Using 3 KEYSTROKES to Answer Survey in Qualtrics - jscript

I use Jscript to enable Keystrokes in Qualtrics to answer a question.
It works as with 2 options as provided in the example by Qualtrics: https://www.qualtrics.com/university/researchsuite/developer-tools/custom-programming/example-code-snippets/#ExampleJavaScript
I added a third Keystroke option (press q) which is not working: somehow the keystroke for q is registered but neither does it enter the data nor proceed to the next question as is the case when pressing j or k. See code below. Any advise appreciated - thanks!
Qualtrics.SurveyEngine.addOnload(function()
{
/*Place Your Javascript Below This Line*/
this.hideNextButton();
this.hidePreviousButton();
var that = this;
Event.observe(document, 'keydown', function keydownCallback(e) {
var choiceID = null;
switch (e.keyCode) {
case 74: // 'j' was pressed
choiceID = 1;
break;
case 75: // 'k' was pressed
choiceID = 2;
break;
case 81: // 'q' was pressed
choiceID = 5;
break;
}
if (choiceID) {
Event.stopObserving(document, 'keydown', keydownCallback);
that.setChoiceValue(choiceID, true);
that.clickNextButton();
}
});
});
});

I'm not sure exactly what is wrong. A few different things it could be:
1) Your code above has an extra }); at the end. However, Qualtrics wouldn't let you save that, so I'm thinking it is just a typo in your post above.
2) If your choiceID is wrong and you have force response turned on, then it won't advance and you'll get an error message.
3) If you are in JFE preview mode, then you have to first get focus on the form before any keypress will work.
BTW, this won't work on mobile devices.
Here is some cleaned up code that also fixes issue (3):
Qualtrics.SurveyEngine.addOnload(function()
{
$('Buttons').hide();
if(window.location.pathname.match(/^\/jfe[0-9]?\/preview/)) {
$(this.questionId).select('input').first().focus();
}
var that = this;
Event.observe(document, 'keydown', function keydownCallback(e) {
var choiceID = null;
switch (e.keyCode) {
case 74: // 'j' was pressed
choiceID = 1;
break;
case 75: // 'k' was pressed
choiceID = 2;
break;
case 81: // 'q' was pressed
choiceID = 5;
break;
}
if (choiceID) {
Event.stopObserving(document, 'keydown', keydownCallback);
that.setChoiceValue(choiceID, true);
$('NextButton').click();
}
});
});

Related

My code doesn't receive a message from xserver

