## Coding: Fleeting Thoughts

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

Jplus
Posts: 1721
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

### Re: Coding: Fleeting Thoughts

I think the quote from Wildcard, "(A implies B) implies (B implies A)", nicely illustrates what people are confused about when they find the logical meaning of "implies" counterintuitive. The statement would be provable if "implies" meant the bi-implication (A if and only if B). With the actual meaning (if A then B), the statement is not sound. I think many people do interpret "implies" as the bi-implication, although I would disagree about that being the "standard" meaning in colloquial English (or Dutch). Then again, I'm not a native speaker of English.

Also, @Wildcard: that you can find rows in a truth table where the statement as a whole is true, does not mean that the statement is valid in a logical sense. (A -> B) -> (B -> A) is never sound or valid according to formal logic.

Jplus wrote:Edit: English also has a word for XOR. Can you identify it?

Spoiler:
unless
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

Flumble
Yes Man
Posts: 2265
Joined: Sun Aug 05, 2012 9:35 pm UTC

### Re: Coding: Fleeting Thoughts

ucim wrote:let x be c and b.
let y be c and ~b.
Both are TRUE (under the original statement a -> b)

I don't get your mindbrain here. Using propositional logic I get x and y = (c and b) and (c and ¬b) = c and (b and ¬b) = c and false = false, which contradicts your statement that they are both true.

korona
Posts: 495
Joined: Sun Jul 04, 2010 8:40 pm UTC

### Re: Coding: Fleeting Thoughts

ucim wrote:
korona wrote:I cannot follow your reasoning at all here. Why should c imply b or ~b?
It's not that c (which is ~a) "implies" anything. It's that (in the logic world), c is compatible with b, and is also compatible with ~b, because only a (aka ~c) carries any real implication about b.

Let's break that down a bit.

I assume we only talk about propositional logic. For predicate logic some things must be adjusted but they can be made work. We say that A ⊨ B if every model of A (i.e. every satisfying truth assignment) is also a model of B. This operator is called semantic consequence / entailment.

Now certainly
a -> b ⊭ c ∧ b (because a = 0, b = 0 is a model of the LHS but not of the RHS)
a -> b ⊭ c ∧ ~b (because a = 0, b = 1 is a model of the LHS but not of the RHS)

I don't really understand what you mean by "is compatible with". "is compatible with" aka "a and b CAN be true at the same time" cannot be expressed in propositional logic. In modal logic you could formulate that as ◇(a ∧ b). ◇ is the "it is possible that" operator.

As a side note: The claim that (a ∧ (a -> b)) -> b (which is the modus ponens) should be tautology (i.e. every truth assignment is a model for this formula) already fixes the first two rows of the truth table: 0 -> 0 = 1 and 0 -> 1 = 1.
Last edited by korona on Fri Feb 05, 2016 11:57 am UTC, edited 1 time in total.

Yakk
Poster with most posts but no title.
Posts: 11129
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

### Re: Coding: Fleeting Thoughts

ucim wrote:
Yakk wrote:The question? The answers? The comments? Please be more clear than "post", link contains dozens if not hundreds of stack overflow posts.
I was referring to the highest rated answer, which was the first answer after the OP.

You can directly link it via the "share" link under it btw.
It said:
Boolean implication A implies B simply means "if A is true, then B must be true". This implies (pun intended) that if A isn't true, then B can be anything. Thus:

False implies False -> True
False implies True -> True
True implies False -> False
True implies True -> True

This can also be read as (not A) or B - i.e. "either A is false, or B must be true".

While it is logically correct, surely they could have used a better word than "implies".... many years ago when this was first set up. "Is consistent with" would be a good choice.

i do not see how "is consistent with" helps in any shape or form in this discussion. It is not a drop in for implies anywhere I can see. "A is consistent with B" -- that does not read to me as saying "if B is false, A must be false", as a possible interpretation of your statement.

