« first day (2685 days earlier)      last day (2270 days later) » 
00:00 - 18:0018:00 - 00:00

6:00 PM
Ah, see, you need a perpendicular port and then you can send two bytes simultaneously if you polarize them first.
 
DSM
(taps mike) Is this thing on?
 
@Kevin LOL
What is Mike on?
 
mike = microphone
 
@noumenal It may be constructive to share the code you used to get b'Ii\xf3\xa9' from 65536
 
google "is this thing on"
 
6:01 PM
Are we talking semicardioids?
 
no wait, if you google that you'll find a Pink song
 
@Kevin Good point!
 
DSM
Alex the rock star is ready to wow the crowd with his hip brand of radical rap-rock-metal fusion.
 
@AndrasDeak Or this bad boy A Computer Handbook for Late Bloomers
 
import xdrlib
p = xdrlib.Packer()
x = 3.14
p.pack_float(x)
p.get_buffer()
# <--Output
p.reset()
# <--Empty for next packing
#Replace x with the number suggested by DSM
 
6:06 PM
If you're saying "when I pack the float 65536.0, I get a value containing more than two bytes; therefore, it is incorrect that you can store 65536 different values in two bytes", I think there's a missing step in your proof there.
 
wim
yaml users, I wrote a drop in replacement for PyYAML last night which doesn't destroy dict orderings. If that interests you, pip install oyaml and import oyaml as yaml.
 
@Kevin I was packing 2*pi / (65536-1)
 
>>> p.pack_int(65535)
>>> p.get_buffer()
b'\x00\x00\xff\xff'
 
I was wrong about the number of bytes. DSM checked me on that.
 
I think this is more representative
 
6:08 PM
@Kevin Yes!
 
I think DSM was recommending something like p.pack_int(int(your_angle * (65536-1) / (2*pi)))
 
Hmm, what's the difference...
 
pack_float vs pack_int?
 
I'm not sure what I am asking honestly. I guess your_angle must be in radians?
 
Yeah. If it's in degrees then you'd do p.pack_int(int(your_angle * (65536-1) / (360)))
 
6:19 PM
Oh wait... this is so smart. The 65536-1 actually determines the byte precision!?
 
Pretty much
 
that's DSM for you :P
 
wim
@Arne sounds like a job for @pytest.mark.parametrize
 
And minus one is to make room for sign bit?
 
There shouldn't be a sign because you need to be in the range of [0, 360) or [0, 2*pi) before packing
 
6:22 PM
Hmm, I can only have half of that because I need to be able to represent -3.14 as well
 
I'd guess minus one because the largest integer on n bytes is 2^n - 1
 
So basically:

p.pack_int(int(your_angle * (2 ^ byte_resolution - 1) / (2 * math.pi)))
 
but I'd have to write this down to be sure
35 mins ago, by DSM
Unless there's some unmentioned constraint or relaxation of constraints (e.g. you don't actually need to encode both -pi and pi, you're happy for pi and -pi+epsilon), or you need to make sure you hit 0 exactly (which is the sort of thing I'd want), why wouldn't you just map 0 to -pi and then have every increment be 2*pi / (65536-1)?
 
Oh, if you need to distinguish pi from negative pi, I don't know how you'd do that
 
"map 0 to -pi" probably involves a shift by pi
take your angle -> shift by pi -> count the number of increments
 
6:25 PM
I guess 4*pi will do it
 
don't "guess"
and to decode, take -pi and add increment*number_of_increments
 
@AndrasDeak I'm running examples in the background as we speak. "Hypothesize" would have been a better word.
 
a bit better
the best is to formalize what you want to do on paper
cargo cult math will kick you in the butt with edge cases
 
Fancy words appeal to Andras' inner scientist
 
@AndrasDeak I very much agree with you. I lack the analytical skills however.
 
6:27 PM
@Aran-Fey sssssh don't let them know :P
 
