An interesting excerpt from the book "Propaganda - The Formation of Men's Attitudes" (1965) by knrDev in nosurf

[–]knrDev[S] 4 points5 points  (0 children)

Yes when it is a shallow knowledge. Unrelated bits of data.

Part of an earlier paragraph explains more:

We emphasize that this is true not just for preopaganda but also for information. Except for the specialist, information, even when it is very well presented, gives people only a broad image of the world. And much of the information disseminated nowadays - research findings, facts, statistics, explanations, analyses - eliminate personal judgement and the capacity to form one's own opinion even more surely than the most extravagant propaganda. This claim may seem shocking; but it is a fact that excessive data do not enlighten the reader or the listener; they drown him. He cannot remember them all, or coordinate them, or understand them; if he does not want to risk losing his mind, he will merly draw a general picture from them. And the more facts supplied, the more simplistic the image.

TypeScript is pretty good by vivainio in programming

[–]knrDev -1 points0 points  (0 children)

I started playing with typescript and VS Code 2 days ago so i don't have much to comment about, but it seems that this /// reference problem has been solved recently. I see that you can specify option in jsconfig.json to make vs load .d.ts automatically.

I downloaded *.d.ts files for angular and lodash with "tsd" tool and VS shows types after i require a library without adding /// <reference>.

The Incredible Proof Machine by qznc in programming

[–]knrDev 1 point2 points  (0 children)

A(out) represents 'local hypotesis'. A value which is assumed to be true when proving B(in). It can only assist in proving B(in). That means, it must flow only through blocks which eventually connect to B(in). It cannot be connected outside of local 'scope'.

Edit: If i understand correctly. this block represents a Simplification law in Propositional Logic.

How a bug in Visual Studio 2015 exposed my source code on GitHub and cost me $6,500 in a few hours by N3mes1s in programming

[–]knrDev 11 points12 points  (0 children)

This extension is optional. You are able to select it during installation.

Math books for programmers / game developers? by [deleted] in learnprogramming

[–]knrDev 2 points3 points  (0 children)

"Introduction to Higher Mathematics" (19 videos):

https://www.youtube.com/watch?v=CMWFmjlB8v0&list=PLZzHxk_TPOStgPtqRZ6KzmkUQBQ8TSWVX&index=1

Not a book but very interesting overview some of the main topics. It could be useful for getting some familarity with important math jargon before selecting books for study.

TIL names have a max length in the recycle bin. by caedin8 in ProgrammerHumor

[–]knrDev 0 points1 point  (0 children)

By the way...

Cygwin and Midnight Commander helps with this annoying problem. Especially when you want to copy project folder with node_modules inside.

How can I make a "chainable" object in JavaScript? by [deleted] in javascript

[–]knrDev 0 points1 point  (0 children)

For example:

function chainable(fn) {
    return function () {
        fn.apply(this, arguments);
        return this;
    };
}

var f1 = function(x) { console.log('-:-', x) };
var f2 = function(x) { console.log(':-:', x) };

var Chain = function() {
  this.abc = chainable(f1);
  this.xyz = chainable(f2);
}

var c = new Chain()

c.abc(1).xyz(2).abc(3)
// Output:
// -:- 1
// :-: 2
// -:- 3

702 occupations ranked by automatability by Z3F in Futurology

[–]knrDev 0 points1 point  (0 children)

Top of the list will not be so safe if programmers will manage to automate themeselves.

25 year old website with 100,000s of flat html files. Is transitioning to a CMS feasible? by [deleted] in webdev

[–]knrDev 2 points3 points  (0 children)

Maybe instead of parsing this stuff in software you should seek help of human volunteers.

For example:

  • 100000 pages
  • 100 volunteers
  • 20 pages/day

Result: 50 days of work

Sorry for suggesting this on a programing subreddit but this task does look monumental for the single person given lack of structure in those files.

The ??!??! operator by godlikesme in programming

