Red updating text in VID using reactive method - red

Red [needs: 'view]
num: ["1^/"]
k: num/1
view [
size 600x600
txt: text 30x50 k
ar: area 300x400 "" focus on-change[
txt/size: ar/size
len: length? split face/text newline
either (len - face/data) > 0 [
append num append form (len + 1) newline
face/data: len
][
remove back tail num
face/data: face/data - 1
]
txt/text: form num
]
do [ar/data: 0]
]
This Red program contains a "text face" and an "area face". The text face contains a vertical list of serial numbers. When a newline is added in the area face, the serial number will increase as per number of lines. And when a line is removed in the area face, the serial number will decrease as well.
This is using a non-reactive method. Is there a reactive approach to do it?

I believe that you we're looking for the react function. The reactive framework was introduced in this blog post and there is a very similar example of converting an example using on-change to its reactive version.
Anyhow, I was reading a lot lately about Red, and I was looking for an first exercise; My to-list implementation could be improved probably, but the view declaration is more compact now:
Red [needs: 'view]
to-list: function [text][
; converts text area string to list of numbers separated by newlines
txt: copy text
append txt "dummy" ; handle empty lines
len: length? split txt newline
x: copy ""
repeat i len [ append x mold i append x newline]
]
view [
size 600x600
text 30x600 react [
face/text: to-list text-area/text
]
text-area: area 300x400 ""
]

Related

Editing the labels on a flow chart with DiagrammeR

I’m trying to make a flow chart with R. Attached is the chart I made in word (which is what I'm trying to get to). I don’t want to copy and paste it, I want to actually make it in R. I’ve been using DiagrammeR to try, and the code is below.
I'm having the main trouble with the labels, how to change some parts to bold and make them a nice distance away from the nodes. I've added in the blue and pink boxes in my code, which I like.
Code:
library(DiagrammeR)
graph <- "
digraph boxes_and_circles{
# Add node statements
# This states that all following nodes have a box shape
node[
shape=box,
style=rounded,
fontname=Helvetica,
penwidth=2,
fixedsize = true
width=4
]
# Connect the nodes with edge statements
edge[
arrowhead = normal,
arrowtail = none
]
# These are the main nodes at top of graph
'##1'->'##2'
[label=' Cleaning Function:
Text to lower case
Contractions expanded
Numbers replaced
Abbreviations expanded (Qdap)
NA’s ignored
Kerns replaced
White space removed', fontname=Helvetica, fontsize=20, fontweight=bold]
'##2'->'##3'
'##2'->'##4'
# Make subnodes with boxes around for tidy text grouping
# graph, node, and edge definitions
graph [
compound = true,
nodesep = 1,
ranksep = 0.25,
color = pink
]
# subgraph for tidy text, direct the flow
subgraph cluster0 {
'##3'->'##5'
[label=' -Tokenization
-Lemetisation
-Stop words removed', fontname=Helvetica, fontsize=20, fontweight=bold]
}
# Make subnodes with boxes around for Dictionary grouping
# graph, node, and edge definitions
graph [
compound = true,
nodesep = 1,
ranksep = .25,
color = blue
]
# subgraph for Dictionary direct the flow
subgraph cluster1 {
node [
fixedsize = true,
width = 3
]
'##4'->'##6' [label=' Scoring function (sentimentr)
Inner Join (dplyr)',fontname=Helvetica]
'##6'->'##7' [label=' Grouping
Summarise (dplyr)',fontname=Helvetica]
'##7'->'##8'
}
#Add a graph statement to change the properties of the graph
graph[nodesep=1] #this modifies distance between nodes
}
# Name the nodes
[1]: 'Response Data'
[2]: 'Clean Data'
[3]: 'Tidy Text'
[4]: 'Dictionary Creation'
[5]: 'Visualisation'
[6]: 'Sentiment Lexicon'
[7]: 'Summarised Text'
[8]: 'Visualisation and Statistics'
"

NetLogo chain of turtles breaks up when linking

I'm doing a model of some chains of cells (as part of a larger DNA string model). They wiggle around on screen, and when they wiggle so much, that they come close to a cell of the same type in the same string, they must create a link with that cell.
Code below.
It kinda works.... But after I introduced the linking behavior described above, the string breaks into pieces after a short while. I can't figure out why :-) Any ideas?
Thanks,
Palle
breed [cells cell]
cells-own [paired?]
globals [chains]
to setup
clear-all
set chains []
addchain
reset-ticks
end
to go
foreach chains [c -> movechain c]
ask cells [if any? other cells-here with [label = [label] of myself and paired? = false] [
let makker one-of other cells-here with [label = [label] of myself and paired? = false]
create-link-with makker [tie]
set color red
set paired? true
ask makker [set color red set paired? true]
print word label " was found!"
]]
tick
end
to addchain
set chains lput makechain chains
end
to movechain [mylist]
let antalfollowers length mylist - 1
let i antalfollowers
repeat antalfollowers [
ask item i mylist [
move-to (item (i - 1) mylist)
]
set i i - 1
]
ask first mylist [
right random-float wigglefactor
left random-float wigglefactor
fd 1
]
end
to-report makechain
let mylist []
let text "MGIVEQCCTSICSRYQ"
let startx random-xcor / -3
let starty random-ycor / -3
let i 0
repeat length text [
create-cells 1 [
set color green
set shape "circle"
set label item i text
set paired? false
set mylist lput self mylist
setxy startx + i * .75 starty + i * .75
]
set i i + 1
]
report mylist
end
OK - I finally figured out what's going on. This was hard to see. The tricks I used
in order to see it are listed at the bottom of this post.
In the case of a single strand of synthetic DNA floating around,
when two cells of the same type hit and stick, at that point there will
be a loop of all the cells that were between the moving cell and the
cell that got run into in the list of the sequence of cells.
What you need to do is to:
(a) take the cell that just got run into and link it and tie it to the moving
cell, making the moving cell the MASTER of the link [tie]. You do that
already.
(b) remove the cell you just made a SLAVE from the list of cells your code
has to move, because it will now be moved automatically when the master cell
moves.
AND ... importantly ...
(c) repeat steps (a) and (b) for EVERY cell on the list in positions between
the two cells that just collided and stuck.**
That will effectively freeze the configuration of the entire loop and make it
into a single large unit that will move as one unit when the master cell is
moved by your code.
The User Manual states in the subsection on TIE in the section on LINKS:
When the root turtle turns right or left, the leaf turtle rotates
around the root turtle the same amount as if a stiff were attaching
the turtles. When tie-mode is set to “fixed” the heading of the leaf
turtle changes by the same amount.
I think that you do want to set tie-mode to FIXED so the whole cluster will rotate when the master cell rotates.
I think, but have not looked at it, that this algorithm will work even if the linked cell is the very first or very last one on the chain. Better check it though. Maybe the cell that should be the MASTER is the one that got hit, not the one doing the moving.
In the case of two different strands of DNA intersecting,
basically forming an X, or more complicated cases ... I leave it up to you to figure out what you want the larger connected structure to do, and how hit should move. Do BOTH of the leading cells of each strand tug on it at once? Do you need to shut off one of them so there is only one cell moving the crowd? Will you need to change your code that moves the chain to insert one of the chains entirely into the middle of the other chain on the list that moves them in sequence? I don't know!
By the way, to figure this out, I had to:
slow down the motion and
set the color of the cells to [0 255 0 125] which is a half-transparent green
so I could see through them and see through them overlap, and
use the "watch" feature of the Inspector to follow one of the cells I knew
was going to get linked up, and
use the slider in the inspector to zoom up as far as it would go, and
put a 500 millisecond "wait" in side the innermost loop of the motion.
I'm working on your question and have made some progress -- at least I have a revision of your code with some troubleshooting additions to it, and a revision of the Interface. I can't figure out how to attach a model here, or an image of the view you will see when you run it, so I posted the full model and a PNG file in the netlogo-users Google Group.
The revisions do not fully answer your question about how to solve the breaking up of the chain, but they provide a reproducible version of the model that you can be sure will break at step 746 and that you can turn on dense printing and slow action and watch what is going on with attempted moves after that.
Maybe if we both look at that it will be obvious why this is breaking.
One thing I think may be happening is that, once two cells link and tie, your move algorithm no longer is the correct logic for how the knotted chain should move.
Here's the changes that I made:
I added a random-seed command in setup so that the model can be repeatedly run with exactly the same choices in random variables, so we can both look at the results.
I added a "verbose?" switch on the Interface to turn on or off detailed printing of what's going on.
I added a "clear-stop" button that will allow the "stop" commands I put in the model to stop the running using a stop-requested? flag, which the code sets and this button resets so that "go" and "one step" work again after a stop and the ticks counter keeps on incrementing.
I added a msec-per-tick slider to put a fixed number of milliseconds at the end of the go step so the model will run at a speed that is usable for debugging. I don't know how other people can do it -- when I try to use the built-in slider at the top of the interface to control speed, either it's way too slow, or it's way too fast, and I can't seem to be able to tweak it to just right. So I added this kludge.
I guessed what limits you had on your wigglefactor slider on your interface and made one that goes from 0 to 90 (degrees). It works ok and reproduces your bug.
I added some additional tests to prevent the two C-cells that are adjacent in your choice of cells from linking to each other when they discover, as they do sometimes, that they are on the same patch. With a random seed of 23456 your original code ties its own CC adjacent pair together in tick 2 for instance.
(
Here's the revised code, and comments as to how to use it are in the posted model (in netlogo-users) and below after the code as well.
breed [cells cell]
cells-own [paired?]
globals [
chains
stop-requested? ;;//////////////////////////////////////////////////
]
to setup
clear-all
;; random-seed 12345 ;; /////////////// breaks at either step 35 or 45 ////
;; random-seed 23456 ;; ////////////////// ties its own CC in tick 2 ///
random-seed 34567 ;; /////////////////// ties own cc in tick 84 , ties C at 746 and breaks in 6 steps
;;// wow -- it SNIPS TSIC out of the middle of the chain!! snips out CTIS, turtles 7 8 9 and 10
;; cell 6 C is directly followed by cell 11 -- also C
set chains []
addchain
set stop-requested? FALSE ;; ////////////////////////////////////////
reset-ticks
end
to go
if stop-requested? [ stop ] ;;////////////////////////////////////////////
foreach chains [c -> movechain c]
ask cells [if any? other cells-here with [label = [label] of myself and paired? = false
and who != [who] of myself + 1
and who != [who] of myself - 1
] [
let makker one-of other cells-here with [label = [label] of myself and paired? = false]
create-link-with makker [tie]
set color red
set paired? true
ask makker [set color red set paired? true]
print ( word label " was found at tick " ticks)
set stop-requested? TRUE ;;/////////////////////////////////////////////
]]
wait ( msec-per-tick / 1000 ) ;;////////////////////////////////////////
tick
end
to addchain
set chains lput makechain chains
end
to movechain [mylist]
if verbose? [print ( word "\n\nin code at tick " ticks " starting movechain") ];;//////////////
;;if verbose? [ show mylist ]
let antalfollowers length mylist - 1
let i antalfollowers
repeat antalfollowers [
ask item i mylist [
if verbose? [
;;print (word " asking item " i " on mylist to move to item " (i - 1) )
let mover [label] of item i mylist
let moveto [label] of item (i - 1) mylist
let mover-color [color] of item i mylist
let moveto-color [color] of item (i - 1) mylist
;; BLUE one moves TO the YELLOW ONE at the end of this second
print (word " move " mover " to " moveto )
ask item i mylist [set color blue set shape "square" set size 2]
ask item (i - 1) mylist [set color yellow set shape "square" set size 2]
display
wait 4
ask item i mylist [set color mover-color set shape "circle" set size 1]
ask item (i - 1) mylist [set color moveto-color set shape "circle" set size 1]
display
]
move-to (item (i - 1) mylist)
;;print word "just moved follower " i ;;//////////////////////////
;; wait 0.1 ;;////////////////////////////////////////////////////
]
set i i - 1
]
ask first mylist [
right random-float wigglefactor
left random-float wigglefactor
fd 1
]
end
to-report makechain
let mylist []
let text "MGIVEQCCTSICSRYQ" ;; NOTE - this has a repeat of CC in it which SOMETIMES gets tied (23456 tick 2)
let startx random-xcor / -3
let starty random-ycor / -3
let i 0
repeat length text [
create-cells 1 [
set color green
set shape "circle"
set label item i text
set paired? false
set mylist lput self mylist
setxy startx + i * .75 starty + i * .75
]
set i i + 1
]
report mylist
end
to clear-stop ;;////////////////////////////////
set stop-requested? FALSE ;;////////////////////////////////
end ;;////////////////////////////////
Anyway, here's how to run it to reproduce the problem and examine it
in fine detail very closely.
WHAT IS IT?
model of DNA in motion modified for troubleshooting. When a "C" cell
touches another "C" cell in step 746, and sets a link between the two
C cells and ties them to move as one, the algorithm for motion
breaks somehow. This may help figure out why,
HOW IT WORKS
This has added to it a msec-per-tick slider, default 50, to set the
display speed about right if you leave the usual speed slider at the
very top in the middle (normal).
I also added a button ("clear stop") and a switch ( verbose?)
normally off. With verbose? ON, the model runs very very slowly and
color codes which cell is about to move to which cell ( blue is moving
to yellow ) and they both temporarily change to squares.
HOW TO USE IT
1) set msecs-per-tick to 50 2) shut off verbose?, click SETUP, click
GO. The model will run 746 ticks. ( thats with the random-seed set to
a value of 34567 in globals. )
3) After it stops at tick 746. click clear-stop.
NOTICE the CTI group at the upper right. This is logically BETWEEN the
two C-cells which have linked up. This group will be snipped-out of
the moving DNA It has who numbers 7, 8, 9 and 10 as you can see by
inspecting it.
4) click one-step 6 times to advance to where you can see more clearly
that the two groups have become separate. Then turn on verbose? and
click one-step once to watch the gory details with a 4 second pause
between cell-moves and the running commentary in the Command Center
telling which cells are about to move.

how to let long text change to multiple lines when adding annotation to images

how to let long text change to multiple lines when adding annotation to image
and make the length of each line are equal, like rectangle?
image temp:=getfrontimage()
temp.ShowImage()
imageDisplay disp = front.ImageGetImageDisplay(0)
getsize(temp,x,y)
le=x*2/3
to1=y*80/100
component text1 = NewTextAnnotation(le,to1,string1+","+string2+","+string3,100)
I tried to add 3 strings to an image, each string has more than 15 letters/characters, Total more than 50 letters.
If I put all 3 strings in one text annotation in on line, it is too long.
If I put them as 3 text annotations, as the each line does not have exactly same numbers of letters, it shows ugly.
Is there any could let the text as multiple line, and the background of texts in each line has the same length?
Or the 3 text annotations has the same length, I mean the background of the texts has the same length, when the letters in each text annotations are not same, for example, 1st text annotation with 16 letters, 2nd text annotation with 20 letters, 3rd text annotation with 14 letters, but their background of the text have the same length.
Thanks,
You can add line-breaks as with all strings by simply adding the line-break escape string \n.
Example script:
number sx = 512
number sy = 512
image img := RealImage("test",4,sx,sy)
img = icol
img.ShowImage()
imageDisplay disp = img.ImageGetImageDisplay(0)
number l = sx * 2/3
number t = sy * 80/100
String mLstr = "Some text line\nSome more text lines\nShort text"
number fontSize = 12
Component Line = disp.NewTextAnnotation(l,t,mLstr,fontSize)
Line.TextAnnotationSetAlignment(1) // 1=Left, 2=Center, 3=Right
Line.ComponentSetDrawingMode(1) // 1=with background, 2=without background
Line.ComponentSetBackgroundColor(0.5,0.0,0)
Line.ComponentSetForegroundColor(0,1,0)
disp.ComponentAddChildAtEnd(line)
A note: When creating the new component, there are two different variants of the NewTextAnnotation command:
Component NewTextAnnotation( Component ref_par_comp, Number left, Number top, String text, Number size )
Component NewTextAnnotation( Number left, Number top, String text, Number size )
The first one takes the addtional "parent" component. If you use that one, then the font-size will scale with the default display-size of the parent component on the screen, i.e. will not be different for differently sizes images.
To test: Just try the above script with sx and sy values. Then do the same without the disp. in the line-annotation creating line.

vscode if/else conditions in user defined snippet

Looking at the vscode documentation for user defined snippets, it would appear that using the regex transform, you can do if/else conditions.
However, I can't seem to find any examples of this and I'm struggling to understand the correct syntax based on the BNF alone.
Can someone explain the syntax for this?
For example,
Lets say I have a snippet like this:
"body": [
"let color = '${1|white,black|}';",
"let hex = '${???}';"
]
If color==white, I want hex to output #fff, otherwise if black #000.
This works:
"color conditional": {
"prefix": "_hex",
"body": [
"let color = '${1};",
"let hex = '${1/(white)|(black)|(red)/${1:+#fff}${2:+#000}${3:+#f00}/}';" //works
],
"description": "conditional color"
},
However, as soon as I try it with default placeholders and choices, like
"let color = '${1|white,black|}';", // does not work
Apparently, you cannot do snippet transforms on default placeholder values. See transforms on placeholder values issues
I used the simpler if transform style, so here:
${1/(white)|(black)|(red)/${1:+#fff}${2:+#000}${3:+#f00}
if there is a group 1 $[1} in this case white then replace that group 1 with #fff and if group 2 (black) replace with #000, etc.
You could make it just an if/else (white) or not pretty easily.
"let hex = '${1/(white)/${1:?#fff:#000}/}';" // any non-`white` entry will print `#000`.
${1:? => if group 1 (white) print #fff , else print #000
The vscode docs are not very helpful on these conditional replacements, if you have more questions on their syntax, let me know.

NetLogo - How to set turtle color from array

How can I set a turtle's color from an array?
Here's my code but it doesn't work:
let colors array:from-list ["red" "yellow" "blue" "pink"]
set index random 3
let c array:item colors index
set color array:item colors index
Which leads to this error:
can't set flower variable COLOR to non-number blue error while flower 101 running SET
In NetLogo color, the names of the 14 main colors, plus black and white are defined as constants, so no quotes are required. Also, since they are constants, they are treated like literal values, so you can use them in the bracketed list notation, otherwise, you'd need to use the (list . . . ) reporter to create that list.
Also, your use of an array may be more complicated than needed.
You can write:
let colors [ red green blue yellow ]
set index random 3
let c item colors index
set color c
As an extra bonus, you can use the one-of primitive to do all the above:
set color one-of [ red green blue yellow ]
The accepted answer is the correct one, but as an aside, note that the read-from-string function will interpret a basic NetLogo color name as a color value:
observer> show read-from-string "red"
observer: 15
Also useful to know about is the base-colors built-in function that reports an array of the 14 basic NetLogo colors as numeric values, allowing you to do things such as:
ask turtles [ set color one-of base-colors ]
try setting your color names to number values, according to this site