I think only files have __file__, modules don't. Don't the latter have __path__? On mobile now, can't check. Surely bunch of dupes for "where's my module".
I have written java client and python server communicating over SSL. I used SSLSocket class for both python and java. When I read general description of how SSL works, I realized that in most implementation (say browsers), client creates a session key and sends it to the server. Further explanation works using session key. But when I read docs of java/python classes, it does not say anything like this. The question is does those classes implement the session key under the hood and use it, or I have to generate them explicitly?
It's a shame that How to convert any word into an integer in Python is so informally specified, because in the past I've needed to reversibly convert a (byte) string to a unique int, so it would be nice to have a canonical post for the problem.
IIRC my solution was something like to_int = lambda b: sum([x<<(i*8) for i,x in enumerate(b)]), with the reverse being to_str = lambda x: bytes((x >> (i*8))%256 for i in range(int(1+(math.log(x,2**8)))))
... Might have a fencepost error in that log calculation there.
Not really feeling inclined to write an answer for that post, since the hash solution got accepted. Which has about as much practical utility as return random.randint(1, 2**64) if you ask me
In [29]: f"{int.from_bytes('cabbage'.encode('utf-8'), 'little'):x}"
Out[29]: '65676162626163'
In [30]: "".join(f"{b:x}" for b in 'cabbage'.encode('utf8')[::-1])
Out[30]: '65676162626163'
I have a bad feeling that there isn't one, because from_bytes isn't reversible, because several different bytes objects can be converted to zero, in particular the empty byte string and any byte string composed only of repetitions of "\0"
Which is also a failing of my own handmade approach
Why not? Can't you zero-pad bits of the bytes, and then concatenate the result and get your int? Then if you write your int in binary you know you have to cut it up every 8th place
doesn't the fact that the number is a concatenation of hex already do that?
Ex. If we use the protocol "a variable-length header indicating the number of bytes, followed by a number representing the values of those bytes" then you could construct an integer that corresponds to "a header indicating the message is 4 bytes long, followed by a body of 200 bytes", then that would either be considered a "syntax error" for having too many characters, or the last 196 bytes would simply be ignored
3 upvotes and accepted answer for someone providing a dictionary to lookup values in a Numpy array. dict(enumerate(array_of_unique_values)). What's better array_of_unique_values[0] or dict(enumerate(array_of_unique_values))[0]. My apologies, its just frustrating to see how votes go sometimes.
I wonder if this protocol would work: take the int.from_bytes() value, and prefix it with a "1" bit followed by however many "0" bits is necessary to make log(result, 256) == len(original_string)+1
Except for the empty string, which continues to map to 0
Wow, my arithmetic is awful. If I want 256 separate values, that's from 1 to 256. Maybe I can pretend my range was upper-exclusive, being a Python dev and all..
Or, hmm, maybe that would map every string to a unique int, but not vice versa, since having a leftmost byte of anything other than 0b1 would be a syntax error
import itertools
def slow_to_int(b):
b = tuple(b)
idx = 0
for i in itertools.count():
for seq in itertools.product(range(256), repeat=i):
if seq == b:
return idx
idx += 1
result = slow_to_int(b"\0\0\0")
print(result, hex(result))
Which is horribly slow for any byte string of practical size but it at least can give some insight about the structure of the results
"" maps to 0. "\0" maps to 0x1. "\0\0" maps to 0x101. "\0\0\0" maps to 0x10101. "\0\0\0\0" maps to 0x1010101. I assume this pattern continues.
A faster implementation might look like: construct a 0x10101...01 value corresponding to the "\0" filled string that has the same length as your input string. Then take int.from_bytes(your_input_string), and... XOR them together? Something like that.
C:\Users\Kevin\Desktop>test.py
b'' maps to 0x0
b'\x00' maps to 0x1
b'\x01' maps to 0x0
b'\x02' maps to 0x3
b'\x03' maps to 0x2
b'\x04' maps to 0x5
b'\x05' maps to 0x4
C:\Users\Kevin\Desktop>test.py
b'' maps to 0x0
b'\x00' maps to 0x1
b'\x01' maps to 0x2
b'\x02' maps to 0x3
b'\x03' maps to 0x4
b'\x04' maps to 0x5
b'\x05' maps to 0x6
b'\x06' maps to 0x7
Looks like sum(1 << i*8 for i in range(len(b))) + int.from_bytes(b, "little") first fails when b equals b'\x00\x01'. We would prefer it to return 0x102, but it returns 0x201
I guess it's not too hard. You can reconstruct the 0x10101...01 value by inspecting the size of the integer, then you can subtract to find the from_bytes result. Then you do magic to it to get the byte sequence (stripped of any leading \0s if it had them), then you un-strip the \0s
"reconstruct the 0x10101...01 value by inspecting the size of the integer" may be more complicated than I intimated, since a one-element byte can turn into either a one byte int or a two byte int. In particular, b"ÿ" maps to x100
And it's not just "the lexicographically-last byte object of length N has N+1 bytes instead of N". bytes([255,0]) maps to a three byte int, and so does bytes([255,1]), and so does bytes([255,2])... etc
Probably you could just iterate up through the (0, 1, 0x1, 0x101, 0x10101) sequence until you find the largest one that's smaller than your number, but I'd hate to use a loop if a closed-form solution exists
I mean, you can construct an 0x10101..01 value of a given length in a reasonably efficient fashion. What's hard is determining the correct length given your number
To rephrase my "drift" concern: call a byte object "askew" if it is N elements long, but maps to an integer larger than N bytes. There is only one askew byte object of length 1. There are ~256 askew byte objects of length 2. I suspect there are 256**2 askew byte objects of length 3.
My fear was that at larger sizes, there may be byte objects of length N that have int representations of length N+2 or larger. Which means you couldn't trivially recover the size of the byte object from the size of the int.
But thinking about it, I don't think this is actually possible. Even though the drift increases exponentially, the number of numbers representable with N bits also increases exponentially. So it balances out, so askew byte objects should only ever be off by one.
At some point it makes sense to throw up your hands and say "on second thought, let's just construct a bijection between the non-negative integers and strings that don't have trailing null terminators"
(yeah, yeah, now you're thinking "bytes are not strings and you should not assume that their use case is similar to strings; having trailing \0s is perfectly valid for bytes and any algorithm that can't handle that is a nonfunctional algorithm")
@Kevin I'm only mildly annoyed, since it's easy enough to use int.to_bytes. And bytes.hex() is a nice compensation.
Thank goodness for silly FGITW questions. :) Of my last 3 questions, one I answered in a couple of minutes with a "Pythonic" loop using enumerate on a product. Another does a breadth-first search of a JSON object to analyse its branching structure. And my most recent one is a recursive generator that produces anagrams. The FGITW answer scored 5 upvotes, the other two are still sitting on zero. Oh well.
Speaking of values, the other day I was reminded of this cute quip. Niklaus Wirth, creator of Pascal, Algol W, Modula, etc, joked that because Europeans pronounce his name properly ("VEER-t"), while Americans pronounce it as "nickel's worth", he is called by name in Europe and called by value in America.
Maybe all of the previous "i am getting following errors" questions have been deleted, so the title wasn't a dupe... assuming the dupe title check doesn't look at deleted questions.
Not sure how hard I should dog Python Base64 encoding adds random letters to string for more information about their problem, since it's working on their machine now (despite the self-answer not changing all that much)
Most likely they'll just reply "haha idk this new version just works and the old one just didn't :-)" then I guess I'll close as can no longer be reproduced
Hey @DSM. The other day I mentioned writing code to find stapled intervals. My algorithm is semi brute force, but not as bad as that OP's approach, and it can find solutions for small intervals pretty quickly, just doing a search on every interval.
But I enhanced it using Tim Peter's version of a postponed sieve to look for prime gaps >= the interval size, and only searching in those intervals, which gave a 10x speed increase, although in my tests I was only searching for numbers <50 million.
80% chance there's already something in itertools that does what my last_before function is doing, but also handles corner cases better and has a pine-fresh scent
cbg, before I consult on SE, I was wondering if anyone could take a look at this serialization scheme (I don't want to get shot down for my 0 knowledge of proper serialization)
I'm trying to perform serialization on a inheritance hierarchy, and it's kind of bothering me. I know I could do something like super(B,b).__dict__ = a.__dict__, but it just doesn't feel right.
Pretty sure my innermost lambda g: isn't necessary but I'm not going to try too hard to optimize jokey code
Half serious implementation of itertools.last(g): {1:x for x in g}[1]
Combine with PM's serious suggestion for a 75% serious solution
>>> last_before = lambda g, cond: {1: x for x in itertools.takewhile(lambda y: not cond(y), g)}[1]
>>> last_before(range(10), lambda x: x > 5)
5
@OneRaynyDay Don't know much about inheritance but I'm concerned that your .json files can only store one object apiece. What if the user wants to serialize ten A's at once?
Sometimes when I serialize things, I take a page out of __repr__'s book and package the data in such a way that you could pass it into the type's constructor and get an object equal to the original.
So if, say, Point has a constructor __init__(self, x, y):, I would serialize it as a tuple, (self.x, self.y). Then I can write my deserializer as return Point(*json.load(f))
I don't want to serialize everything into disk. My objects aren't as simple as Point. They have many complex objects like giant numpy arrays
some of which are computed during runtime so you shouldn't ever really serialize them, rather start the model at the initial point and let it generate that data itself
otherwise you end up with a giant, uninterpretable mess of junk on your hard disk
Mercy is not paperclips, therefore they will not have it
Still just throwing random ideas around, but I wonder if it would be useful to have a non-staticmethod version of deserialize which updates the attributes of self with the deserialized data, rather than returning a new object
Then B.deserialize could call A.deserialize, passing itself as a parameter, so both A and B's deserializers operate on the same object
@DSM Thanks! There's some interesting & useful info at oeis.org/A090318 and oeis.org/A194585 but some of the info at the 2nd link is a bit confusing. Or maybe it's just downright wrong. :)
Question about when to use inheritance. I have a class that wraps some data, and has some attributes/properties for that data and methods to process it. now I want to make a new class that turns that data into something conceptually pretty different, so it should be a new class (?). I want to keep most of the attributes but I don't need the methods. Is this a good place to use inheritance or should I just copy the properties in my new class's init?
This time last year I wrote a program to download chat transcripts & view them in the terminal. I just had a quick look at it, and it ignores those ZERO WIDTH thingies, since they didn't hurt anything.
@CalumYou can you have the data and attributes/properties as one class and have two processing classes that extend that with their independent sets of methods?
Other possibilities: 1) just use the existing class everywhere. 2) make a plain-old-data class with no methods, and make two classes that both inherit from it; one with your existing methods, and one with the methods you're about to write
I have a homemade Point class that I use for all manner of geometry-related code, and 50% of the time what I really need is not a point but a Vector, but conceptually they have the same attributes (x, y, and z) and most of the same methods (overriding addition and such) so I haven't bothered to separate them
@MoxieBall i'm trying to think how this would work. i guess the problem is that I want to do processing in sequence. So it would be make data ClassA that sets all the properties, and then use inheriting ClassB() and ClassC() that have their own methods? What if I want ClassD() that works on ClassB() and ClassC()? inheriting here seems like ClassD() now has all of B and C's methods that it doesn't need
The tricky decision is what to do if the two classes only have some attributes in common, but not all. A Dog and a Closet both have a "volume" and "coat" attribute, but they have many other things not in common, and you would not want them to be anywhere close to one another on the inheritance tree
It sounds like maybe you need a processor class that doesn't inherit from the data class, and that has methods that take an instance of the data class and return a processed instance, so you can chain them
this sounds like a "has a" or "uses" relationship more than an "is a"
Ok that actually does help a lot. yeah D is not really "one of" B or C, so inheriting would be weird. and yes keeping track of what attributes actually make sense where is part of the headache!
hi I need help with a piece of code i'm trying to built
i don't think its that important to post a question for it so i'll just ask here
from time import sleep as t from subprocess import run as r r('', shell=True) print('\n Terminating program\n\n '+'\033[34;1m'+'\u25A1'*15+'\033[15D', end='') for ex in range(15): print('\u25A0', end='') t(1) print('\x1b[0m') exit()
when i run that instead of changing the empty boxes to filled one by one it waits for 15sec and replaces them all at once