Cannot access instance variable/property of javascript object in clojurescipt - clojurescript

Chestnut project. Cider BREPL.
Using Three.js, I'm getting a simple color object:
(set! c (js/THREE.Color. 0 0 255))
Examine the object:
clojoids-org.dev> (type c)
#<function ( color ) {
if ( arguments.length === 3 ) {
return this.setRGB( arguments[ 0 ], arguments[ 1 ], arguments[ 2 ] );
}
return this.set( color )
}>
I read this as it sets the color property. However, when I try to get the color property, I get nil:
clojoids-org.dev> (.-color c)
-> nil
Tried aget as well:
clojoids-org.dev> (aget c "color")
->nil
As well as accessing RGB or setRGB (as suggested by the setRGB() call in the function):
clojoids-org.dev> (.-RGB c)
-> nil
clojoids-org.dev> (.-setRGB c)
#<function ( r, g, b ) {
this.r = r;
this.g = g;
this.b = b;
return this;
}>
nil
clojoids-org.dev> (.-r (.-setRGB c))
nil
clojoids-org.dev> (.-b (.-setRGB c))
nil
clojoids-org.dev> (.-g (.-setRGB c))
nil
Either it's genuinely nil because I'm not setting color properly, or I am not accessing it properly.
Can anyone see what I'm doing wrong?

Well, shortly after posting this question, I discovered this worked:
clojoids-org.dev> (.-r c)
0
clojoids-org.dev> (.-g c)
0
clojoids-org.dev> (.-b c)
255
Thus the problem was I was not accessing it properly.

Related

Recursive Function involving *html.Node to print all links in a HTML Doc