Hmm, it wouldn't be too crazy to choose a range that's slightly larger than your actual range. Like, pretend you need to map [-4, 4) to two byte ints, and then you can store both pi and negative pi at the expense of only a small amount of precision that you probably didn't need anyway
You'll still need to shift all the values so they're all non-negative, in any case
 
wim
also at the expense of beauty and elegance
 
will no one think of the children?!
 
wim
Just choose [-pi, pi) or (-pi, pi]
half-open interval
 
that also happens to be what DSM suggested
 
wim
6:31 PM
redesign anything that cares about the difference between pi and -pi
 
import math

def signed_radian_to_small_int(f):
    f += 4
    return int(f * (2**16 - 1) / 8)


def small_int_to_signed_radian(x):
    f = float(x) * 8 / (2**16 - 1)
    return f - 4

val = -math.pi
x = signed_radian_to_small_int(val)
print(x)
print(hex(x))
print(small_int_to_signed_radian(x))

#result:
#7031
#0x1b77
#-3.1417105363546196
Converting from small int to bytes object of length 2: left as an exercise to the reader
 
(Not exactly Python, but that's what I'm coding in)
Is it a good idea to unit test a function that returns X with some probability Y by running it a million times and checking that the average number of times X is returned falls within some range of Y?
If not, is there another way to unit test something like that?
 
Relevant:
39
Q: Unit-testing of inherently random/non-deterministic algorithms

KeithSMy current project, succinctly, involves the creation of "constrainably-random events". I'm basically generating a schedule of inspections. Some of them are based on strict schedule constraints; you perform an inspection once a week on Friday at 10:00AM. Other inspections are "random"; there are ...

 
the law of large numbers might help with that
 
Accepted answer suggests either seeding the RNG so the test covers the interesting cases in a known finite number of loops, or mocking out the RNG entirely so that it only returns numbers that cause interesting cases
Running a million times seems to be recommended against simply because you might get unlucky and not hit any of the interesting cases after a million tries
But, hmm, that's more for verifying that corner cases work, rather than verifying anything about the average behavior of the function
Verifying that the answers fit some kind of distribution seems... Hard.
 
6:44 PM
exactly
 
Like "professionals get paid six figures to do this" hard
 
Yeah, I have tests for some corner cases (including 0%, 100%), suppose I can add another test to check that a very small percentage eventually shows up, but that indeed doesn't say much about the distribution.
 
You could start by looking at the average. Assuming your function generates random numbers with a given distribution, that's a first test it should pass. But then you should check every higher moment of its samples to make sure it's what it's supposed to be. After all a uniform and a normal distribution can both have an average of 0.
 
Some of the other answers do dip a toe into this area, so those are worth a read
 
("you're function" wty)
 
6:46 PM
Does anyone else hate seeing lower case i's in questions where it should be I? Ive been editing some questions today and they are all over the place!
 
@ZackTarr we hate that but also we hate suggested edits that only capitalize the is. It's not easy:) I hope you try to fix everything when you suggest such edits
and by everything I mean title, tags, capitalization, grammar, clarity, defluffing, formatting (and whatever I forgot about)
 
Being able to unilaterally make edits was such an important event for me because then I could make frivolous spelling and grammar fixes without bothering anyone
 
I try to yes. Those just bug me a lot for some reason.
 
I wish every forum let me edit other people's posts.
 
If its only i's I move on and let it bug me for the next few minutes. Until I find another new question to fix things on.
 
wim
6:49 PM
An interesting question. I had a test that needed to do something like this once, and here's how I handled it
 
@AndrasDeak Doesn't looking at the average have the same problem? The average might not be correct at any given point in time, so you need to check within a range, so you can get unlucky and it can be outside the range, no?
 
@NotThatGuy that's where the law of large numbers and statistics comes into play
 
