How to access values from panels in Red language - object

I am using following code to find products of 2 series of numbers and then to find sum of these products:
make-row: func [][
compose [
t1: text "N1:"
f1: field
t2: text "N2: "
f2: field
t3: text "Product: "
t4: text ""
b: button "Get product" [
x: face/extra/2/text
y: face/extra/4/text
z: (to-integer x) * (to-integer y)
face/extra/6/text: rejoin [z]]
do [b/extra: reduce [t1 f1 t2 f2 t3 t4]] ] ]
view compose [
(make-row) return
(make-row) return
b: button "Calculate" [t2/text: "..to be given"]
t1: text "Sum of products:"
t2: text "" ; NEED TO GET SUM OF ALL PRODUCTS IN ABOVE ROWS.
]
The first part is working all right - The products are being calculated properly. But how can I access these individual products to find sum of products? I could not find any way since the rows are not really objects whose public variables or methods/functions I may be able to access. How can this be solved? Thanks for your help.

As I just learned about faces and panes, here a solution without error handling
make-row: func [][
compose [
text "N1:"
field
text "N2: "
field
text "Product: "
text ""
button "Get product" [
b1: index? find face/parent/pane face
face/parent/pane/(b1 - 1)/text: form multiply to-integer face/parent/pane/(b1 - 5)/text to-integer face/parent/pane/(b1 - 3)/text
]
]
]
view compose [
(make-row) return
(make-row) return
button "Calculate" [
t2/text: form add to-integer face/parent/pane/6/text to-integer face/parent/pane/13/text
]
text "Sum of products:"
t2: text ""
]
All face objects are ordered in the pane block of the parent face. So looking at the index of the clicked face object you get a reference to compute the position of other face objects.

Related

Display first ten cols of Altair chart if no user selection?

My graph contains 90 rows of different companies. It's controlled by a dropdown menu that allows users to select an individual company. However, until a user selects a value from the dropdown, ALL the rows are displayed all my graph, which looks messy. Is there anyway to show only the first company by default? Or the first ten companies? Thanks.
Current Output.
Desired Output
I haven't found any solutions thus far. Here is my current code.
dropdown_list = df["Name"].sort_values().unique().tolist()
dropdown = alt.binding_select(options=[None] + dropdown_list, labels = ['All'] + dropdown_list, name = "Operator")
selection = alt.selection_single(fields=["Name"], bind=dropdown)
`(alt.Chart(df).mark_circle(opacity=1, size = 150).transform_window(id='rank()',groupby=['Variable']).encode(alt.X('Percentage:O', sort='ascending', axis=alt.Axis(ticks=False, grid=False)),
alt.Y('Name:N'),
color=alt.Color("Variable:N", scale=alt.Scale(range=cp.CALITP_CATEGORY_BRIGHT_COLORS), legend=None),
tooltip = ['Name', 'Variable'])
.properties(title = "Title Here").add_selection(selection).transform_filter(selection))`

Interactive labeling of images in jupyter notebook