I am trying to print all links in a HTML Doc using a function which accepts *html.Node as an argument. I am new to both Golang and the *html.Node datatype, I have never worked with them before.
func visit(links []string, n *html.Node) []string {
if n == nil {
return links
}
if n.Type == html.ElementNode && n.Data == "a" {
for _, a := range n.Attr {
if a.Key == "href" {
links = append(links, a.Val)
}
}
}
if i == 0 {
i++
return visit(links, n.FirstChild)
}
return visit(links, n.NextSibling)
}
The aim of the if block which checks whether i==0 is to ensure that return visit(links, n.FirstChild) only runs once (the first time) and return visit(links, n.NextSibling) runs on the following iterations. However, links never gets appended, and always returns an empty slice. I do not understand the error in my code.
The code works perfectly fine when using a for loop, but breaks when I try to use recursion.
for c := n.FirstChild; c != nil; c = c.NextSibling {
links = visit(links, c)
}
Your code doesn't work as in it takes the first child of the document, which is html element and then it takes its sibling element which is nil thus causing the function to end with empty slice of links.
To explain in detail:
Here's an example code,
package main
import (
"fmt"
"log"
"strings"
"golang.org/x/net/html"
)
var i int = 0
func visit(links []string, n *html.Node) []string {
if n == nil {
return links
}
if n.Type == html.ElementNode && n.Data == "a" {
for _, a := range n.Attr {
if a.Key == "href" {
links = append(links, a.Val)
}
}
}
if i == 0 {
i++
return visit(links, n.FirstChild)
}
return visit(links, n.NextSibling)
}
func main() {
s := `<p>Links:</p><ul><li>Foo<li>BarBaz</ul>`
doc, err := html.Parse(strings.NewReader(s))
if err != nil {
log.Fatal(err)
}
links := visit([]string{}, doc)
fmt.Println(links)
}
1st call to visit,
Arguments:
links = []
n = DocumentNode
In the first call, i=0, so it makes a recursive call to visit with the first child of the document node.
2nd call to visit,
Arguments:
links = []
n = ElementNode (n.Data = "html")
In the 2nd call, n is the html element node. Now a 3rd call to visit is made with the next sibling of the html element node.
And this is where the problem lies.
There is no sibling for html element node, so n will be nil.
3rd call to visit,
Arguments:
links = []
n = nil
So, now all the function 3 function calls that were called recursively will return and the flow of execution will go back to main and hence the slice links will remain empty.
Hope you understood.
The proper way to code this functionality is by the loop you shared in your question, like this,
package main
import (
"fmt"
"log"
"strings"
"golang.org/x/net/html"
)
func visit(links []string, n *html.Node) []string {
if n.Type == html.ElementNode && n.Data == "a" {
for _, a := range n.Attr {
if a.Key == "href" {
links = append(links, a.Val)
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
links = visit(links, c)
}
return links
}
func main() {
s := `<p>Links:</p><ul><li>Foo<li>BarBaz</ul>`
doc, err := html.Parse(strings.NewReader(s))
if err != nil {
log.Fatal(err)
}
links := visit([]string{}, doc)
fmt.Println(links)
}
Here, the loop helps to recursively find the links by checking each and every HTML element's children. If one of the HTML elements have no siblings, then it would simply move on to its parent's next sibling element and check
I'm struggling with the same problem for a while. According to the title the purpose of the question is how to replace for loop:
for c := n.FirstChild; c != nil; c = c.NextSibling {
links = visit(links, c)
}
with recursive function. This for loop is a standard way to traverse the tree document included in x/html go package. Despite that #Ramaraja answer was accepted it doesn't contain a proper solution.
Here, the loop helps to recursively find the links by checking each and every HTML element's children. If one of the HTML elements have no siblings, then it would simply move on to its parent's next sibling element and check
Based on this answer I tried this one:
if c := n.FirstChild; c != nil {
links = visit(links, c)
} else if c.NextSibling != nil {
links = visit(links, c.NextSibling)
}
The program triggers panic procedure. I'm not sure whether it is possible to avoid for loop at all.

Print Go call tree

Given a file like this:
package main
func A() {}
func B() {
A()
}
func C() {
A()
}
func D() {
B()
}
func E() {
B()
}
func F() {
C()
}
func G() {
C()
}
func main() {
D()
E()
F()
G()
}
I would like to print a call tree of the program, something like this:
main
D
B
A
E
B
A
F
C
A
G
C
A
I found the callgraph program [1], but it does not create a tree:
PS C:\prog> callgraph .
prog.A --static-4:5--> prog.C
prog.A --static-5:5--> prog.D
prog.main --static-19:5--> prog.A
prog.B --static-9:5--> prog.E
prog.B --static-10:5--> prog.F
prog.main --static-20:5--> prog.B
Is some method available to do this?
https://github.com/golang/tools/blob/master/cmd/callgraph
So I did find a package that seems to handle printing a tree from a graph on the
command line [1]. However I thought about it some more, and a printed tree
might not be the best solution to my issue. What I want to do, is return an
error from one of my functions. However to do that, I need to propagate the
error all the way up to main. As this can be several layers, I thought it
would be best if I start from main, and work my way down to the desired
function. That way, I can the work in stages if need be. The issue is, how do I
get an ordered list of these functions? I found a solution with tsort [2]:
PS C:\> callgraph -format digraph . | coreutils tsort
"init/test.main"
"init/test.D"
"init/test.E"
"init/test.F"
"init/test.G"
"init/test.B"
"init/test.C"
"init/test.A"
but I may not always want the entire call graph. Next I thought about just adding
a panic:
func A() {
panic(1)
}
but this will not give you all branches, only the first path to the target
function:
main.A(...)
C:/test.go:4
main.B(...)
C:/test.go:8
main.D(...)
C:/test.go:16
main.main()
C:/test.go:32 +0x45
Finally I wrote my own sort function, that takes arbitrary destination as input,
and prints all paths in order from main to the target function:
package main
func tsort(graph map[string][]string, end string) []string {
var (
b = make(map[string]bool)
l []string
s = []string{end}
)
for len(s) > 0 {
n := s[len(s) - 1]
b[n] = true
for _, m := range graph[n] {
if ! b[m] {
s = append(s, m)
}
}
if s[len(s) - 1] == n {
s = s[:len(s) - 1]
l = append(l, n)
}
}
return l
}
Example:
package main
import (
"bytes"
"fmt"
"os/exec"
)
func main() {
b := new(bytes.Buffer)
c := exec.Command("callgraph", "-format", "digraph", ".")
c.Stdout = b
c.Run()
m := make(map[string][]string)
for {
var parent, child string
_, e := fmt.Fscanln(b, &parent, &child)
if e != nil { break }
m[child] = append(m[child], parent)
}
for n, s := range tsort(m, `"init/test.A"`) {
fmt.Print(n+1, ". ", s, "\n")
}
}
Result:
1. "init/test.main"
2. "init/test.G"
3. "init/test.F"
4. "init/test.C"
5. "init/test.D"
6. "init/test.E"
7. "init/test.B"
8. "init/test.A"
https://github.com/soniakeys/graph/blob/master/treevis/treevis.go
https://github.com/uutils/coreutils

GoLang structure doesn't unmarshal properly when using a custom unmarshal for a nested struct

We need to use a custom unmarshaler for a struct nested in multiple other structs which don't require a custom unmarshaler. We have lots of structs similar to B struct defined below (similar as in nesting A). The code's output is true false 0 (expected true false 2). Any ideas?
Go Playground example here.
package main
import (
"fmt"
"encoding/json"
)
type A struct {
X bool `json:"x"`
Y bool `json:"y"`
}
type B struct {
A
Z int `json:"z"`
}
func (a *A) UnmarshalJSON(bytes []byte) error {
var aa struct {
X string `json:"x"`
Y string `json:"y"`
}
json.Unmarshal(bytes, &aa)
a.X = aa.X == "123"
a.Y = aa.Y == "abc"
return nil
}
const myJSON = `{"x": "123", "y": "fff", "z": 2}`
func main() {
var b B
json.Unmarshal([]byte(myJSON), &b)
fmt.Print(b.X," ",b.Y," ",b.Z)
}
EDIT: question was marked as duplicate here but making A an explicit field will make our API cluttered. Also after making A an explicit field the result is false false 2 so it does not help at all.
Since B embeds A, A.UnmarshalJSON() is exposed as B.UnmarshalJSON(). Due to that, B implements json.Unmarshaler and as a result json.Unmarshal() calls B.UnmarshalJSON() which only unmarshal's A's fields. That's the reason B.Z does not get set from the JSON.
This is the easiest way I could think of to get it working in accordance with your constraint of not changing the data types in A:
Make B embed another struct C which contains the fields not contained in A.
Write an UnmarshalJSON() method for B which unmarshals the same JSON into both B.A and B.C. The advantage of defining another type C with the fields not in A is that you can delegate unmarshalling it to the json package.
With the new B.UnmarshalJSON() method, you now have full control to unmarshal the fields outside of A as well.
type A struct {
X bool `json:"x"`
Y bool `json:"y"`
}
func (a *A) UnmarshalJSON(bytes []byte) error {
// the special unmarshalling logic here
}
type C struct {
Z int `json:"z"`
}
type B struct {
A
C
}
func (b *B) UnmarshalJSON(bytes []byte) error {
if err := json.Unmarshal(bytes, &b.A); err != nil {
return err
}
if err := json.Unmarshal(bytes, &b.C); err != nil {
return err
}
return nil
}

XCode 6.3 / Swift 1.2 curried functions runtime error in release build?

This little generic function produces an interesting runtime error:
func clamps <T: Comparable> (from: T, to: T)(_ x: T) -> T {
if x < from { return from }
if x > to { return to }
return x
}
(As I explain below, please keep in mind that I was unable to significantly reduce the error generating code any further – except by removing one of the if lines!)
We can use it to generate a clamp function like so:
let clamp: Int -> Int = clamps(2, 4)
We'll print some examples like so:
for i in 0...5 {
println("clamp(\(i)) -> \(clamp(i))")
}
When run in Debug the for loop produces the following output:
// clamp(0) -> 2
// clamp(1) -> 2
// clamp(2) -> 2
// clamp(3) -> 3
// clamp(4) -> 4
// clamp(5) -> 4
Which is what we would expect. When run in Release configuration, however, we get:
// clamp(0) -> 4296676200
// clamp(1) -> 4296676200
// clamp(2) -> 4296676200
// clamp(3) -> 4296676200
// clamp(4) -> 4296676200
// clamp(5) -> 4296676200
Notice that this number is very close to UInt32.max (which is 4294967295), so my guess is that it is some sort of UnicodeScalar value... If you use this clamps with other types, like CGFloat, the results are similarly nonsensical.
If we rewrite the function so as to avoid Swift's currying syntax, then everything works fine both in Debug and Release:
func clamps2 <T: Comparable> (from: T, to: T) -> T -> T {
return {
if $0 < from { return from }
if $0 > to { return to }
return $0
}
}
let clamp2: Int -> Int = clamps2(2, 4)
for i in 0...5 {
println("clamp2(\(i)) -> \(clamp2(i))")
}
// clamp2(0) -> 2
// clamp2(1) -> 2
// clamp2(2) -> 2
// clamp2(3) -> 3
// clamp2(4) -> 4
// clamp2(5) -> 4
So the question is whether this really is a bug or have I missed something obvious to the whole world?
As a final example, consider that this (an otherwise useless function) does not reproduce the error:
func f <T: Comparable> (from: T, to: T)(_ x: T) -> T {
if x < from {
return x // <---- returning x
}
return x
}
But this does:
func f <T: Comparable> (from: T, to: T)(_ x: T) -> T {
if x < from {
return from // <---- returning from
}
return x
}
Apple Developer Relations response
My bug report just got a message from Apple Developer Relations saying that they believe this issue has been addressed in the latest Xcode 7 beta.

How to pass a function as argument in Rust

Given the following rust program:
fn call_twice<A>(val: A, f: fn(A) -> A) -> A {
f(f(val))
}
fn main() {
fn double(x: int) -> int {x + x};
println!("Res is {}", call_twice(10i, double));
// println!("Res is {}", call_twice(10i, (x: int) -> int {x + x}));
// ^ this line will fail
}
Why can I pass double as the function, but not inlined? What is a good way to achieve the same behaviour without defining the function somewhere?
2016-04-01 Update:
As of Rust 1.0, the code should look like this:
fn call_twice<A, F>(val: A, mut f: F) -> A
where F: FnMut(A) -> A {
let tmp = f(val);
f(tmp)
}
fn main() {
fn double(x: i32) -> i32 {x + x};
println!("Res is {}", call_twice(10, double));
println!("Res is {}", call_twice(10, |x| x + x));
}
The change to the closure parameter is because closure are now unboxed.
Original:
Insofar as I know, you can't define functions inline like that.
What you want is a closure. The following works:
fn call_twice<A>(val: A, f: |A| -> A) -> A {
let tmp = f(val);
f(tmp)
}
fn main() {
fn double(x: int) -> int {x + x};
println!("Res is {}", call_twice(10i, double));
println!("Res is {}", call_twice(10i, |x| x + x));
}
There are a few things to note:
Functions coerce to closures, but the opposite isn't true.
You need to store the result of f(val) in a temporary due to borrowing rules. Short version: you need unique access to a closure to call it, and the borrow checker isn't quite clever enough to realise the two calls are independent in their original positions.
Closures are in the process of being replaced by unboxed closures, so this will change in the future, but we're not quite there yet.