wim
@pytest.mark.timeout(2)
def test_proxy_choices_cover_the_range(monkeypatch):
    monkeypatch.setitem(config, 'proxy', 'the-test[1-2]-proxy:[8881-8883]')
    all_proxies = {
        'the-test1-proxy:8881',
        'the-test1-proxy:8882',
        'the-test1-proxy:8883',
        'the-test2-proxy:8881',
        'the-test2-proxy:8882',
        'the-test2-proxy:8883',
    }
    seen_proxies = set()
    while seen_proxies != all_proxies:
        seen_proxies.add(get_s3_client().proxy)
 
Lifetimes ago when I frequented the cplusplus dot com forums, there was a guy who would prepend all of his questions with upside down question marks. It annoyed me very much. His only justification was "Spanish is my first language and I decided to bring '¿' over from there". I ended up writing a user script that filtered them all out of the page.
 
for a given number of samples you can judge how close the result should be to the average
this is a conceptually different problem from "you actually need to test 'every' moment of your distribution"
 
wim
6:51 PM
I'm not actually testing the distribution is uniform, but it's similar to your problem.
 
you need to 1. test its moments, and 2. the testing is a non-trivial thing in itself
 
wim
this test has an unbounded loop, but it will fail if it takes more than 2 seconds.
I'm not saying this is the best, or even a good way. Just what was "good enough" for what I wanted to test.
 
but of course we're talking about stochastics so the statements you're allowed to make are "this sample average should be closer to the true average than epsilon with <large> probability", and you can never be sure that if that fails your code is wrong
 
@Kevin I was thinking about that for this issue. Have a script to go through and replace all lower case I's with no letters beside it unless its like ive, im and so on.
 
you can probably reduce statistical fluctuations to a point where you can live with the chance of a false positive/negative
@ZackTarr unformatted code with i as a variable?
@Kevin that sounds a bit chauvinistic
I mean their behaviour
 
6:54 PM
@Kevin
My adaptation of your solution. Pushing down the envelope. Given an integer resolution of pi:

import math

SIGNIFICANT_DIGITS = 3 # 3.14
MY_PI = int(math.pi * SIGNIFICANT_DIGITS - 1)
MY_TAU = 2 * MY_PI

def signed_radian_to_small_int(f):
f += MY_PI
return int( f * (2**16 - 1) / (2 * MY_TAU) )

def small_int_to_signed_radian(x):
f = float(x) * (2 * MY_TAU) / (2**16 - 1)
return f - MY_PI

val = -math.pi
x = signed_radian_to_small_int(val)
print(x)
print(hex(x))
print(small_int_to_signed_radian(x))
 
I may very well have migrated away from C++ just because of that one guy.
 
@AndrasDeak Very true. Cant take that into account easily.
 
@Kevin it's their loss \o/
¡We love you more!
 
I was in my larval stage then so it wasn't that much of a loss for them
 
I suppose the next question would then be whether I should try to write such a unit test in an interview setting where I was asked to write the RNG with tests. I guess "fails with some probability" would be looked down on by some, but others may expect a distribution test.
 
6:57 PM
@Kevin Thanks for your help!
 
Good luck with your project :-)
 
Thanks all! :-)
 
cbg.
 
Maybe I should generate a random number to tell me what to do.
 
wim
@NotThatGuy Tough question. You'd have to gauge whether the interviewer is a hard-core unit test guy, or has a more practical approach to testing.
 
6:59 PM
@NotThatGuy How is this not your default strategy already?
 
If you don't want to rely on pseudo-RNGs check out www.random.org
 
decay random is best random
 
Hey, just pointing this out but nothing is truly random...
 
many things are as far as we know :P
 
wim
time spent worrying about whether your pseudo rng is random enough is best spent elsewhere
 
7:02 PM
unless it's a multiplicative congruential PRNG
 
random.org uses the movement of particles in the atmosphere, to create random numbers.
 
wim
there's some other site that uses a wall of lava lamps
 
@wim Less "random enough", and more "basically looks like it works". Still hard to test in a non-manual way (manually I can just run it and go "see, that looks about right").
 
