Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Soricidus
Oct 21, 2010
freedom-hating statist shill

Malcolm XML posted:

there's a lot of dumb tricks in the itertools documentation

yeah and it's dumb as all hell, why the gently caress are they putting code in the documentation instead of just ... in the module, so you can use it without having to copy-paste from the documentation?!

"batteries included*

* light bulbs sold separately"

Adbot
ADBOT LOVES YOU

ahmeni
May 1, 2005

It's one continuous form where hardware and software function in perfect unison, creating a new generation of iPhone that's better by any measure.
Grimey Drawer

MononcQc posted:

What kind of aptitude test? Like "are you skilled enough" tests or "what's your personality type" tests? both are terrible but for various reasons.

Pairing is time-consuming, but I don't hate it. lt lets you have a look at who you'll work with and how they are. You're interviewing them as much as they interview you in there, so try to avoid stuff like "let me show them how great I am" and try to make it more like your everyday work interaction with them. Otherwise they'll be observing you, but you won't be getting your part back.

the last test I did was full on logic and problem solving and I just barely failed the programmer cutoff but not the DevOps cutoff (heh), this one seems to be personality + some logic but it's still creepy

the working together I can understand but the whole process when I have an existing job is weird, it feels like "taking time off to go do another job" is some sort of weird betrayal and ugh gently caress the entire job hunting spiel

Malcolm XML
Aug 8, 2009

I always knew it would end like this.

Soricidus posted:

yeah and it's dumb as all hell, why the gently caress are they putting code in the documentation instead of just ... in the module, so you can use it without having to copy-paste from the documentation?!

"batteries included*

* light bulbs sold separately"

:shrug:

MononcQc
May 29, 2007

ahmeni posted:

the working together I can understand but the whole process when I have an existing job is weird, it feels like "taking time off to go do another job" is some sort of weird betrayal and ugh gently caress the entire job hunting spiel

yeah definitely. Usually companies that do that do understand they're gonna be cutting themselves off of anyone in any sort of precarious position or who doesn't have a job with lots of flex time. They assume it's worth losing plenty of great candidates for more certainty with those that will accept to spend their time there.

They should at the very least cover expenses, and if they're any nice, offer some form of compensation/contract for the trial period.

Notorious R.I.M.
Jan 27, 2004

up to my ass in alligators

MononcQc posted:

Python code:
dict = {"a": "b", "c":"d", "e":"b"}
flipped = {}
for k,v in dict.items():
    if not v in flipped:
        flipped[v] = []
    flipped[v].append(k)

I think this is the best approach. Python provides defaultdicts which get around the awkwardness of having to check whether a dict key is defined. The constructor for defaultdict will automatically substitute in an empty element of the type that is passed each time a new key is referenced.

Python code:
from collections import defaultdict
dict = {"a": "b", "c":"d", "e":"b"}
flipped = defaultdict(list)
for k,v in dict.items():
    flipped[v].append(k)

Merdifex
May 13, 2015

by Shine
How implement monads in python

fart simpson
Jul 2, 2005

DEATH TO AMERICA
:xickos:

Merdifex posted:

How implement monads in python

ok
Python code:
import types

###### Base Monad and @do syntax#########

class Monad:
    def bind(self, func):
        raise NotImplementedError

    def __rshift__(self, bindee):
        return self.bind(bindee)

    def __add__(self, bindee_without_arg):
        return self.bind(lambda _ : bindee_without_arg())

def make_decorator(func, *dec_args):
    def decorator(undecorated):
        def decorated(*args, **kargs):
            return func(undecorated, args, kargs, *dec_args) 
        
        decorated.__name__ = undecorated.__name__
        return decorated
    
    decorator.__name__ = func.__name__
    return decorator

def make_decorator_with_args(func):
    def decorator_with_args(*dec_args):
        return make_decorator(func, *dec_args)
    return decorator_with_args

decorator           = make_decorator
decorator_with_args = make_decorator_with_args

