Is there an equivalent groupOrder option for graph2d as there is for the timeline widget? http://visjs.org/docs/timeline/#Configuration_Options
Looking to draw bar charts in a specific order to handle overlapping.
The group order is determined by the order how you add groups, unless you set the ids as integers.
This is a example where you set the ids with strings:
a = new vis.DataSet()
-> DataSet {_options: Object, _data: Object, length: 0, _fieldId: "id", _type: Object…}
a.add([{id:"b"}, {id: "a"}, {id: "c"}])
-> ["b", "a", "c"]
a.getIds()
-> ["b", "a", "c"]
But when you create a dataset where the ids are integers, it will sort the datagroups based on the integers:
b = new vis.DataSet()
-> DataSet {_options: Object, _data: Object, length: 0, _fieldId: "id", _type: Object…}
b.add([{id:2}, {id: 3}, {id: 1}])
-> [2, 3, 1]
b.getIds()
-> [1, 2, 3]
When you mix the integers and strings it will sort the integers first and then then leave the strings unsorted.
c = new vis.DataSet()
DataSet {_options: Object, _data: Object, length: 0, _fieldId: "id", _type: Object…}
c.add([{id:"b"}, {id: 2}, {id: "a"} , {id: 1}])
["b", 2, "a", 1]
c.getIds()
[1, 2, "b", "a"]
Related
I have a nested dict in elixir, from which I want to save the latest items in a new dict.
sorted_slides = [
%{
id: 1,
visual_events: [
%{entity_id: 1, payload: "abc"},
%{entity_id: 2, payload: "def"}
]
},
%{
id: 2,
visual_events: [
%{entity_id: 2, payload: "yui"},
%{entity_id: 3, payload: "def"},
%{entity_id: 4, payload: "ghi"},
]
},
%{
id: 3,
visual_events: [
%{entity_id: 2, payload: "ert"},
%{entity_id: 4, payload: "poi"},
]
}
]
dict = %{}
Enum.each(sorted_slides, fn slide ->
Enum.each(slide.visual_events, fn ve ->
eid = ve.entity_id
dict = Map.put(dict, eid, ve)
IO.inspect(dict)
end)
end)
IO.inspect(dict)
My original data structure contains items that may be overwritten by newer items. I want the new dict to be:
dict = %{
1 => %{entity_id: 1, payload: "abc"},
2 => %{entity_id: 2, payload: "ert"},
3 => %{entity_id: 3, payload: "def"},
4 => %{entity_id: 4, payload: "poi"}
}
I want the dict to save the changes made to it by each iteration, but I guess that scoping works different from some other languages here.
How would I achieve this in Elixir?
You can use Enum.flat_map/2 to extract the inner elements, and Map.new/2 to construct a new map from those elements. Map.new/2 will ensure the latest element prevails when there are duplicate keys.
sorted_slides
|> Enum.flat_map(fn %{visual_events: items} -> items end)
|> Map.new(fn %{entity_id: id} = map -> {id, map} end)
Result:
%{
1 => %{entity_id: 1, payload: "abc"},
2 => %{entity_id: 2, payload: "ert"},
3 => %{entity_id: 3, payload: "def"},
4 => %{entity_id: 4, payload: "poi"}
}
In the case you want to build a structure within a "loop", you can most of the times reach for Enum.reduce/3:
Enum.reduce(sorted_slides, %{}, fn slide, acc ->
Enum.into(slide.visual_events, acc, fn event ->
{event.entity_id, event}
end)
end)
The inner loop could be implemented with Enum.reduce/3 as well, but Enum.into/3 makes it slightly more compact.
Enum.each/2 is only meant to perform side-effects (like printing) but doesn't return any actual result, it just always returns :ok.
I guess that scoping works different from some other languages here.
Exactly, in Elixir you don't mutate existing structures, you create new structures and need to pass them around. This is typically the case of our acc accumulator above.
Side note: in Elixir, these are not called dicts but maps. There have been deprecated dicts structure in the past.
Say you have an array of objects with the structure like {id: 1, type: 'A', value: 10} want to find the total of type A, type B, and type C.
It would be more efficient to initialize the total variables and then loop through the array once, adding the the total variables based on type, than to use a reduce function for each total, in effect looping over the array 3 times.
However, from what I understand from the functional programming paradigm, functions should not manipulate anything outside of it internal scope and functions should have just one purpose, so the latter approach would be preferred.
Approach 1: initialize a variable for each of the three types, loop once and add to each total based on type
Approach 2: use reduce function for each total type.
Which one is preferred?
You can use a single fold/reduce if you use a record containing the three values as the state e.g. in clojure:
(defn sum-inputs [inputs]
(reduce (fn [acc {:keys [type value]}]
(update acc (keyword type) + value))
{:A 0 :B 0 :C 0}
inputs))
then
(sum-inputs [{:id 1 :type "A" :value 10}
{:id 2 :type "B" :value 12}
{:id 3 :type "B" :value 7}
{:id 4 :type "C" :value 40}])
in Javascript it looks like you can use Array.reduce:
const input = [{id: 1, type: "A", value: 4}, {id: 2, type: "B", value: 3}, {id: 3, type: "B", value: 9}, {id: 4, type: "C", value: 2}]
input.reduce(function(acc, i) { acc[i.type] += i.value; return acc; }, {A: 0, B: 0, C: 0})
note this mutates the accumulator record in place.
I'm trying to understand list comprehensions in Elixir.
The example I'm looking at is producing the permutations of a string from this answer.
def shuffle([], _), do: [[]]
def shuffle(_, 0), do: [[]]
def shuffle(list, i) do
for x <- list, y <- shuffle(list, i-1), do: [x|y]
end
How does this double-generator comprehension look when re-written without the comprehension? I made an attempt to implement the algorithm myself, but my implementation is appending to the list, rather than prepending as in the comprehension. I want to write the algorithm without the comprehension but with identical behaviour.
A comprehension without filters can be converted into a sequence of Enum.flat_map and Enum.map. Specifically, all but the last one will become flat_map and the last one will become map. Here's a translation of your code:
list
|> Enum.flat_map(fn x ->
shuffle(list, i - 1)
|> Enum.map(fn y ->
[x | y]
end)
end)
I tested with A.shuffle([1, 2, 3, 4, 5], 2) and the output looks identical to the original code in that question.
Running Dogbert's example with the flat_map replaced with map really helped me see what was going on:
iex(1)> Permute.shuffle(~w(A B C), 3)
[
[
["A", ["A", ["A"]], ["A", ["B"]], ["A", ["C"]]],
["A", ["B", ["A"]], ["B", ["B"]], ["B", ["C"]]],
["A", ["C", ["A"]], ["C", ["B"]], ["C", ["C"]]]
],
[
["B", ["A", ["A"]], ["A", ["B"]], ["A", ["C"]]],
["B", ["B", ["A"]], ["B", ["B"]], ["B", ["C"]]],
["B", ["C", ["A"]], ["C", ["B"]], ["C", ["C"]]]
],
[
["C", ["A", ["A"]], ["A", ["B"]], ["A", ["C"]]],
["C", ["B", ["A"]], ["B", ["B"]], ["B", ["C"]]],
["C", ["C", ["A"]], ["C", ["B"]], ["C", ["C"]]]
]
]
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
for items in messy_list:
if items.isdigit() == 0:
messy_list.remove(items)
Please help me to do so?
You can do something like this (not in-place):
lst = [item for item in messy_list if isinstance(item, int) and not isinstance(item, bool)]
I am a little confused on the answer that Xcode is giving me to this experiment in the Swift Programming Language Guide:
// Use a for-in to iterate through a dictionary (experiment)
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25]
]
var largest = 0
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
largest
I understand that as the dictionary is being transversed, the largest number is being set to the variable, largest. However, I am confused as to why Xcode is saying that largest is being set 5 times, or 1 time, or 3 times, depending on each test.
When looking through the code, I see that it should be set 6 times in "Prime" alone (2, 3, 5, 7, 11, 13). Then it should skip over any numbers in "Fibonacci" since those are all less than the largest, which is currently set to 13 from "Prime". Then, it should be set to 16, and finally 25 in "Square", yielding a total of 8 times.
Am I missing something entirely obvious?
Dictionaries in Swift (and other languages) are not ordered. When you iterate through the dictionary, there's no guarantee that the order will match the initialization order. In this example, Swift processes the "Square" key before the others. You can see this by adding a print statement to the loop. 25 is the 5th element of Square so largest would be set 5 times for the 5 elements in Square and then would stay at 25.
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25]
]
var largest = 0
for (kind, numbers) in interestingNumbers {
println("kind: \(kind)")
for number in numbers {
if number > largest {
largest = number
}
}
}
largest
This prints:
kind: Square
kind: Prime
kind: Fibonacci
let dict : [String : Any] = ["FirstName" : "Maninder" , "LastName" : "Singh" , "Address" : "Chandigarh"]
dict.forEach { print($0) }
Result would be
("FirstName", "Maninder")
("LastName", "Singh")
("Address", "Chandigarh")
This is a user-defined function to iterate through a dictionary:
func findDic(dict: [String: String]) {
for (key, value) in dict {
print("\(key) : \(value)")
}
}
findDic(dict: ["Animal": "Lion", "Bird": "Sparrow"])
// prints…
// Animal : Lion
// Bird : Sparrow
If you want to iterate over all the values:
dict.values.forEach { value in
// print(value)
}
Here is an alternative for that experiment (Swift 3.0). This tells you exactly which kind of number was the largest.
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
var whichKind: String? = nil
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
whichKind = kind
largest = number
}
}
}
print(whichKind)
print(largest)
OUTPUT:
Optional("Square")
25
You can also use values.makeIterator() to iterate over dict values, like this:
for sb in sbItems.values.makeIterator(){
// do something with your sb item..
print(sb)
}
You can also do the iteration like this, in a more swifty style:
sbItems.values.makeIterator().forEach{
// $0 is your dict value..
print($0)
}
sbItems is dict of type [String : NSManagedObject]