I want to receive a message from xserver when I close my window.
(when I hit the 'X' button')
For example, I have a list of windows that are currently opened. (can be referred by dayRecord.)
I want to print that "window closed!" when I click the x button on a terminal.
But though I clicked it, I couldn't get any message from xserver.
Also, that XNextEvent is blocking.
I've test this exact same logic with a window generated in my code using XCreateSimpleWindow,
and it worked perfectly.
I can even close an existing window I created manualy by XDestroyWindow.
So, I think there is no difference between a window that is created by the code
and created before the code starts once if I have a window id.
But somehow, I cannot get any message from a former one.
This is my code.
It is trying to get a list of windows that are opened.
And within them, when I close a terminal it should print "window closed!"
void windowManager() {
// getting a text viewer to be traced
char **textViewers = getTextViewers();
// retreiving new record of a day
DayRecord *dayRecord = getNewDayRecord();
// save an x11 display, and currently opened windows into the day record
Display *display = recordInit(dayRecord);
Window whatToClose;
for (int i = 0; i < dayRecord->recordCnt; ++i) {
printf("currently opened: %s %lu\n", dayRecord->record[i].name, dayRecord->record[i].window);
// for example: i want to know when a terminal is closed. (before the program starts, it should be opened, or it crashes.)
if (strcmp(dayRecord->record[i].name, "gnome-terminal-server") == 0)
whatToClose = dayRecord->record[i].window;
addInfoSpace(display, dayRecord->record + i, textViewers);
}
printf("let's close %lu: %s\n", whatToClose, getWindowName(display, whatToClose));
// window close detecting logic down here...
Atom wmDelete = XInternAtom(display, "WM_DELETE_WINDOW", False);
XSetWMProtocols(display, whatToClose, &wmDelete, 1);
XEvent xEvent;
printf("I am listening!\n");
while (True) {
XNextEvent(display, &xEvent);
if (xEvent.type == ClientMessage && xEvent.xclient.data.l[0] == wmDelete) {
printf("window closed!\n");
break;
}
}
char *json = (char *)malloc(sizeof(char) * 100000);
dayRecordToJSON(dayRecord, json);
printf("%s", json);
// freeing memories
free2dArray((void **)textViewers, MAX_FILE_COUNT);
freeDayRecord(dayRecord);
XCloseDisplay(display);
}
Thank you.
I've tried many things and this worked.
If you're trying to do the same thing, please check the code.
But, I am not sure if this is a right way to do.
Maybe there can be a safer and right way to do this but this works anyway.
// ...
Atom wmDelete = XInternAtom(display, "WM_DELETE_WINDOW", False);
XSetWMProtocols(display, whatToClose, &wmDelete, 1);
XSelectInput(display, whatToClose, SubstructureNotifyMask);
XEvent xEvent;
printf("I am listening!\n");
while (1) {
XNextEvent(display, &xEvent);
if (xEvent.type == DestroyNotify) {
printf("window closed!\n");
break;
}
}
// ...

JAVA Switches, if then else and booleans with string

I'm having a bit of trouble getting a few parts of my code to work properly.
I'm still a bit new to java and could some direction and clues to where I went wrong.
The error comes from the if statements. I feel like i know why they are erring out because the || are undefined but I'm not sure how to fix it. What I'm trying to get it to do is take the inputs either L,R,F,B (left, right, forward and back). lowercase the input and either accept either one or the other using boolean "or".
import java.util.Scanner;
public class ChooseYourAdventure {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Choose a diection: ");
String direction = input.nextLine().toLowerCase();
System.out.printf(" %s and %s/n",getDirection (way),getYourChoice (found));
}
public static String getYourChoice (String found) {
String result = "Unknown";
switch (found)
{
case "l":
result = " now we all know you can turn left unlike Zoolander";
break;
case "left":
result = " now we all know you can turn left unlike Zoolander";
break;
case "r":
result = " you fall down a hole never to be seen again... sad.";
break;
case "right":
result = " you fall down a hole never to be seen again... sad.";
break;
case "f":
result = " YOU ARE THE KWISATZ HADERACH!!";
break;
case "forward":
result = " YOU ARE THE KWISATZ HADERACH!!";
break;
case "b":
result = " you are a scaredy cat but, you live to fight or runaway another day";
break;
case "back":
result = " you are a scaredy cat but, you live to fight or runaway another day";
break;
}
return result;
}
public static String getDirection(String way) {
String result;
if (way == "l" || "left") {
System.out.print("Your character moves left");
}
else if (way == "r" || "right") {
System.out.println("You character moves right");
}
else if (way == "f" || "forward") {
System.out.println("Your character moves forward");
}
else if (way == "b" || "back") {
System.out.println("Your character moves forward");
}
else {
System.out.println(" You cant go that way ");
}
return result;
}
}
All your if statements are wrong. When using || or &&, you need to specify the variable way on each side of the ||:
if (way == "l" || way == "left") {
System.out.print("Your character moves left");
}

Get Visible Text from RichTextBlock