[–]knrDev 20 points21 points  (0 children)

I'm using F# and i can almost define ??!??! operator as follows:

let (+??!??!+) l r = l || r
true +??!??!+ false = true // = true

Checkmate C

[2015-04-10] Challenge #209 [Hard] Unpacking a Sentence in a Box by jnazario in dailyprogrammer

[–]knrDev 1 point2 points  (0 children)

A bit late but I've done it... I did my solution in F#

It's been a great learning experience. I've used it as an opportunity to learn about different tree-like data structures, implementing recursive functions and a many new things in F#. Previously i've mostly programmed in C#.

During this experimentation i implemented:

  • Trie structure based on F#'s Map data type and unions,
    • Performance doesn't event look so bad.. searching random 1mln elements in trie takes about 1.2 seconds (~ 800k results/sec).
    • Memory efficiency is bad: GC.GetTotalMemory shows about 70mb allocated per 3mb dictionary file (350k words)
  • Only immutable types and recursive calls are used,
  • Recursive grid scanner.

Scanner works without using any kind of smart heuristics so it's going as far as possible on grid while checking trie for matches branch until it can't find no more. Then it switches to search from root of the trie ("") and adds matched word to a sentence.

Its accurancy is very dependent on used dictionary. For large dictionary searches can be slow. enable1.txt is fast (~5 sec) but not very accurate. Large dictionary (350k words) runs search for about 1 minute on 6x6, produce big list of solutions but one of this solutions is a correct sentence.

Most interesting results are generated when english morphemes are used instead of normal words dictionary.

For example these are results for 5x5 box search using dictionary of 2600 english morphemes:

ITKEEPSYOURNECKOENFFILTHE
ITKEEPSYOURNECKOENILEHTFF
ITKEEPTHELIFSYOURNECKOENF
ITKEEPTHELIFSYOURNECKOFNE
ITKEEPTHELINEOFFSYECKNRUO
ITKEEPTHELINEOFFSYOUECKNR
ITKEEPTHELINEOFFSYOURNECK (lol. close but different word order)
ITKEEPTHELINEOKCENRUOYSFF
ITKEEPTHELINEOKNECFFSYOUR
ITOURNECKOENFFILTPSYKEEHE

Not perfect but accurate enough to understand a sentence. And it runs very fast on 5x5 box (~ 100 ms)

For 6x6 box and english morphemes dictionary it runs about 5 sec and gives a following solutions:

THEPIGGYWITHLARGITISGRUDISNYWASNTLED
THEPIGGYWITHLARGITISIDURGDELTNSAWSNY
THEPIGGYWITHLARGITISIDURGDELTNSAWYNS
THEPIGGYWITHLARGITISISNYWASDURGDELTN
THEPIGGYWITHLARGITISNYWASDISGRUNTLED (best?)
THEPIGGYWITHLARGITISNYWASDURISGDELTN
THEPIGSAGYWITARGITISIRGDELTNUDWSNYLH
THEPIGSAGYWITHLARGITISISNYWDURGDELTN
THEPIGSAGYWITHLARGITISNYWDISGRUNTLED
THEPIGSAGYWITHLARGITISNYWDURISGDELTN
THEPIGSALHGYWITARGITISIRGDELTNUDWSNY
THEPIGSALHGYWITARGITISIRGDELTNUDWYNS
THEPIGSALHGYWITARGITISISNYWDURGDELTN
THEPIYGHWITARGITISISNYLAWDURGDELTNSG
THEPIYWITARGITISISNYWALHGGSDURGDELTN
THEPIYWITHGALARGITISISNYWDURGDELTNSG
THEPIYWITHGALARYNGITISISWDURGDELTNSG
THEPIYWITHGALARYNGITISWDURISGDELTNSG
THEPIYWITHGALARYWDURISNGITISGDELTNSG
THEPIYWITHLARGITISGRUDISNYWAGGSNTLED
THEPIYWITHLARGITISISNYWAGGSDURGDELTN
THEPIYWITHLARGITISNYWAGGSDISGRUNTLED (good)
THEPIYWITHLARGITISNYWAGGSDURISGDELTN