It is a sort of seed for the psudo-random number gen
 
Ah, I thought that was the radioactive one fourmilab.ch/hotbits
 
7:03 PM
@wim LOL, never would have guessed
 
@wim that's what cloudflare or something uses. Yup: blog.cloudflare.com/…
 
wim
fun fact, the big primes needed by implementations of ssh key pairs sometimes aren't even prime
they are just "probably prime"
 
RNG rankings: particle decay > atmospheric eddies > lava lamps > PRNG > return 4;
 
Wow, I thought they only used lava lamps to hypnotize people.
 
wim
and the consequences if you use a number that isn't actually prime, is pretty much nothing
 
7:05 PM
@Kevin I like the allusion to xkcd
 
@NotThatGuy it will probably also depend on your distribution. Testing a shifted uniform vs testing an upside-down-double-cheesecake distribution matters
@wim with the invention of quantum computers it's pretty much a moot point anyway, since the robots are going to kill us all
 
The rumor that quantum robots are going to kill us is both an exaggeration and not.
That was an allusion to Schrödinger... a bit farfetched perhaps
 
Nah he's pretty entrenched in the pop science collective unconscious
Especially for a STEM audience you can assume everyone knows about him and his cat
 
@Kevin And yet they don't...
 
by "everyone". Kevin means "everyone in this room"
 
7:10 PM
Only because you put them in a box and won't let them out
 
Bonsai kittens anyone?
 
Hey could I get a syntax check(I am getting a sqlite3.ProgrammingError, trust me the data base has everything it needs):
 
@Mr.Zeus Shoot!
 
import sqlite3
from os import _exit
import traceback
#Make a connection to the data base
conn = sqlite3.connect("discord_roles.db")
#Create a cursor
curser = conn.cursor()
#That is a joke name...
while True:
    #Conntinully take input and add role with the name from the input
    try:
        #Get input for the name of the role
        role = input("Enter role name: ")
        #Try to add the role
        curser.execute('insert into roles(role_name) values("?")', (role,))
        #If it passes the exeute, print the name of the role, thus confirming that the role has been added
Sorry that was bigger than I thought.
 
@Mr.Zeus What's the error?
 
7:13 PM
> #Conntinully
 
Here is the full one:
Traceback (most recent call last):
  File "/Users/MrZeus/Desktop/PY_FOLDER/SQLITE_PY/Disord_DB/JOTHEPRO_Public/role_adder.py", line 15, in <module>
    curser.execute('insert into roles(role_name) values("?")', (role,))
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied.
 
@Mr.Zeus This line: curser.execute('insert into roles(role_name) values("?")', (role,))
@Mr.Zeus There seems to be a positional argument left out after "role".
 
Yes @noumenal I know it is on that line
@AndrasDeak I will try that
 
(role,) is valid syntax, incidentally.
 
nevermind I don't want to guess
 
7:15 PM
@Mr.Zeus Just wanted to save others from counting... :-)
 
@noumenal :P did not mean that in a rude way, sorry
 
"you're missing something after the comma and before the paren" is not necessarily true because the way it is is how you pass a one-element tuple as an argument
 
looking at the docs should give you example inputs for such bindings because I know I've seen this come up before
 
@AndrasDeak Another episode of #ContextMatters "upside-down-double-cheesecake distribution matters"! Of course it does. That's partly why Marie Antoinette lost her head.
 
@AndrasDeak YAY, you were right!
 
7:17 PM
ah, cool
 
Thanks all!
 
but please edit that #Conntinully :P
 
You got it!
Wish I could stay longer, rhubarb!
 
rbrb
 
rbrb
 
wim
7:37 PM
@AndrasDeak With the disdain of engineers that theoretical physicists are afflicted by, they probably won't get their quantum computing stuff working for decades ... :P
oh new spotmini video yesterday (trigger warning: robot abuse)
 
awwwwwwwww :'(
 