I have a list of pictures:
pictures = {im1,im2,im3,im4,im5,im6}
Where
im1:
im2:
im3:
im4:
im5:
im6:
I want to assign the pictures to labels (1,2,3,4 etc.)
For instance, here pictures 1 to 3 belong to label 1, picture 4 belongs to label 2, picture 5 to label 3, and picture 6 to label 4.
-> label = {1,1,1,2,3,4}
Since I need to see the images when I label them, I need a method to do that while labeling them. I was thinking of creating an array of images:
And then I define the ranges by clicking on the first and last picture belonging to the same labels, so for example:
What do you think ? Is this somehow possible ?
I would like to assign different labels to different ranges of pictures.
For instance: When one has finished selecting the first label one could indicate it by a Double-click and then do the selection of the second label range, then Double-click, then do the selection of the third label range, then Double-click, then do the selection of the fourth label range, etc.
It does not have to be Double-clicking to change the selection of the labels, it could also just be a buttom or any other idea that you might have.
In the end one should have the list of labels.
Essentially, most of the interaction you are looking for boils down to being able to display images, and detect clicks on them in real time. As that is the case, you can use the jupyter widgets (aka ipywidgets) module to achieve most (if not all) of what you are looking for.
Take a look at the button widget which is described here with explanation on how to register to its click event. The problem - we can't display an image on a button, and I didn't find any way to do this within the ipywidgets documentation. There is an image widget, but it does not provide an on_click event. So construct a custom layout, with a button underneath each image:
COLS = 4
ROWS = 2
IMAGES = ...
IMG_WIDTH = 200
IMG_HEIGHT = 200
def on_click(index):
print('Image %d clicked' % index)
import ipywidgets as widgets
import functools
rows = []
for row in range(ROWS):
cols = []
for col in range(COLS):
index = row * COLS + col
image = widgets.Image(
value=IMAGES[index], width=IMG_WIDTH, height=IMG_HEIGHT
)
button = widgets.Button(description='Image %d' % index)
# Bind the click event to the on_click function, with our index as argument
button.on_click(functools.partial(on_click, index))
# Create a vertical layout box, image above the button
box = widgets.VBox([image, button])
cols.append(box)
# Create a horizontal layout box, grouping all the columns together
rows.append(widgets.HBox(cols))
# Create a vertical layout box, grouping all the rows together
result = widgets.VBox(rows)
You can technically also write a custom widget to display an image and listen for a click, but I simply don't believe it's worth your time and effort.
Good luck!
The qsl package provides widgets that do this. For your case, the following code would allow you to label images in batches. Full disclosure, qsl is a project I started because I, like you, wanted to label images from inside Jupyter notebooks.
import qsl
from IPython.display import display
labeler = qsl.MediaLabeler(
items=[
{"target": "https://i.stack.imgur.com/cML6z.jpg"},
{"target": "https://i.stack.imgur.com/6EVAP.jpg"},
{"target": "https://i.stack.imgur.com/CAxUw.jpg"},
{"target": "https://i.stack.imgur.com/8fhan.jpg"},
{"target": "https://i.stack.imgur.com/eMXn5.jpg"},
{"target": "https://i.stack.imgur.com/YFBfM.jpg"}
],
# Optional, you can also configure the labeler from
# the UI.
config={
"image": [
{
"name": "Type",
"options": [
{"name": "Foo"},
{"name": "Bar"}
]
}
]
},
# Optional, set to 1 if you want to label
# one image at a time.
batch_size=4,
# Optionally, save labels to JSON. You
# can also get the labels using `labeler.items`.
jsonpath="labels.json"
)
display(labeler)
This generates a UI that looks like this.
Here is a Google Colab notebook that shows how to do this in Google Colab.

How synchronize two list controls vertically in MFC

I have two list controls and both are vertically scroll-able separately.
However I want to synchronize scroll also I would like to hide the vertical scroll bar in list control-1.
On the other hand if you scroll vertically list control-2, then the list control-1 should scroll down automatically the same amount of items in such way that the options on the both the list boxes should always appear in the same row.
How can I achieve this in MFC?
I do this with a connection between two list views through the document, but the end result is a command to the Scroll member of the slave list control.
So handle the ON_WM_VSCROLL() in the master, I actually have a custom notify but you may want to just shortcut to from the likes of in the master:
if( pS->nSBCode == SB_THUMBTRACK )
GetDocument( )->SetSplitScrollPos( pS->nPos );
How ever you work past to the likes of 'SetSplitScrollPos' it ends up with this at the slave:
void CLCtrl::ScrollToVPosition( long inPos )
{
long scroll= ( inPos - curVScrollPos );
Scroll( scroll << 20 );
curVScrollPos= inPos;
}
The 'Scroll' call is a CListCtrl member, so you could:
mySlaveCtrl.Scroll( ... );
Now, I'm sorry, but I don't recall why the shift of 20 as '<< 16' should move the value to the hi_word, but it needed to be 16 times greater, (20 - 16). I did not write in the required comments.
To wit, it may be as simple for you to handle the master ON_WM_VSCROLL and:
if( pS->nSBCode == SB_THUMBTRACK )
mySlaveCtrl.Scroll( ( ps->pos - curVScrollPos ) << 20 );

Formatted String from List Psychopy