Please be more explicit. I do not understand what your point is.
I (Note also that simply saying "False implies False" is meaningless, because each instance of False refers to a different (false) statement.

Meaningless? It isn't completely explicit, but the variable assignment to the values lines up first to first and second to second. As in "We can turn left or right. We'll end up in Chicago or New York. Which way to turn?" -- this reasonably strongly implies that left is Chicago and right is New York in English. To make it stronger, you add respectively.
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.

ucim
Posts: 6895
Joined: Fri Sep 28, 2012 3:23 pm UTC

### Re: Coding: Fleeting Thoughts

The crux of it is (quoted from Wildcard):

Code: Select all

`    A         B         if A then B    True      True      True    True      False     False    False     True      N/A (therefore, True)    False     False     N/A (therefore, True)`

N/A (therefore, True) is, afaict, arbitrary. I assume it was adopted as a convention to make certain logical things "neat", in the same manner that 1 is prime (or isn't prime, I forget which).

Anyway... there are two different relations to look at: (note: {} is not intended as set notation)

One is:
{set of (A's truth value AND B's truth value)} -> A {relation} B

The other is:
A {relation} B -> {set of (A's truth value AND B's truth value)}

where {relation} could be either of "implies", "is consistent with", "if..then" and the question becomes what to do with "unknown".
"If it's raining, then there are clouds".
"It's not raining".
Are there clouds? Unknown. Not-raining and clouds are "consistent with each other". They are possible, but not required.

Yakk wrote:i do not see how "is consistent with" helps in any shape or form in this discussion. It is not a drop in for implies anywhere I can see
No, it is not a drop-in for implies. It has a different meaning, one which I contend is a better English translation for the logical "implies" truth table, where N/A is defaulted to TRUE.

So, in the evolution of logic, why was N/A defaulted to TRUE?

Jose
Order of the Sillies, Honoris Causam - bestowed by charlie_grumbles on NP 859 * OTTscar winner: Wordsmith - bestowed by yappobiscuts and the OTT on NP 1832 * Ecclesiastical Calendar of the Order of the Holy Contradiction * Heartfelt thanks from addams and from me - you really made a difference.

Jplus
Posts: 1721
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

### Re: Coding: Fleeting Thoughts

It is not N/A, there was never a need to make a convention on whether A -> B should be true or false when A is false. There are two ways to look at it, both of which have to do with contradiction.

The first way to look at it is based directly on the semantics of implication as a connective. The only way to contradict "if A, then B" is by making A true and B false.

Code: Select all

`A      B      if A, then B----------------------------true   true   finetrue   false  contradiction!false  true   finefalse  false  fine`

The second way to look at it is to consider that logical consequence (operator: ⊢, "turnstile") behaves exactly like material implication (->) at a metalevel. In a proof, the turnstile separates the premises from the conclusion. We read A ⊢ B as "given the premise A, we may conclude B".

Now, a well known catch in logic is that you can derive anything you want from contradiction. For example, if I use A && ~A as a premise, I can use that to prove all kinds of wildly bizarre things. Just as logical consequence is the metaversion of material implication, contradiction is the metalevel of false (in fact both are often written as ⊥; some people might even want to maintain it's the same thing). So it is no surprise that a material implication is always true when the antecedent is false.
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

Flumble
Yes Man
Posts: 2265
Joined: Sun Aug 05, 2012 9:35 pm UTC

### Re: Coding: Fleeting Thoughts

I think the reasoning behind (⊥→A) always being true is that all the statements in a proof/argument must be true in order to have a sound proof.
So in order to let B take all values (i.e. you can't derive anything about B) from the premises {¬A, A→B} (i.e. "A does not occur" and "if A occurs, B must occur") and to have a sound argument/proof (i.e. you can't derive your mom's phone number), an implies-operation must always be true if the left hand is false.

Also because of the axiom in logic that A∨¬A, so "unknown"-values can't exist.

Also very much note that the "truth" here is assigned to the whole expression A→B (given ¬A), not to B.
Logically, if it's a given that "Santa Clause isn't real" (premise: ¬A), I can state that "if Santa Clause is real, then it rains pancakes" (conclusion: A→B). No matter whether it rains pancakes, my (material) implication can't be false. Furthermore, you can't derive whether it's raining pancakes from these statements. ( (¬A)∧(A→B) ⊬ B and (¬A)∧(A→B) ⊬ ¬B )

Alternatively, if it's a given that it's raining pancakes, I can make the same statement without being wrong. But as a consequence, I can't derive whether Santa Clause exists either.
But if Santa Clause is real and it's not raining pancakes, well, then my implication is wrong. (And given that I must be right, I'll have to make it rain pancakes or kill Santa. )

moiraemachy
Posts: 190
Joined: Wed Jan 04, 2012 9:47 pm UTC

### Re: Coding: Fleeting Thoughts

English words don't map very well to material equivalence and material implication. The English phrases "imply", "is equivalent to", etc express constraints on possible truth values, so they are closer to logical relationships.

Material connectives in plain English are better expressed by "and" (⋅), "or" (⊕) and "and/or" (+). I have no idea why. Example:

A = "the sky is green"
B = "rats are mammals"

A -> B ≡ (!A)+(B)
A -> B = true (in our world)

"the sky is green implies rats are mammals" sounds false; "the sky isn't green and/or rats are mammals" sounds true.

"A implies B" suggests that there is a thread of deduction that proves B and requires A. You can't say "A implies B" if it is easy to show that B is always true even if A is false.

Wildcard
Candlestick!
Posts: 253
Joined: Wed Jul 02, 2008 12:42 am UTC
Location: Outside of the box

### Re: Coding: Fleeting Thoughts

chridd wrote:What system does that work on? On my computer (Mac OS X), that sort of thing won't work—#! scripts can't call other #! scripts that way. (Attempting to execute such a script from the shell causes the shell it's executing from to interpret the script; attempting to execute it from a C program gives "Exec format error". This is different from the behavior if the interpreter simply doesn't exist.) From http://linux.die.net/man/2/execve it looks like it won't work on Linux either ("The interpreter must be a valid pathname for an executable which is not itself a script.").

You're right, actually. On further inspection it doesn't work. But it's still there in the code...

...and the init script for the app, as it turns out, has the following hardcoded into it to start up the app:

Code: Select all

`cd /path/to/the/directory && ./shebang ./js/script.js --options`

There's no such thing as a funny sig.

phlip
Restorer of Worlds
Posts: 7573
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia
Contact:

### Re: Coding: Fleeting Thoughts

F->x isn't "N/A" and it's not being "defaulted" to anything...
phlip wrote:The motivation makes more sense when you consider "for all" conditions... for instance, a statement of "all A's are B's", or "if anything is an A, then it is a B" can be formalised as "for all x, A(x) -> B(x)". The only thing that can be a counterexample is an x where A(x) is true but B(x) is false, so that's the only case where A(x) -> B(x) is false. All other cases are acceptable.

As has been pointed out, in many contexts, this "for all" condition is exactly how "implies" is used in English... "A implies B" being mapped to "for all situations x, A(x) -> B(x)".

Eg," if there's smoke, there's fire" gets read as "for all spacetime positions x, if there is smoke near x, there is fire near x"... "∀x. S(x) -> F(x)". The equivalence is easiest seen by considering what could count as a counterexample to each - for both, the only counterexample is a time and place that has smoke, but no fire.

Code: Select all

`enum ಠ_ಠ {°□°╰=1, °Д°╰, ಠ益ಠ╰};void ┻━┻︵​╰(ಠ_ಠ ⚠) {exit((int)⚠);}`
[he/him/his]

Wildcard
Candlestick!
Posts: 253
Joined: Wed Jul 02, 2008 12:42 am UTC
Location: Outside of the box

### Re: Coding: Fleeting Thoughts

Jplus wrote:I think the quote from Wildcard, "(A implies B) implies (B implies A)", nicely illustrates what people are confused about when they find the logical meaning of "implies" counterintuitive. The statement would be provable if "implies" meant the bi-implication (A if and only if B). With the actual meaning (if A then B), the statement is not sound. I think many people do interpret "implies" as the bi-implication, although I would disagree about that being the "standard" meaning in colloquial English (or Dutch). Then again, I'm not a native speaker of English.

Also, @Wildcard: that you can find rows in a truth table where the statement as a whole is true, does not mean that the statement is valid in a logical sense. (A -> B) -> (B -> A) is never sound or valid according to formal logic.

My head was in a whirl when I finished writing that post. I'm not surprised it's invalid in formal logic.

If (if my water bottle is full, then you have an egg on your head), then (if this cookie is made of peanut butter, then (if the moon is made of green cheese, then 2+2 = 5)).

Obviously a true statement, right?
There's no such thing as a funny sig.

Jplus
Posts: 1721
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

### Re: Coding: Fleeting Thoughts

Prove it.
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

Flumble
Yes Man
Posts: 2265
Joined: Sun Aug 05, 2012 9:35 pm UTC

### Re: Coding: Fleeting Thoughts

Spoiler:
Given that the moon is not made of green cheese (green cheese implies it would shine green, but it's only ever white, yellow or red), the whole statement is already true.

Moo
Oh man! I'm going to be so rebellious! I'm gonna...
Posts: 6441
Joined: Thu Aug 16, 2007 3:15 pm UTC
Location: Beyond the goblin city
Contact:

### Re: Coding: Fleeting Thoughts

Anyone here have experience with the C# MongoDB driver? I cannot for the life of me get a distinct selection out of my DB. Details below, any advice appreciated. The driver seems to have changed a lot in the most recent version (v4) so everything Google turns up seems to be no longer valid. Or at least I can't get it to even compile, nevermind work.
Spoiler:
I have a collection of documents, each consisting of an ObjectID "_id", string "email" and binary data "Data". I want to select distinct values or failing that, group by email address.
Initialization code:

Code: Select all

`public IMongoCollection<MongoProfileEntity> MongoCollection { get; set; }---------var mongoClient = new MongoClient(connectionString);var db = mongoClient.GetDatabase(databaseName);var MongoCollection = db.GetCollection<MongoProfileEntity>(collectionName);`

Everything else works. Returning all data, find by email, find by id.
Using MongoCollection.Distinct gives me issues with the types of arguments I try to pass but I can't really understand what it needs from me. Plugging in some copypasta code from all over the internet using Group similarly just doesn't seem to work. And I haven't used Linq and am loathe to change the other working parts of this but if needs must, so be it. I did half-heartedly try it but similarly with no luck.

edited to add: I am a complete mongo noob and can barely formulate a coherent query in Mongo Chef on the data itself. I assumed it would be easy enough to "translate" SELECT DISTINCT. Wroooong.
Proverbs 9:7-8 wrote:Anyone who rebukes a mocker will get an insult in return. Anyone who corrects the wicked will get hurt. So don't bother correcting mockers; they will only hate you.
Hawknc wrote:FFT: I didn't realise Proverbs 9:7-8 was the first recorded instance of "haters gonna hate"

Posts: 1419
Joined: Sat Mar 07, 2009 11:33 am UTC
Location: ᘝᓄᘈᖉᐣ
Contact:

### Re: Coding: Fleeting Thoughts

CFT: I'm getting back into C++11 for a university assignment in which you're free to choose your programming language (C or FORTRAN are recommended -- but C++11 has a lot of neat features which I think are useful for it). I think I can get a small speed boost if I can generate an array like this:

Code: Select all

`constexpr std::size_t x, D; // Set at compile-timeconstexpr std::size_t f(std::size_t y, std::size_t d); // Some constexpr functionconstexpr std::array<std::size_t, D> = { f(x, 0), f(x, 1), ..., f(x, D-1) };`
...but it seems that's not really a reasonable thing to do until C++14, at least not in a way the course instructors will understand what I'm doing. Which is fine, but then I lose the ability to get support from them, which sucks.

Oh well, I can get away with generating it once at run-time.

ETA: actually, never mind, I don't even need this, really.

jestingrabbit
Factoids are just Datas that haven't grown up yet
Posts: 5967
Joined: Tue Nov 28, 2006 9:50 pm UTC
Location: Sydney

### Re: Coding: Fleeting Thoughts

I'm learning javascript using "eloquent javascript" which you can find on the web. There's an exercise where you want to convert a list (ie an object with a "value" and "rest" property, with rest being either another list or null) to an array (ie the standard javascript array object). Question: Why does this code fail?

Code: Select all

`function listToArray(alist){  if(!alist){    return [];  } else {    var anarray = listToArray(alist.rest);    return anarray.unshift(alist.value);  }}`

The error that node throws up tells us that anarray doesn't have the unshift method. But surely anarray is an array and therefore has the unshift method. What's going on? I'm interested in why this fails, not how to write something that works (which I've already done).
ameretrifle wrote:Magic space feudalism is therefore a viable idea.

hotaru
Posts: 1045
Joined: Fri Apr 13, 2007 6:54 pm UTC

### Re: Coding: Fleeting Thoughts

jestingrabbit wrote:Question: Why does this code fail?

Code: Select all

`function listToArray(alist){  if(!alist){    return [];  } else {    var anarray = listToArray(alist.rest);    return anarray.unshift(alist.value);  }}`

The error that node throws up tells us that anarray doesn't have the unshift method. But surely anarray is an array and therefore has the unshift method. What's going on? I'm interested in why this fails, not how to write something that works (which I've already done).

what does unshift return?
hint: not an array.

Code: Select all

`factorial = product . enumFromTo 1isPrime n = factorial (n - 1) `mod` n == n - 1`

jestingrabbit
Factoids are just Datas that haven't grown up yet
Posts: 5967
Joined: Tue Nov 28, 2006 9:50 pm UTC
Location: Sydney

### Re: Coding: Fleeting Thoughts

Thanks, that was a lot easier than I thought it would be, I should have worked it out myself.
ameretrifle wrote:Magic space feudalism is therefore a viable idea.

Xanthir
My HERO!!!
Posts: 5426
Joined: Tue Feb 20, 2007 12:49 am UTC
Contact:

### Re: Coding: Fleeting Thoughts

And note that you can set a breakpoint on that line in your code, then see what the types are. It would have been immediately obvious when you saw that "anarray" had the value "1". ^_^
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))