@wim I have to say it is pretty cool that the little robot doesn't give up
 
question: why are we so set on making robots walk? Why not wheels or something?
 
increased creepy factor
then again there is a wheely boston dynamics robot, and it's also scary
 
7:53 PM
wheels make many tasks much more difficult
 
Otherwise we'd have evolved with wheels
 
@AndrasDeak maybe evolution isn't finished with us
 
it's not really possible for it to be finished
 
@AndrasDeak One could say we've evolved the ability to use wheels at will: rollerblades, cars, etc
 
unless everything is dead
 
7:56 PM
@excaza +1 for the positive outlook ;)
 
is that a Doppler experiment?
or Doppler + that-thing-that-interfering-close-frequencies-do beat?
 
wim
@toonarmycaptain learning != evolution
 
@excaza neat, thanks
 
wim
8:03 PM
evolution is just a fact, something you can watch under a microscope in a petri dish
 
allegedly
no, wait, "just a theory"
 
wim
it's a fact as much as gravity
(which makes it quite funny when people say "I don't believe in evolution" when they mean to say "I don't believe in natural selection as origin of mankind")
 
they probably don't believe in evolution either
if species change it's harder to rationalize that humans never have, so it's easier to deny the entire phenomenon
but I agree that these kind of people usually lack the knowledge to distinguish between the two
 
cbg
 
cbg
 
8:13 PM
Can I input the precision of an old-style format string as a variable? E.g.

'%.<var>f'%(2.7222)
 
7
Q: variable number of digit in format string

Emanuele PaoliniWhich is a clean way to write this formatting function: def percent(value,digits=0): return ('{0:.%d%%}' % digits).format(value) >>> percent(0.1565) '16%' >>> percent(0.1565,2) '15.65%' the problem is formatting a number with a given number of digits, I don't like to use both '%' operato...

has both .format & printf style answers
 
@excaza Thanks!
 
why are you using an old-style format string?
it's now doubly obsolete
 
@AndrasDeak Because I'm too lazy importing the future when calling an external closed source legacy library that has not been updated since 2.7.
 
booo (well, not for you, for them :P)
wait, what would you import after 2.7?
.format should be readily available in 2.7 and there's no future import for f-strings, right?
 
8:19 PM
Oh.... oopsie
 
so shift your excuses ;D
 
Wrong excuse, sorry! I'm not in the loop. :D
@AndrasDeak Done. It's all bananas. rbrb
 
rbrb
 
AD with that detective hat :D
 
wim
8:39 PM
>>> 7 str.format 5    # still not working.  Python 3 sucks!
2
 
Logging? I think I read that you should use %s in logging to defer string interpolation until the logging level has been checked, but maybe I just made it up that .format() doesn't do the same
 
wim
You should use % in logging, but not for the reason that you wrote.
There is no good reason why they couldn't have used "this {} template" style in logging messages.
 
I found something unusual with Spyder/iPython yesterday through using logging that I now need to look up. Within Spyder, it's perfectly ok to have logger = logging.handlers.RotatingFileHandler (it even auto-completes for me) but running python my_script.py with exactly the same version of Python will fail; it only accepts from logging.handlers import RotatingFileHandler. Any ideas what Spyder/iPython is doing here in the broader sense?
 
"will fail" how?
 
8:52 PM
AttributeError on logging.handlers
Let me confirm exact error
 
perhaps you need to import logging.handlers in addition to logging. I don't think anything magical should be going on here
 
Mmm, it's a bit tougher to ensure I'm using exactly the same Anaconda version of Python on my home PC but it was absolutely repeatable at work as it's the only installation and I confirmed versions
It's still repeatable in P2.7 though
 
no MCVE
 
import logging

a = logging.handlers.RotatingFileHandler('something.txt')
Fine in Spyder
 
4 mins ago, by Andras Deak
perhaps you need to import logging.handlers in addition to logging. I don't think anything magical should be going on here
 