My task is a variation of a multiple object tracking task. There are 7 circles on the screen. It randomly selects 3 circles to change the color (red, green, blue) briefly to indicate to the participant to track these circles. After the color change, all the circles will change to the same color and the circles will move for a period of time. When the circles stop moving, a response prompt will appear, where the participant is to select one of the three colored circles ('select the red/green/blue circle'). I am having difficulty inserting which color circle to select into the formatted string. I keep getting the error message: unsupported operand type(s) for %: 'TextStim' and 'list'
I'm not sure if I need to or how to convert these lists, so any help would be much appreciated!
n_targets = 7 #seven locations
circles = [] #setting up the circle stimuli
for i in range(n_targets):
tmp = visual.Circle(win,radius = 27,units = 'pix',edges = 32,fillColor='white',lineColor = 'black',lineWidth = 1, pos=(posx[i],posy[i]))
circles.append(tmp)
cols = ['blue','red','green'] #3 colors the circles will change to
targets = random.sample(circles,3) #randomly select 3 of the 7 circles
TrialTarget = random.sample(targets, 1) #select 1 of the 3 circles to be the target for the trial
#code for movement would go here (skipping since it is not relevant)
#at end of trial, response prompt appears and ask user to select target and is where error occurs
ResponsePrompt = visual.TextStim(win, text = "Select the %s circle") %TrialTarget
In this line, you are trying to create a formatted string from a TextStim object and a Circle stimulus object rather than a string object and another string object:
ResponsePrompt = visual.TextStim(win, text = "Select the %s circle") %TrialTarget
i.e. ResponsePrompt is clearly a visual.TextStim, as you are creating it as one, and I think TrialTarget is a visual.Circle stimulus, as you randomly sample it from a list of Circles.
I'm guessing that you actually want to incorporate the colour label into the prompt text. So to fix both problems (the type incompatibility and the formatting syntax), you need to actually get one of the elements of cols, called say trialColour, and use something like this:
ResponsePrompt = visual.TextStim(win, text = "Select the %s circle" % trialColour)
i.e. here trialColour is actually a string, and the formatting operation is brought inside the brackets so it applies directly to the text string "Select the %s circle"
That should hopefully fix your immediate problem. You might also want to investigate using random.shuffle() to shuffle lists in place instead of random.sample().

how to use an atomic vector as a string for a graph title in R

I'm trying to plot a graph from a matrix of z-scores in R, i would like to build a function to iterate through each column using the column header as part of the title and saving each graph as a png.I think I know how to do the iteration and saving graphs as pngs but I am getting stuck with using the vector as a string. I tried to upload the matrix with no column headers and then store matrix[1,] as a variable 'headers' to use. Then I tried to plot:
plot(1:30, rnorm(30), ylim=c(-10,10), yaxs="i", xlab = "Region", ylab = "Z-Score",main = "CNV plot of " + headers[i], type = "n")
I get:
Warning message:
In Ops.factor(left, right) : + not meaningful for factors
I try without the '+' and it says:
Error: unexpected symbol in ...
So then I looked around and found 'paste(headers[i],collapse=" ") which I though I could substitute in but it just puts the number '28' as the title.
I've tried what I thought was another potential solution:
plot(1:30, rnorm(30), ylim=c(-10,10), yaxs="i", xlab = "Region", ylab = "Z-Score",main = "Z-scores of " $headers[i], type = "n")
and I get:
Error in "Z-scores of "$headers :
$ operator is invalid for atomic vectors
I'm new to R and this seems like something that would be so simple if I happened to stumble across the right guide/tutorial after hours of google searching but I really don't have that kind of time on my hands. Any suggestions, pointers or solutions would be great??
If you want to insert values from variables into strings for a plot title, bquote is the way to go:
headers <- c(28, 14, 7) # an examle
i <- 1
plot(1:30, rnorm(30), ylim=c(-10,10), yaxs="i",
xlab = "Region", ylab = "Z-Score", type = "n",
main = bquote("CNV plot of" ~ .(headers[i])) )
Have a look at the help page of ?bquote for further information.
paste("CNV plot of", headers[i]), should work. You only need collapse if you are pasting vectors of length greater than one (headers[i] should be one length, even if header is not). R doesn't have any concatenation operators, unlike PHP, JS, etc (so +, &, . will not work, you have to use paste).
Note that your paste was paste(headers[i],collapse=" "), and if that just plotted 28, it suggests your headers vector doesn't contain what you think it does (if you didn't want 28 to be displayed, that is.
Try just looping through your vector and printing the paste command to screen to see what it displays (and also, just print the vector).

Resources