In a UWP app, I am using a RichTextBlock that gets populated with some content. It has word wrapping enabled and has a max lines set so that regardless of the length of its content, it will only show a certain number of lines of rich text.
I'd like to know if there is a way to figure out what is the visible text?
So if I have:
<RichTextBlock TextWrapping="Wrap" MaxLines="2">
<RichTextBlock.Blocks>
<Paragraph>
<Paragraph.Inlines>
A bunch of runs go in here with text that are several lines
</Paragraph.Inlines>
</Paragraph>
</RichTextBlock.Blocks>
</RichTextBlock>
I'd like to know how much of the text is actually visible.
I'm trying to detect cases where the text is longer than a set number of lines and append a "... Read More" at the end of the last line (replacing the last 13 chars with "... Read More")
So I wrote some code to get the behavior that I want, but unfortunately this is rather slow and inefficient. So if you're using it in an app that is primarily to show a lot of text that needs to be truncated (like a ListView with a lot of text items) then this would slow down your app perf. I still would like to know if there is a better way to do this.
Here's my code (which only handles Run and Hyperlink inlines so you'll have to modify to handle other types that you need):
private static void TrimText_Slow(RichTextBlock rtb)
{
var paragraph = rtb?.Blocks?.FirstOrDefault() as Paragraph;
if (paragraph == null) { return; }
// Ensure RichTextBlock has passed a measure step so that its HasOverflowContent is updated.
rtb.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
if (rtb.HasOverflowContent == false) { return; }
// Start from end and remove all inlines that are not visible
Inline lastInline = null;
var idx = paragraph.Inlines.Count - 1;
while (idx >= 0 && rtb.HasOverflowContent)
{
lastInline = paragraph.Inlines[idx];
paragraph.Inlines.Remove(lastInline);
idx--;
// Ensure RichTextBlock has passed a measure step now with an inline removed, so that its HasOverflowContent is updated.
rtb.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
}
// The last inline could be partially visible. The easiest thing to do here is to always
// add back the last inline and then remove characters from it until everything is in view.
if (lastInline != null)
{
paragraph.Inlines.Add(lastInline);
}
// Make room to insert "... Read More"
DeleteCharactersFromEnd(paragraph.Inlines, 13);
// Insert "... Continue Reading"
paragraph.Inlines.Add(new Run { Text = "... " });
paragraph.Inlines.Add(new Run { Text = "Read More", Foreground = new SolidColorBrush(Colors.Blue) });
// Ensure RichTextBlock has passed a measure step now with the new inlines added, so that its HasOverflowContent is updated.
rtb.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
// Keep deleting chars until "... Continue Reading" comes into view
idx = paragraph.Inlines.Count - 3; // skip the last 2 inlines since they are "..." and "Read More"
while (idx >= 0 && rtb.HasOverflowContent)
{
Run run;
if (paragraph.Inlines[idx] is Hyperlink)
{
run = ((Hyperlink)paragraph.Inlines[idx]).Inlines.FirstOrDefault() as Run;
}
else
{
run = paragraph.Inlines[idx] as Run;
}
if (string.IsNullOrEmpty(run?.Text))
{
paragraph.Inlines.Remove(run);
idx--;
}
else
{
run.Text = run.Text.Substring(0, run.Text.Length - 1);
}
// Ensure RichTextBlock has passed a measure step now with the new inline content updated, so that its HasOverflowContent is updated.
rtb.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
}
}
private static void DeleteCharactersFromEnd(InlineCollection inlines, int numCharsToDelete)
{
if (inlines == null || inlines.Count < 1 || numCharsToDelete < 1) { return; }
var idx = inlines.Count - 1;
while (numCharsToDelete > 0)
{
Run run;
if (inlines[idx] is Hyperlink)
{
run = ((Hyperlink)inlines[idx]).Inlines.FirstOrDefault() as Run;
}
else
{
run = inlines[idx] as Run;
}
if (run == null)
{
inlines.Remove(inlines[idx]);
idx--;
}
else
{
var textLength = run.Text.Length;
if (textLength <= numCharsToDelete)
{
numCharsToDelete -= textLength;
inlines.Remove(inlines[idx]);
idx--;
}
else
{
run.Text = run.Text.Substring(0, textLength - numCharsToDelete);
numCharsToDelete = 0;
}
}
}
}

C# Visual Studio's Text to Answer

This is kinda of a Noobie what about I am gonna ask but I am trying to get my Program to work I do not know how to Ask a question in a text box hit the button and it outputs the answer; I Have been researching this for a while I know how to get everything else to work.
So a simple Console app example:
static void Main()
{
bool exit = false;
string response;
while (!exit)
{
Console.Write("Command ('Exit' to end): ");
response = Console.ReadLine();
switch (response)
{
case "Hey":
Console.WriteLine("Welcome");
break;
case "unicorns":
Console.WriteLine("...are awesome!");
break;
case "Exit":
exit = true;
break;
default:
Console.WriteLine("Unrecognized command!");
break;
}
}
Console.Write("Press Enter to Quit");
Console.ReadLine();
}