8:59 PM
Just did a kernal restart, so nothing left in iPython. import logging alone is sufficient for it to work
 
no handlers in the __all__ in /usr/local/lib/python3.6/logging/__init__.py
 
Exactly, so that was my initial musing... what is Spyder/iPython doing to resolve that
 
@roganjosh yes but that's not python, that's something spyder does. I guess you could consider it a kind of magic, but a very weak one
it might pre-emptively load every submodule of a module
damn, that's not it
I got double confused \o/
try import urllib; print(dir(urllib))
 
I mean, it is convenient within Spyder but it created issues when I tried to use the code elsewhere. It's not a major issue, just I have to be careful with auto-complete suggestions
 
yeah, this is a bug being hidden
 
9:05 PM
@AndrasDeak ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'error', 'parse', 'request', 'response']
 
now try that in a script outside spyder
plus edit the message with backticks to remove dunderbold...
 
err, hold on
Only dunder methods outside of Spyder
 
okay, so it's consistent with what I said
 
Seems so, yes
 
odds are you can disable this somewhere in spyder
Although googling I don't find any signs of that. But it's mentioned in several places that a large part of the scipy stack and matplotlib might get imported by ipython
 
9:12 PM
Before I do that, if I could pick your brain one last time. The Spyder approach seems better from these examples; is there a pending train-wreck within Spyder worse than AttributeError when porting a script out?
@AndrasDeak yes, and you can get it to load numpy and pandas into namespace by default for any script
 
@roganjosh what do you mean?
It's just that modules don't pull import their submodules for a reason. Some modules (like scipy) have pretty large submodules, and you might not benefit from importing all of them all the time.
either way I wouldn't rely on spyder's behaviour, considering that the resulting python programs will be broken
 
@AndrasDeak that answered my question. So the reason it's not default behaviour in python is simply to stop loading unnecessary modules, Spyder foregoes that for simplicity
 
that would be my guess, though I can't know for sure
but if you take your script, run it in a vanilla python shell and it dies, that tells you that it's broken
the solution is to import those things yourself anyway
if spyder pre-imports those submodules, later manual imports will be no-ops
 
@AndrasDeak the auto-complete blurs the lines a bit if you're not overly familiar with the module. Since Spyder isn't something like Pycharm, it makes sense they might add these convenience approaches internally since most scripts probably never run outside of the IDE anyway
 
Yeah, I guess. You can always run your program outside your IDE every once in a while if you expect such bug hiding shenanigans
as I said, you could try looking into the preferences to see if it can be disabled
 
9:24 PM
@AndrasDeak at least now I know it does this (surprised this was my first encounter) so I know how to fix them without the "What on Earth?! <hands waving>" debug approach :P
 
there's a slight chance that ipython itself does this, but I don't think so (since mine doesn't)
 
DSM
9:45 PM
Three separate people have tried, and failed, to write a working set consolidation function on this question which I thought should be closed as a dupe but it turns out should be closed as a library request.
 
I saw that question and I was like huh.... DSM working hard shooting down people's attempt
 
 
2 hours later…
11:40 PM
Is it possible to mock a field named name in a MagicMock? It looks like MagicMock already has its own name member.
although maybe it isn't as minimal as possible
 
It seems you can just do bar.func.return_value.name = 'file.pdf'
But that's one of those workarounds that "works on my machine" and isn't backed up by any documentation
 
let me try that
yup, looks like that works, thanks @Aran
 
11:59 PM
hey guys, I was thinking of making a graphic on a django website that I am making to visualize where everybody signs up from. Is this doable from just logging the accessing IP addresses. I also saw Geolocation requests are doable inside html itself...though I'd be worried about users being turned off by the location request and atm this is just for rough visualization of signup patterns so I dont need it to be super precise since a prompt that might scare off some people off.
 
00:00 - 18:0018:00 - 00:00

« first day (2685 days earlier)      last day (2270 days later) »