jestingrabbit
Factoids are just Datas that haven't grown up yet
Posts: 5967
Joined: Tue Nov 28, 2006 9:50 pm UTC
Location: Sydney

### Re: Coding: Fleeting Thoughts

Xanthir wrote:And note that you can set a breakpoint on that line in your code, then see what the types are. It would have been immediately obvious when you saw that "anarray" had the value "1". ^_^

Yeah, I tried console.logging stuff and just couldn't work out what was happening. I should have put it at the top of the function and seen what was in the args on each call, I think I might have got it then.
ameretrifle wrote:Magic space feudalism is therefore a viable idea.

bentheimmigrant
Dotcor Good Poster
Posts: 1366
Joined: Fri Apr 25, 2008 9:01 pm UTC
Location: UK

### Re: Coding: Fleeting Thoughts

We have an unattended PC that needs to be logged in all the time, but to keep up with our IT policy also needs to automatically install Windows updates. Which means it will restart, and need to be manually logged in again.

I think I'm going to write something in VB.net, to write the date and time to a text file (specified in a config file) on a mapped drive, then make a scheduled task to run it every 30 minutes. This seems trivial, even at my skill level.

I could then write another mini program to check the text file occasionally from another PC, and make sure the time is <31 minutes old. I think I would rather this was a service though, so it doesn't have to be scheduled, and would be easy to install on any PC on the network.