How to compile a program in Befunge-93?

How do I save and compile a program in Befunge-93?
What file extension do I need to save the file as (like fileName.what)?
Then how do I compile it?
Befunge is typically an interpreted language. In fact it was designed to be difficult to compile because the programs are self-modifying (but that hasn't stopped people from trying to write a compiler).
You should save the file however you like (a .bf extension is typically used) and run the interpreter (bef), passing the filename as a command line argument.
You can see the usage instructions in the source code for the interpreter.
As it is an interpreted language, it usually won't be compiled. A C# Befunge 93 interpreter below, that will read code as an array[] of strings.
string befunge93(string[] p) {
for (int i=0;i<p.Length;i++)
p[i]=p[i].Replace("\"","ª"); // REMOVE QUOTATIONS TO MAKE THINGS EASIER
int l=0; int c=0; // current line and colum
var stack=new Stack<int>(new int[20000]); // initialize stack with many zeroes.
string res=""; // output limited to 1000 chars
int limit=100000; // max commands limited to 10^5
bool smode=false; // string mode
char direction='>';
//-------- MAIN LOOP ---------------
while (res.Length < 1000 && limit--> 0 )
{
var ch=p[l][c];
if (ch=='ª') // ", TOGGLE STRING MODE
smode = !smode;
else if (smode) // STRING MODE => PUSH CHAR
stack.Push((int)ch);
else if (ch==',') // OUTPUT CHAR FROM STACK
res+=(char)stack.Pop();
else if (new Regex(#"[><^v]").IsMatch(""+ch)) // CHANGE DIRECTION
direction = ch;
else if (new Regex(#"\d").IsMatch(""+ch)) // CHANGE DIRECTION
stack.Push(ch-'0');
else if (ch=='*') // MULTIPLICATION
stack.Push(stack.Pop()*stack.Pop());
else if (ch=='+') // SUM
stack.Push(stack.Pop()+stack.Pop());
else if (ch=='`') // GREATER THEN
stack.Push(stack.Pop()>=stack.Pop()?0:1);
else if (ch=='!') // NOT
stack.Push(stack.Pop()==0?1:0);
else if (ch=='.') // OUTPUT NUMBER
res+=$"{stack.Pop()} ";
else if (ch=='#') // JUMP NEXT COMMAND
move();
else if (ch=='$') // DISCARD ITEM FROM STACK
stack.Pop();
else if (ch=='\\') // SWAP
{ var a=stack.Pop(); var b=stack.Pop(); stack.Push(a); stack.Push(b); }
else if (ch=='%') // modulo
{ var a=stack.Pop(); var b=stack.Pop(); stack.Push(b%a); }
else if (ch=='-') // MINUS
{ var a=stack.Pop(); var b=stack.Pop(); stack.Push(b-a); }
else if (ch=='/') // DIVISION
{ var a=stack.Pop(); var b=stack.Pop(); stack.Push(b/a); }
else if (ch==':') // DUPLICATE
stack.Push(stack.First());
else if (ch=='_' || ch=='|') // CONDITIONALS: MOVE IF STACK ZERO, LEFT OTHERWISE
{
var last = stack.Pop();
if (ch=='_') direction=last==0?'>':'<'; // right if stack was zero. Left otherwise
else direction=last==0?'v':'^'; // ch=='|'
}
else if (ch==' '); // SPACE - DO NOTHING.
else return res;
move();
}
return res;
void move() // move cursor
{
switch(direction)
{
case '>':
if (++c==p[0].Length) c=0; break;
case '<':
if (--c==-1) c=p[0].Length-1; break;
case 'v':
if (++l==p.Length) l=0; break;
case '^':
if (--l==-1) l=p.Length-1; break;
default: break;
}
}
}

Resources