@decorator_with_args
def do(func, func_args, func_kargs, Monad):
    @handle_monadic_throws(Monad)
    def run_maybe_iterator():
        itr = func(*func_args, **func_kargs)

        if isinstance(itr, types.GeneratorType):
            @handle_monadic_throws(Monad)
            def send(val):
                try:
                    # here's the real magic
                    monad = itr.send(val) 
                    return monad.bind(send)
                except StopIteration:
                    return Monad.unit(None)
                
            return send(None)
        else:
            #not really a generator
            if itr is None:
                return Monad.unit(None)
            else:
                return itr

    return run_maybe_iterator()

@decorator_with_args
def handle_monadic_throws(func, func_args, func_kargs, Monad):
    try:
        return func(*func_args, **func_kargs)
    except MonadReturn, ret:
        return Monad.unit(ret.value)
    except Done, done:
        assert isinstance(done.monad, Monad)
        return done.monad

class MonadReturn(Exception):
    def __init__(self, value):
        self.value = value
        Exception.__init__(self, value)

class Done(Exception):
    def __init__(self, monad):
        self.monad = monad
        Exception.__init__(self, monad)

def mreturn(val):
    raise MonadReturn(val)

def done(val):
    raise Done(val)

def fid(val):
    return val

##### Failable Monad ######

class Failable(Monad):
    def __init__(self, value, success):
        self.value   = value
        self.success = success

    def __repr__(self):
        if self.success:
            return "Success(%r)" % (self.value,)
        else:
            return "Failure(%r)" % (self.value,)    

    def bind(self, bindee):
        if self.success:
            return bindee(self.value)
        else:
            return self

    @classmethod
    def unit(cls, val):
        return cls(val, True)

class Success(Failable):
    def __init__(self, value):
        Failable.__init__(self, value, True)

class Failure(Failable):
    def __init__(self, value):
        Failable.__init__(self, value, False)

def failable_monad_examle():
    def fdiv(a, b):
        if b == 0:
            return Failure("cannot divide by zero")
        else:
            return Success(a / b)

    @do(Failable)
    def with_failable(first_divisor):
        val1 = yield fdiv(2.0, first_divisor)
        val2 = yield fdiv(3.0, 1.0)
        val3 = yield fdiv(val1, val2)
        mreturn(val3)

    print with_failable(0.0)
    print with_failable(1.0)

###### StateChanger Monad #########

class StateChanger(Monad):
    def __init__(self, run):
        self.run = run

    def bind(self, bindee):
        run0 = self.run

        def run1(state0):
            (result, state1) = run0(state0)
            return bindee(result).run(state1)

        return StateChanger(run1)

    @classmethod
    def unit(cls, val):
        return cls(lambda state : (val, state))

def get_state(view = fid):
    return change_state(fid, view)

def change_state(changer, view = fid):
    def make_new_state(old_state):
        new_state    = changer(old_state)
        viewed_state = view(old_state)
        return (viewed_state, new_state)
    return StateChanger(make_new_state)


def state_changer_monad_example():
    @do(StateChanger)
    def dict_state_copy(key1, key2):
        val = yield dict_state_get(key1)
        yield dict_state_set(key2, val)
        mreturn(val)

    @do(StateChanger)
    def dict_state_get(key, default = None):
        dct = yield get_state()
        val = dct.get(key, default)
        mreturn(val)

    @do(StateChanger)
    def dict_state_set(key, val):
        def dict_set(dct, key, val):
            dct[key] = val
            return dct

        new_state = yield change_state(lambda dct: dict_set(dct, key, val))
        mreturn(val)

    @do(StateChanger)
    def with_dict_state():
        val2 = yield dict_state_set("a", 2)
        yield dict_state_copy("a", "b")
        state = yield get_state()
        mreturn(val2)

    print with_dict_state().run({}) # (2, {"a" : 2, "b" : 2})

###### Continuation Monad #########

class ContinuationMonad(Monad):
    def __init__(self, run):
        self.run = run

    def __call__(self, cont = fid):
        return self.run(cont)        

    def bind(self, bindee):
        return ContinuationMonad(lambda cont : self.run(lambda val : bindee(val).run(cont)))

    @classmethod
    def unit(cls, val):
        return cls(lambda cont : cont(val))

    @classmethod
    def zero(cls):
        return cls(lambda cont : None)
    
def callcc(usecc):
    return ContinuationMonad(lambda cont : usecc(lambda val : ContinuationMonad(lambda _ : cont(val))).run(cont))
    