I feel like I'm about to bite off more than I can chew with the service, though.
"Comment is free, but facts are sacred" - C.P. Scott

speising
Posts: 2367
Joined: Mon Sep 03, 2012 4:54 pm UTC
Location: wien

### Re: Coding: Fleeting Thoughts

you can let the unattended pc perform a task at a shutdown/reboot/logoff event. such as sending an email.

Breakfast
Posts: 117
Joined: Tue Jun 16, 2009 7:34 pm UTC
Location: Coming to a table near you

### Re: Coding: Fleeting Thoughts

Moo wrote:Anyone here have experience with the C# MongoDB driver? I cannot for the life of me get a distinct selection out of my DB. Details below, any advice appreciated. The driver seems to have changed a lot in the most recent version (v4) so everything Google turns up seems to be no longer valid. Or at least I can't get it to even compile, nevermind work.
Spoiler:
I have a collection of documents, each consisting of an ObjectID "_id", string "email" and binary data "Data". I want to select distinct values or failing that, group by email address.
Initialization code:

Code: Select all

`public IMongoCollection<MongoProfileEntity> MongoCollection { get; set; }---------var mongoClient = new MongoClient(connectionString);var db = mongoClient.GetDatabase(databaseName);var MongoCollection = db.GetCollection<MongoProfileEntity>(collectionName);`

Everything else works. Returning all data, find by email, find by id.
Using MongoCollection.Distinct gives me issues with the types of arguments I try to pass but I can't really understand what it needs from me. Plugging in some copypasta code from all over the internet using Group similarly just doesn't seem to work. And I haven't used Linq and am loathe to change the other working parts of this but if needs must, so be it. I did half-heartedly try it but similarly with no luck.

edited to add: I am a complete mongo noob and can barely formulate a coherent query in Mongo Chef on the data itself. I assumed it would be easy enough to "translate" SELECT DISTINCT. Wroooong.

What's the error you're getting when you do the .Distinct()?

bentheimmigrant
Dotcor Good Poster
Posts: 1366
Joined: Fri Apr 25, 2008 9:01 pm UTC
Location: UK

### Re: Coding: Fleeting Thoughts

speising wrote:you can let the unattended pc perform a task at a shutdown/reboot/logoff event. such as sending an email.

That was my first thought, but the unattended PC doesn't have an associated email account. I suppose I could create a gmail account for it, and set up a client etc., but half the point of this PC is it only performs certain core functions (e.g. hosting network software licences), and doesn't have additional ways to go wrong. But mostly, I just want to see if I can do this.
"Comment is free, but facts are sacred" - C.P. Scott

Flumble
Yes Man
Posts: 2265
Joined: Sun Aug 05, 2012 9:35 pm UTC