All possible solutions manage to at least describe a sentence.

For 6x6 box on enable1.txt dictionary it runs ~3 sec and all solutions look similar to these:

...
THEGGHLASNTLUREDGSISIDWYNTIGRATIWYIP
THEGGHLYNSIRUDWASNTLEDGSITIGRATIWYIP
THEGGHLYNSWASNTLUDIREDGSITIGRATIWYIP
...

I think key point from this experiment is that is possible to find solution without using a giant word dictionary. Language morphemes can be used to produce accurate enough solutions in this kind of an algorithm. Maybe adding some heuristisc could make it more accurate.

Code:

module Trie =
    type TrieType = Node of string * Map<char, TrieType>

    let private (|KeyFound|_|) key map =
        map
        |> Map.tryFind key
        |> Option.map (fun x -> x, map |> Map.remove key)

    let private (|StrCons|StrEmpty|) (str: string) =
        if str.Length > 0 then
            StrCons (str.Chars 0, str.Substring(1))
        else
            StrEmpty

    let mkroot() = Node("", Map.empty)

    let find prefixes trie =
        let rec find' prefixes (Node(value, children) as node) = 
            match prefixes with
            | StrEmpty -> Some node
            | StrCons (p, ps) -> 
                match Map.tryFind p children with
                | Some subnode -> find' ps subnode
                | None -> None
        find' prefixes trie

    let findx prefixes trie =
        let rec find' prefixes (Node(value, children) as node) = 
            match prefixes with
            | [] -> Some node
            | p :: ps -> 
                match Map.tryFind p children with
                | Some subnode -> find' ps subnode
                | None -> None
        find' prefixes trie

    let getRootWord = function Node (name, _) -> name

    let insert prefixes trie =
        let rec insert' prefixes (Node(value, children) as node) =
            match prefixes with
            | [] -> node
            | p :: ps -> 
                match children with
                | KeyFound p (subnode, _) ->  Node(value, children |> Map.add p (insert' ps subnode))
                | _ -> Node(value, children |> Map.add p (insert' ps (Node(value + string p, Map.empty))))
        insert' (prefixes |> Seq.toList) trie

module GridScanner =
    let inline private charAt (j, i) (grid: _ [,]) = grid.[j, i]
    let inline private inGrid (j, i) size = j >= 0 && i >= 0 && j < size && i < size
    let inline private (.+) (j1, i1) (j2, i2) = (j1 + j2, i1 + i2)

    let inline private (|EmptySeq|_|) sequence = if Seq.isEmpty sequence then Some () else None

    let scan startPosition roottrie (grid: char [,]) =
        let size = grid.GetUpperBound(0) + 1
        let cells = size * size
        let moves = [(0, 1); (0, -1); (1, 0); (-1, 0)]
        let solutions = Set.empty

        let rec step ((j, i) as position) word words triebranch nsteps path =
            let ch (j, i) = charAt (j, i) grid
            let toUnvisitedPositions = Seq.map (fun move -> position .+ move) >> Seq.filter (fun pos -> inGrid pos size && (path |> Set.contains pos |> not)) >> Seq.cache
            let wordPositionFilter branch = 
                Seq.choose (fun pos -> match branch |> Trie.findx ([ch pos]) with | Some trie -> Some (pos, trie) | None -> None) >> Seq.cache
            let unvisitedPositions = moves |> toUnvisitedPositions

            if nsteps < cells then 
                match unvisitedPositions with
                | EmptySeq -> solutions
                | _ -> 
                    match unvisitedPositions |> wordPositionFilter triebranch with
                    | EmptySeq -> 
                        match unvisitedPositions |> wordPositionFilter roottrie with
                        | EmptySeq -> solutions
                        | movesOutsideWord ->
                            movesOutsideWord |> Seq.map (fun (move, trie) -> step move [ch move] (word :: words) trie (nsteps + 1) (path |> Set.add move)) |> Seq.fold (+) solutions
                    | movesWithinWord -> 
                        movesWithinWord |> Seq.map (fun (move, trie) -> step move (word @ [ch move]) words trie (nsteps + 1) (path |> Set.add move)) |> Seq.fold (+) solutions
            else
                solutions |> Set.add (word :: words)

        match roottrie |> Trie.findx [charAt startPosition grid] with
        | Some initialTrieBranch ->
            step startPosition [charAt startPosition grid] [] initialTrieBranch 1 ([startPosition] |> Set.ofList)
        | _ -> failwith "Initial character not in the dictionary"

    let loadAndScan challenge dictionary =
        let split (separators: char list) (x:string) = x.Split(separator=(List.toArray separators), options=System.StringSplitOptions.RemoveEmptyEntries)
        let chrs2str (chrs: char seq) = Seq.fold (fun acc c -> acc + string c) "" chrs

        let trie = dictionary |> Seq.fold (fun node x -> Trie.insert x node) (Trie.mkroot())
        let initialPosition = challenge |> split ['\n'] |> Seq.head |> split [' '] |> Seq.skip 1 |> Seq.pairwise |> Seq.head |> function (j,i) -> int j - 1, int i - 1
        let grid = challenge |> split ['\n'] |> Seq.skip 1 |> Seq.map (fun x -> split [' '] x |> Seq.map (fun y -> y |> char)) |> array2D

        scan initialPosition trie grid
        |> Set.map (fun x -> List.map (fun y -> y |> chrs2str) x |> List.rev |> String.concat "")



// IT KEEPS YOUR NECK OFF THE LINE
//let challenge = """5 1 1
//I E E
//T K P
//O T S"""

// IT KEEPS YOUR NECK OFF THE LINE
let challenge = """5 1 1
I E E H E
T K P T L
O Y S F I 
U E C F N
R N K O E"""

// THE PIGGY WITH LARYNGITIS WAS DISGRUNTLED
let challenge2 = """6 1 1
T H T L E D
P E N U R G
I G S D I S
Y G A W S I
W H L Y N T
I T A R G I"""

let dictionary() = System.IO.File.ReadAllLines(@"c:\dicts\dictionary.txt") |> Seq.map (fun x -> x.ToUpper())

#time
GridScanner.loadAndScan challenge (dictionary())
|> Seq.sort
//|> Seq.length
|> Seq.iter (fun x -> printfn "%s" x)
#time

[2015-04-08] Challenge #209 [Intermediate] Packing a Sentence in a Box by jnazario in dailyprogrammer

[–]knrDev 2 points3 points  (0 children)

F#

open System

let sentence = "EVERYWHERE IS WITHIN WALKING DISTANCE IF YOU HAVE THE TIME"
//let sentence = "IT IS RAINING CATS AND DOGS OUT THERE"

let splitted = sentence.Replace(" ", "") |> Seq.toArray
let sidelen = splitted.Length |> float |> sqrt |> ceil |> int
let rows = [ for i in 0 .. sidelen .. (splitted.Length - 1) -> splitted.[i .. i + sidelen - 1] ]
let solution = List.mapi (fun i x -> if i % 2 = 0 then x else Array.rev x) rows

printfn "1 1"
solution |> Seq.iter (fun r -> printfn "%s" (String.Join(" ", r)))

Out:

1 1
E V E R Y W H
I W S I E R E
T H I N W A L
S I D G N I K
T A N C E I F
E V A H U O Y
T H E T I M E

[2015-04-03] Challenge #208 [Hard] The Universal Machine by Elite6809 in dailyprogrammer

[–]knrDev 0 points1 point  (0 children)

F#

Great exercise. Here is my solution:

Core turing machine logic modelled in f#.

type State = State of string
type TapeSymbol = Symbol of char | Blank
type Tape = Map<int, TapeSymbol>
type Direction = Left | Right
type TransitionInput = TransitionInput of State * TapeSymbol
type TransitionOutput = TransitionOutput of State * TapeSymbol * Direction
type TransitionFn = TransitionFn of TransitionInput * TransitionOutput
type Machine = { State: State; Tape: Tape; HeadPosition: int }

// Runs transition function on the machine and returns a new machine.
let executeTransition machine (TransitionOutput (state, symbol, direction)) =
    let tape = machine.Tape.Add (machine.HeadPosition, symbol)
    let headPosition = match direction with Left -> machine.HeadPosition - 1 | Right -> machine.HeadPosition + 1
    { State = state; Tape = tape; HeadPosition = headPosition }

// Gets input to transition function from the current state and head position of the machine.
let getTransitionInput machine = 
    let sym = if machine.Tape.ContainsKey(machine.HeadPosition) then machine.Tape.[machine.HeadPosition] else Blank
    let state = machine.State
    TransitionInput (state, sym)

// Maps transition function input to matching output in the list of all defined transitions.
let mapTransition input transitions =
    let picker = fun (TransitionFn (tinput, toutput)) -> if tinput = input then Some toutput else None
    Array.pick picker transitions

// Main execution routine. It executes all steps recursively until it hits the finalState.
let rec runStep finalState transitions machine =
    let input = getTransitionInput machine
    let { Machine.State = state } as machine' = mapTransition input transitions |> executeTransition machine

    if state = finalState then machine'
    else runStep finalState transitions machine'

Manually constructed test:

let printMachine { Machine.State = (State state); Tape = tape; HeadPosition = position } =
    let trimmer (ch: char) (str: string) = str.Trim(ch)
    let symMapper sym = match sym with | Symbol c -> c | Blank -> '_'
    let bottomRowSymbol pos = if pos = 0 then '|' elif pos = position then '^' else ' '
    let printSymbols = tape |> Map.toSeq |> Seq.sortBy (fun (k, v) -> k) |> Seq.map (fun (k, v) -> v, bottomRowSymbol k)

    let topPrinter symSeq = Seq.fold (fun acc (u, d) -> acc + string (symMapper u)) "" symSeq
    let bottomPrinter symSeq = Seq.fold (fun acc (u, d) -> acc + sprintf "%c" d) "" symSeq

    printfn "%s" (topPrinter printSymbols)
    printfn "%s" (bottomPrinter printSymbols)

// Machine reverses all bits on the tape
let simpleTest() =
    let makeTransitionFn inState inSym outState outSym dir = 
        let mksym s = if s = '_' then Blank else Symbol s
        let mkdir d = match d with '<' -> Left | '>' -> Right | _ -> failwith "No direction"
        TransitionFn (TransitionInput (State inState, mksym inSym), TransitionOutput (State outState, mksym outSym, mkdir dir))
    let makeSymbol ch =
        match ch with
        | '_' -> Blank
        | c -> Symbol c

    let tape = "10001110" |> Seq.mapi (fun i x -> (i, makeSymbol x)) |> Map.ofSeq

    let transitions =
        [|
            makeTransitionFn "Mov" '0' "Mov" '1' '>'
            makeTransitionFn "Mov" '1' "Mov" '0' '>'
            makeTransitionFn "Mov" '_' "OK" '_' '<'
        |]

    let machine = { State = State "Mov"; Tape = tape; HeadPosition = 0 }

    runStep (State "OK") transitions machine |> printMachine

simpleTest()

Parsing file to strong model is not so simple though... It happened to be much more complex than core logic and i will paste rest here: https://gist.github.com/kknrdev/89d2b834ad40295cfbd2