def continuation_monad_example():
    from collections import deque

    class Mailbox:
        def __init__(self):
            self.messages = deque()
            self.handlers = deque()

        def send(self, message):
            if self.handlers:
                handler = self.handlers.popleft()
                handler(message)()
            else:
                self.messages.append(message)

        def receive(self):
            return callcc(self.react)

        @do(ContinuationMonad)
        def react(self, handler):
            if self.messages:
                message = self.messages.popleft()
                yield handler(message)
            else:
                self.handlers.append(handler)
                done(ContinuationMonad.zero())

    @do(ContinuationMonad)
    def insert(mb, values):
        for val in values:
            mb.send(val)

    @do(ContinuationMonad)
    def multiply(mbin, mbout, factor):
        while True:
            val = (yield mbin.receive())
            mbout.send(val * factor)

    @do(ContinuationMonad)
    def print_all(mb):
        while True:
            print (yield mb.receive())

    original   = Mailbox()
    multiplied = Mailbox()

    print_all(multiplied)()
    multiply(original, multiplied, 2)()
    insert(original, [1, 2, 3])()

if __name__ == "__main__":
    failable_monad_examle()
    state_changer_monad_example()
    continuation_monad_example()

ahmeni
May 1, 2005

It's one continuous form where hardware and software function in perfect unison, creating a new generation of iPhone that's better by any measure.
Grimey Drawer

Notorious R.I.M. posted:

I think this is the best approach. Python provides defaultdicts which get around the awkwardness of having to check whether a dict key is defined. The constructor for defaultdict will automatically substitute in an empty element of the type that is passed each time a new key is referenced.

Python code:
from collections import defaultdict
dict = {"a": "b", "c":"d", "e":"b"}
flipped = defaultdict(list)
for k,v in dict.items():
    flipped[v].append(k)

default dicts are probably one of my most used things recently, though usually if im working with someone newer to python i'll use the .setdefault behaviour to be explicit

yippee cahier
Mar 28, 2005

Don't forget dict.get()'s optional default return value if you're pulling crap out of a dict instead of inserting it.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

ahmeni posted:

default dicts are probably one of my most used things recently, though usually if im working with someone newer to python i'll use the .setdefault behaviour to be explicit

Similarly to dict.get, there's also:

Python code:
dict = {"a": "b", "c":"d", "e":"b"}
flipped = {}
for k,v in dict.items():
    flipped.setdefault(v, []).append(k)
I tend to use that form instead of defaultdict.

VikingofRock
Aug 24, 2008




fart simpson posted:

pythonic monadic

:golfclap:

fart simpson
Jul 2, 2005

DEATH TO AMERICA
:xickos:

i found it on google, i didn't write it

VikingofRock
Aug 24, 2008




still cool tho

Dessert Rose
May 17, 2004

awoken in control of a lucid deep dream...
Thanks for recommending Racket as a scripting language. It's perfect for me.

I want to use Clojure there, but the boot times are awful. Racket is super fast and I can save them as text files.

Now I can stop writing poo poo in Ruby because "well i guess some of my other scripts are already Ruby". :toot:

Dessert Rose
May 17, 2004

awoken in control of a lucid deep dream...
ugh what the gently caress are all those capital letters and commas doing in that post

Dessert Rose
May 17, 2004

awoken in control of a lucid deep dream...
lol my ~/bin dir has about equal proportions .sh, .pl and .rb, with a couple .py and .jar for seasoning

Bloody
Mar 3, 2013

good job standardizing

Bloody
Mar 3, 2013

i pretty much never use dictionaries

Blinkz0rz
May 27, 2001

MY CONTEMPT FOR MY OWN EMPLOYEES IS ONLY MATCHED BY MY LOVE FOR TOM BRADY'S SWEATY MAGA BALLS

Bloody posted:

i pretty much never use dictionaries

what do you use instead?

DONT THREAD ON ME
Oct 1, 2002

by Nyc_Tattoo
Floss Finder
wikis

Bloody
Mar 3, 2013

Blinkz0rz posted:

what do you use instead?

lists I guess? idk I don't work with much data in a key Value format I guess

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
i use Properties

Jerry Bindle
May 16, 2003

a global scope dictionary that ANY process can edit