### Re: Coding: Fleeting Thoughts

bentheimmigrant
Dotcor Good Poster
Posts: 1366
Joined: Fri Apr 25, 2008 9:01 pm UTC
Location: UK

### Re: Coding: Fleeting Thoughts

No, because the IT policy includes having a non-administrator, password protected account. (In order to avoid flouting that completely by leaving the PC logged in, it's set to lock its screen automatically.)
"Comment is free, but facts are sacred" - C.P. Scott

Yakk
Poster with most posts but no title.
Posts: 11129
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

### Re: Coding: Fleeting Thoughts

Sure. So you have a script that logs in remotely with a hard-coded password on another system.
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.

bentheimmigrant
Dotcor Good Poster
Posts: 1366
Joined: Fri Apr 25, 2008 9:01 pm UTC
Location: UK

### Re: Coding: Fleeting Thoughts

But then I need to know which other system will be logged in to run that from (if I follow what you're saying), which I don't.
"Comment is free, but facts are sacred" - C.P. Scott

eviloatmeal
Posts: 571
Joined: Thu Dec 11, 2008 9:39 am UTC
Location: Upside down in space!
Contact:

### Re: Coding: Fleeting Thoughts

Sounds like what you need is a giant network of computers[1] all trying to remotely log into each other in order to keep each other from logging out.
*** FREE SHIPPING ENABLED ***

Riddles are abound tonight

Moo
Oh man! I'm going to be so rebellious! I'm gonna...
Posts: 6441
Joined: Thu Aug 16, 2007 3:15 pm UTC
Location: Beyond the goblin city
Contact:

### Re: Coding: Fleeting Thoughts

Breakfast wrote:What's the error you're getting when you do the .Distinct()?
Thanks for responding; the user eventually decided they don't want distinct data. I wasn't getting an error, as I couldn't get the code to build. I couldn't figure out the right arguments to pass the Distinct where it wasn't complaining about them. I know this is uselessly vague now but as I said, no longer needed. Thanks again though.
Proverbs 9:7-8 wrote:Anyone who rebukes a mocker will get an insult in return. Anyone who corrects the wicked will get hurt. So don't bother correcting mockers; they will only hate you.
Hawknc wrote:FFT: I didn't realise Proverbs 9:7-8 was the first recorded instance of "haters gonna hate"

bentheimmigrant
Dotcor Good Poster
Posts: 1366
Joined: Fri Apr 25, 2008 9:01 pm UTC
Location: UK

### Re: Coding: Fleeting Thoughts

eviloatmeal wrote:Sounds like what you need is a giant network of computers[1] all trying to remotely log into each other in order to keep each other from logging out.

What could possibly go wrong?

As it stands, I was correct. The timestamp program was trivial, and the service was too much. Currently working on a notification tray alternative.
"Comment is free, but facts are sacred" - C.P. Scott

Rysto
Posts: 1460
Joined: Wed Mar 21, 2007 4:07 am UTC

### Re: Coding: Fleeting Thoughts

Here's a lesson I really need to learn: if you're doing a quick one-off test, you are usually better off add 5 lines of code to the application rather than wasting hours trying to figure out how to configure it to do what you need.

Thesh
Posts: 6598
Joined: Tue Jan 12, 2010 1:55 am UTC

### Re: Coding: Fleeting Thoughts

Interesting problem:

You have an arbitrary length stream of bytes, you want to read from this stream and output numbers between 0 and 2 such that each number is equally likely given a truly random input. You want to guarantee that your program halts no matter what the input, but your function must be stateless and dependent entirely on the byte stream.

The normal solution would be to read, say, a 4-byte unsigned integer and check if it is in the range 0-2^32-2, and then keep fetching until you find one that is, but that isn't guaranteed to halt (i.e. every input can be all ones).

I came up with this as the solution:

Code: Select all

`randmod3(s)   r = get_byte(s)   if (r == 255):      r = get_byte(s)&127      if (r == 127):         r = (get_byte(s)&127)+1   return r%3`

Now I have to think about how to turn this into a generic function that works for any integer range.
Summum ius, summa iniuria.

Flumble
Yes Man
Posts: 2265
Joined: Sun Aug 05, 2012 9:35 pm UTC

### Re: Coding: Fleeting Thoughts

so there's a 85/256+1/256*43/128+1/256/128*42/128 = 0.33335... chance of getting a 0, a 85/256+1/256*42/128+1/256/128*43/128 = 0.33332... chance getting a 1 and the same for a 2.

mathematically it's impossible to go from powers of 2 to a multiple of 3, i.e. 2^a=3*b. You have to grab more bytes from the stream while the result isn't within a certain multiple of 3 (either by discarding a few outcomes or accumulating the whole stream).

Thesh
Posts: 6598
Joined: Tue Jan 12, 2010 1:55 am UTC

### Re: Coding: Fleeting Thoughts

That's true for a fixed-length input, my solution is not a fixed length input. It works, I tested it using this script:

Code: Select all

`r = [0,0,0]for i in range(256):    if (i==255):        for j in range(128):         if (j==127):            for k in range(128):               r[(k+1)%3] += 1         else:            r[j%3] += 1    else:        r[i%3] += 1print r#prints [170, 170, 170]`

Note that there's nothing special about those numbers; you can accomplish the same thing reading only one byte of input (first read two bits discarding one of the outputs, then three discarding one of the outputs (giving one output a higher probability), then three again not discarding anything (giving two outputs with a higher probability, evening out when combined with the previous part).
Summum ius, summa iniuria.

jareds
Posts: 436
Joined: Wed Jan 03, 2007 3:56 pm UTC

### Re: Coding: Fleeting Thoughts

You're not weighting the probabilities correctly. You're counting {0x00} as having the same probability as {0xff00,0xff80} and even the same as {0xff7f00,0xff7f80,0xffff00,0xffff80}. However, the probability of getting the something from the first set is 2-8, the probability of something from the second is 2-15, and the probability of something from the third is 2-22.

Code: Select all

`r = [0,0,0]for i in range(256):    if (i==255):        for j in range(128):         if (j==127):            for k in range(128):               r[(k+1)%3] += 1         else:            r[j%3] += 128    else:        r[i%3] += 128*128print r# prints [1398186, 1398059, 1398059]`

Over a denominator of 256*128*128, you get the exact probabilities that Flumble stated.

Your goal is impossible as he said. A bounded length is equivalent to a fixed length for these purposes; your algorithm has the same probability distribution as the following:

Code: Select all

`randmod3(s)   r1 = get_byte(s)   r2 = get_byte(s)   r3 = get_byte(s)   if (r1 == 255):      r1 = r2&127      if (r1 == 127):         r1 = (r3&127)+1   return r1%3`

jaap
Posts: 2094
Joined: Fri Jul 06, 2007 7:06 am UTC
Contact:

### Re: Coding: Fleeting Thoughts

There have been some threads about generating one or more uniform random numbers in one range when given a random number generator with a different range, e.g. a 6-sided die using only coin flips.

Here is the most recent one in Mathematics:
viewtopic.php?f=17&t=113023

Here is the older one in Logic Puzzles:
viewtopic.php?f=3&t=75684

Thesh
Posts: 6598
Joined: Tue Jan 12, 2010 1:55 am UTC

### Re: Coding: Fleeting Thoughts

Yeah, I stayed up drinking until 3am last night; was a bit out of it.
Summum ius, summa iniuria.

Posts: 3072
Joined: Mon Oct 22, 2007 5:28 pm UTC
Location: Beaming you up

### Re: Coding: Fleeting Thoughts

Why not just read 3 bytes for every random number? Then you have an even range to run the modulus on and all is right in the world again.
<quintopia> You're not crazy. you're the goddamn headprogrammingspock!
<Cheese> I love you

jaap
Posts: 2094
Joined: Fri Jul 06, 2007 7:06 am UTC
Contact:

### Re: Coding: Fleeting Thoughts

headprogrammingczar wrote:Why not just read 3 bytes for every random number? Then you have an even range to run the modulus on and all is right in the world again.

2^24 is not divisible by 3 so either you have a non-uniform distribution, or you will have to discard one of those 2^24 cases and accept that there is a 1 in 2^24 chance that more than 3 input bytes are needed to generate the random number and that theoretically there is no bound on the number of input bytes needed.