DONT THREAD ON ME
Oct 1, 2002

by Nyc_Tattoo
Floss Finder

Barnyard Protein posted:

a global scope dictionary that ANY process can edit

only well respected, upstanding processes with a history of making well received edits in narrower scopes can edit

raminasi
Jan 25, 2005

a last drink with no ice

Barnyard Protein posted:

a global scope dictionary that ANY process can edit

isn't that how mumps works

The MUMPSorceress
Jan 6, 2012


^SHTPSTS

Gary’s Answer

GrumpyDoctor posted:

isn't that how mumps works

Kinda. "Globals" are arrays (actually b-trees) that are written to persistent storage. You can map globals to particular namespaces to lock them down to only processes running in those namespaces, or you can have them be truly global. Only an rear end in a top hat would use them to store global mutable state, which means that everyone does that of course.

MUMPS globals are intended to be used as the "database" part of the platform, but since they're the only complex data structure available obviously they get repurposed for all sorts of poo poo. So really, they're kinda like a file that is world-modifiable by default but can have permissions applied to them.

Soricidus
Oct 21, 2010
freedom-hating statist shill
is there a mumps to javascript compiler yet

Cybernetic Vermin
Apr 18, 2005

Internet Janitor posted:

It's a K5 limitation, I'm afraid. Many things have been aggressively simplified compared to K4.
There's still a reasonably simple K5 formulation.

No repeat values:
code:
{(.x)!!x}
Group keys with duplicate values into a list in the result:
code:
{(?.x)!(!x)@.=.x}

gah, i hope there are some really good payoffs in k5, because going to zero good k implementations even counting proprietary ones would be very depressing

i get tempted to write an implementation myself now and then. i wrote a pretty substantial semantics specification for q a number of years back, which we used to do a jvm-based db subset in a clean-room fashion, but i rather suspect i wouldn't quite make it through a complete implementation

The MUMPSorceress
Jan 6, 2012


^SHTPSTS

Gary’s Answer

Soricidus posted:

is there a mumps to javascript compiler yet

no but we have an xml library for MUMPS internally. it's bad.

Bloody
Mar 3, 2013

LeftistMuslimObama posted:

no but we have an xml library for MUMPS internally. it's bad.

:stare:

The MUMPSorceress
Jan 6, 2012


^SHTPSTS

Gary’s Answer

Ya, imagine dealing with xml purely by parsing it as text input.

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
alright, i did it: http://forums.somethingawful.com/showthread.php?threadid=3754012

can't really go much worse than my forth thread did.

JawnV6
Jul 4, 2004

So hot ...

LeftistMuslimObama posted:

persistent storage

:allears:

VikingofRock
Aug 24, 2008




Internet Janitor posted:

alright, i did it: http://forums.somethingawful.com/showthread.php?threadid=3754012

can't really go much worse than my forth thread did.

Cool! Good OP.

The MUMPSorceress
Jan 6, 2012


^SHTPSTS

Gary’s Answer

I assume this is because the phrase is redundant? I just meant "disk" vs "in memory".

MeruFM
Jul 27, 2010

LeftistMuslimObama posted:

I assume this is because the phrase is redundant? I just meant "disk" vs "in memory".

maybe he means nothing is truly persistent and life is meaningless

JawnV6
Jul 4, 2004

So hot ...
no, my current headaches are all around writing to persistent storage

there's internal flash, external flash, internal can be sent down the pipeline while external needs to be paged back in, and all this is on a cortex M4 without those fancy things like a "file system" so i'm trying my darnedest to not write a full fledged FS

so LMO, as way down in the muck of MUMPS as you are, there's still a layer of abstraction you're able to rely on that I cant

MeruFM posted:

maybe he means nothing is truly persistent and life is meaningless
this too tho

suffix
Jul 27, 2013

Wheeee!
there's a zillion lightweight file systems for embedded systems
do you have like 2 bytes of ram or something

Bloody
Mar 3, 2013

suffix posted:

there's a zillion lightweight file systems for embedded systems
do you have like 2 bytes of ram or something

still prob enough for the lightestweight fatfs

Adbot
ADBOT LOVES YOU

MeruFM
Jul 27, 2010
at 2 bytes, the sam becomes the ram

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply