Exemple #1
0
 public QuizInstance(Quiz quiz) {
   this.quiz = quiz;
   this.setQuestions(quiz.getQuestions());
   this.setQuizName(quiz.getQuizName());
   this.setInstructor(quiz.getInstructor());
   this.initFullMark();
 }
Exemple #2
0
  @Test
  public void test_모든_문자_맞춤() throws Exception {

    // given
    Quiz quiz = new Quiz("synapsoft");

    // when
    ResultCode resultCode1 = quiz.runQuiz('s');
    ResultCode resultCode2 = quiz.runQuiz('y');
    ResultCode resultCode3 = quiz.runQuiz('n');
    ResultCode resultCode4 = quiz.runQuiz('a');
    ResultCode resultCode5 = quiz.runQuiz('p');
    ResultCode resultCode6 = quiz.runQuiz('o');
    ResultCode resultCode7 = quiz.runQuiz('f');
    ResultCode resultCode8 = quiz.runQuiz('t');

    // then
    Assert.assertEquals(resultCode1, ResultCode.FOUND);
    Assert.assertEquals(resultCode2, ResultCode.FOUND);
    Assert.assertEquals(resultCode3, ResultCode.FOUND);
    Assert.assertEquals(resultCode4, ResultCode.FOUND);
    Assert.assertEquals(resultCode5, ResultCode.FOUND);
    Assert.assertEquals(resultCode6, ResultCode.FOUND);
    Assert.assertEquals(resultCode7, ResultCode.FOUND);
    Assert.assertEquals(resultCode8, ResultCode.SUCCESS);
  }
Exemple #3
0
 public static Quiz test2() {
   Quiz quiz = new Quiz();
   quiz.setName("This has responses");
   Response r1 = new Response(new Displayable[] {new Text("Great job!"), new Video("1.mpg")});
   Response r2 =
       new Response(
           new Displayable[] {
             new Text("Not quite right"), new Video("2.mpg"),
           });
   /*
   QuestionContainer qc = new QuestionContainer(
   	new Displayable[] {
   		new Text("Fill in the following code"),
   		new FillIn(1, 1, 1),
   		new Text("class A "),
   		new FillIn(2, 1, 1, "{"),
   		new Text("\n  "),
   		new FillIn(3, 1, 1, "private"),
   		new Text(" int x;\n  "),
   		new FillIn(4, 1, 1, "public"),
   		new FillIn(5, 1, 1, "A"),
   		new Text("() {\n"),
   		new Text("  x = 2;\n}\n")
   	}
   );
   quiz.addQuestionContainer(qc);
   */
   return quiz;
 }
 @Override
 public String getAsString(FacesContext context, UIComponent component, Object value) {
   Quiz v = (Quiz) value;
   System.out.println("Converting Quiz to string: " + v.getId());
   // return v.getId().toString();
   return v.getId() != null ? String.valueOf(v.getId()) : null;
 }
Exemple #5
0
 private void setContents(Quiz quiz) {
   removeAllContent();
   titleTxt.setText(quiz.getTitle());
   authorTxt.setText(quiz.getAuthor());
   for (Question question : quiz.getQuestionList()) {
     addQuestion(question);
   }
 }
Exemple #6
0
  @Test
  public void quizUploadTest() {
    Quiz quiz = new Quiz();

    try {
      int id = quiz.quizUpload("Totoro", "dustSprites", "My Neighbor", "Science", "bla", false);

    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Exemple #7
0
  public static void main(String[] args) {
    List<Card> cards = new ArrayList<Card>();

    for (int i = 0; i < 10; i++) {
      cards.add(new Card(Integer.toString(i), "def" + i));
    }

    Deck deck = new Deck("Test", "This is a test deck.", cards);
    Quiz quiz = new Quiz(deck);

    quiz.start();
  }
Exemple #8
0
  @Test
  public void test_문자_삽입() throws Exception {

    // given
    Quiz quiz = new Quiz("synapsoft");

    // when
    ResultCode resultCode = quiz.runQuiz('s');

    // then
    Assert.assertEquals("s****s***", quiz.getWordWithStar());
    Assert.assertEquals(resultCode, ResultCode.FOUND);
  }
Exemple #9
0
  @Test
  public void test_중복_문자_입력() throws Exception {

    // given
    Quiz quiz = new Quiz("synapsoft");

    // when
    ResultCode resultCode1 = quiz.runQuiz('s');
    ResultCode resultCode2 = quiz.runQuiz('s');

    // then
    Assert.assertEquals(resultCode1, ResultCode.FOUND);
    Assert.assertEquals(resultCode2, ResultCode.DUPLICATE);
  }
Exemple #10
0
 public void actionPerformed(ActionEvent e) {
   Object src = e.getSource();
   if (src.equals(next)) {
     showResult();
     quiz.next();
   }
   if (src.equals(finish)) {
     quiz.showSummary();
   }
   for (int i = 0; i < responses.length; i++) {
     if (src == responses[i]) {
       selected = i;
     }
   }
 }
  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   *     <p>Creates the question and registers it within the database then depending on what the
   *     user clicks, sends them to the finish quiz page or to create another question
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession session = request.getSession();
    Quiz qz = (Quiz) session.getAttribute("newQuiz");
    DBConnection dbCon = (DBConnection) session.getAttribute("connection");
    int qzID = qz.getID();
    Question newQn;
    String question = request.getParameter("question");
    String answer = request.getParameter("answer");
    int type = Integer.parseInt(request.getParameter("type"));
    String MC = null;
    switch (type) {
      case 1:
        newQn = new QResponse(question, answer);
        newQn.setType(type);
        break;
      case 2:
        newQn = new FillIn(question, answer);
        newQn.setType(type);
        break;
      case 3:
        newQn = new MultiChoice(question, answer);
        MC = request.getParameter("choices");
        ((MultiChoice) newQn).addMCOptions(MC);
        newQn.setType(type);
        break;
      case 4:
        newQn = new PictureResponse(question, answer);
        newQn.setType(type);
        break;
      default:
        newQn = null;
        break;
    }
    newQn.printString();
    if (!newQn.equals(null)) qz.addQuestion(newQn);
    Question.registerQuestion(qzID, type, question, answer, MC, dbCon);

    // send the user on forward through the quiz creation
    String action = request.getParameter("action");
    if (action.equals("Create & Continue")) {
      RequestDispatcher dispatch = request.getRequestDispatcher("chooseQuestionType.jsp");
      dispatch.forward(request, response);
    } else if (action.equals("Create & Finish Quiz")) {
      RequestDispatcher dispatch = request.getRequestDispatcher("finishCreationQuiz.jsp");
      dispatch.forward(request, response);
    }
  }
Exemple #12
0
  protected void onResume() {
    super.onResume();
    mGameSettings.getString(GAME_PREFERENCES_USERNAME, null);
    mGameSettings.getString(GAME_PREFERENCES_SCHOOL, null);
    if (mGameSettings.contains(GAME_PREFERENCES_AVATAR)) {
      String img = mGameSettings.getString(GAME_PREFERENCES_AVATAR, null);
      Uri path = Uri.parse(img);
      ImageButton ava = (ImageButton) findViewById(R.id.avatar);
      ava.setImageURI(null);
      ava.setImageURI(path);
    }
    if (mGameSettings.contains(GAME_PREFERENCES_DOB)) {
      long dtDob = mGameSettings.getLong(GAME_PREFERENCES_DOB, 0);
      TextView dob = (TextView) findViewById(R.id.ShowDate);
      dob.setText(DateFormat.format("MMMM dd, yyyy", dtDob));
    }

    final EditText usernameText = (EditText) findViewById(R.id.EnterUsername);
    usernameText.setText(mGameSettings.getString(GAME_PREFERENCES_USERNAME, null));
    final EditText emailText = (EditText) findViewById(R.id.enterschool);
    emailText.setText(mGameSettings.getString(GAME_PREFERENCES_SCHOOL, null));

    TextView passwordInfo = (TextView) findViewById(R.id.ShowPassword);
    passwordInfo.setText(mGameSettings.getString(GAME_PREFERENCES_PASSWORD, null));
  }
Exemple #13
0
 @Override
 protected void onPrepareDialog(int id, Dialog dialog) {
   super.onPrepareDialog(id, dialog);
   switch (id) {
     case DATE_DIALOG_ID:
       // Handle any DatePickerDialog initialization here
       DatePickerDialog dateDialog = (DatePickerDialog) dialog;
       int iDay, iMonth, iYear;
       // Check for date of birth preference
       if (mGameSettings.contains(GAME_PREFERENCES_DOB)) {
         // Retrieve Birth date setting from preferences
         long msBirthDate = mGameSettings.getLong(GAME_PREFERENCES_DOB, 0);
         Time dateOfBirth = new Time();
         dateOfBirth.set(msBirthDate);
         iDay = dateOfBirth.monthDay;
         iMonth = dateOfBirth.month;
         iYear = dateOfBirth.year;
       } else {
         Calendar cal = Calendar.getInstance();
         // Today’s date fields
         iDay = cal.get(Calendar.DAY_OF_MONTH);
         iMonth = cal.get(Calendar.MONTH);
         iYear = cal.get(Calendar.YEAR);
       }
       // Set the date in the DatePicker to the date of birth OR to the
       // current date
       dateDialog.updateDate(iYear, iMonth, iDay);
       return;
   }
 }
Exemple #14
0
  protected void onStop() {
    super.onStop();
    App42API.initialize(
        getApplicationContext(),
        "33febecb03a579e972755eccde307dd94a279b5cfe348f845b8762f8e3feb2d6",
        "b5be405b4e76d40a94cdc01250311205b5a7c7b2dc4d003714f24d0df3e219f8");

    final UserService userService = App42API.buildUserService();
    App42API.setOfflineStorage(true);
    String username = mGameSettings.getString(GAME_PREFERENCES_USERNAME, null);
    String schl = mGameSettings.getString(GAME_PREFERENCES_SCHOOL, null);
    App42API.setLoggedInUser(username);
    String p = mGameSettings.getString(GAME_PREFERENCES_PASSWORD, null);
    String strEmailToSave = mGameSettings.getString(GAME_PREFERENCES_EMAIL, null);
    String pwd = p;
    String emailId = strEmailToSave;
    /* This will create user in App42 cloud and will return created User
    object in onSuccess callback method */
    userService.createUser(
        username,
        pwd,
        emailId,
        new App42CallBack() {
          public void onSuccess(Object response) {
            User user = (User) response;
            System.out.println("userName is " + user.getUserName());
            System.out.println("emailId is " + user.getEmail());
          }

          public void onException(Exception ex) {
            System.out.println("Exception Message" + ex.getMessage());
          }
        });

    User userObj = new User();
    userObj.setUserName(username);
    Profile profile = userObj.new Profile();
    Date date = new Date(); /* returns the current date object.User can set any date */
    profile.setFirstName(username);
    profile.setLine1(schl);
    /* Following will create user profile and returns User object
    which has profile object inside in onSuccess callback method */
    userService.createOrUpdateProfile(
        userObj,
        new App42CallBack() {
          public void onSuccess(Object response) {
            User user = (User) response;
            System.out.println("userName is " + user.getUserName());
            System.out.println("School  is " + user.getProfile().getLine1());
          }

          public void onException(Exception ex) {
            System.out.println("Exception Message" + ex.getMessage());
          }
        });
    Toast.makeText(getApplicationContext(), "User Settings Saved", Toast.LENGTH_SHORT).show();
    UtilSettings.this.finish();
  }
Exemple #15
0
 public static Quiz test3() {
   Quiz quiz = new Quiz();
   quiz.setName("Multimedia Quiz");
   QuestionContainer qc =
       new QuestionContainer(
           new Displayable[] {
             new Video("video1.mp4", 480, 360, "video/mp4"),
             new Text("What is this video about ?"),
             new MultiChoiceDropdown(
                 4,
                 5,
                 new Answer[] {new Answer("Train"), new Answer("Cable Car"), new Answer("Bus")}),
             new Audio("audio1.mp3", "audio/mpeg"),
             new Text("What animal sounds like this ?"),
             new MultiChoiceDropdown(
                 4, 5, new Answer[] {new Answer("Cat"), new Answer("Dog"), new Answer("Horse")})
           });
   quiz.addQuestionContainer(qc);
   return quiz;
 }
Exemple #16
0
 // Standard Choice with multipledropdown, multiple radio and multianswers
 public static Quiz test4() {
   Quiz quiz = new Quiz();
   quiz.setName("Multiple- Quiz");
   QuestionContainer qc =
       new QuestionContainer(
           new Displayable[] {
             new Text("Can all birds fly ?"),
             new MultiChoiceDropdown(1, 5, "Poll"),
             new Text("What is the complexity of BubbleSort ?"),
             new MultiChoiceDropdown(1, 5, "Complexity", 2),
             new Text("What is the complexity of QuickSort?"),
             new MultiChoiceRadio(1, 5, "Complexity"),
             new Text("What are the colors of an apple ?"),
             new MultiAnswer(1, 5, "Colors", new int[] {2, 3}),
             new Text("Name the insects:"),
             new MultiAnswer(1, 5, "Insects", new int[] {3, 4, 5})
           });
   quiz.addQuestionContainer(qc);
   return quiz;
 }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Integer curchoice = Integer.parseInt(request.getParameter("numchoice"));
    String[] question = new String[1];

    int error = 0;
    if (request.getParameter("question").equals("")) error = 1;
    ;
    question[0] = request.getParameter("question");
    Vector<String> q = Quiz.convertToVector(question);

    String[] answer = new String[curchoice];
    for (int i = 0; i < curchoice; i++) {
      Integer cur = i;
      if (request.getParameter(cur.toString()).equals("")) error = 1;
      answer[i] = request.getParameter(cur.toString().toLowerCase());
    }
    Integer id = Integer.parseInt(request.getParameter("quizID"));
    request.setAttribute("quizID", id);

    if (error == 1) {
      request.setAttribute("error", "1");
      RequestDispatcher dispatch = request.getRequestDispatcher("addQR.jsp");
      dispatch.forward(request, response);
    } else {

      Vector<String> apre = Quiz.convertToVector(answer);
      Vector<Vector<String>> a = new Vector<Vector<String>>();
      a.add(apre);

      QuizDatabase qdb = new QuizDatabase();

      qdb.addQuestion(id, "qr", q, a);

      RequestDispatcher dispatch = request.getRequestDispatcher("questionAdded.jsp");
      dispatch.forward(request, response);
    }
  }
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // Get Context and Session
    // ServletContext context = request.getServletContext();
    HttpSession session = request.getSession();
    // init variables needed to create quiz
    User user = (User) session.getAttribute("user");
    String creator = user.getUserName();
    String title = request.getParameter("title");
    if (title.equals("")) {
      RequestDispatcher dispatcher = request.getRequestDispatcher("QuizCreation.jsp?error=1");
      dispatcher.forward(request, response);
      return;
    }
    String description = request.getParameter("description");
    if (description.equals("")) {
      description = "No description provided by " + creator;
    }

    // String creator = "Danny"; //for testing
    boolean randomOrder = Boolean.valueOf(request.getParameter("randomOrder"));
    boolean multiPage = Boolean.valueOf(request.getParameter("multiPage"));
    boolean immediateFeedback = Boolean.valueOf(request.getParameter("immediateFeedback"));
    boolean canPractice = Boolean.valueOf(request.getParameter("canPractice"));
    Quiz dup = QuizSite.getSite().getQuiz(SHAHasher.hash(title));
    if (dup != null) {
      RequestDispatcher dispatcher = request.getRequestDispatcher("QuizCreation.jsp?error=1");
      dispatcher.forward(request, response);
    } else {
      // Create Quiz
      try {
        quiz =
            Quiz.createQuiz(
                title,
                description,
                creator,
                randomOrder,
                multiPage,
                immediateFeedback,
                canPractice);
        session.setAttribute("quizBeingCreated", quiz);
        RequestDispatcher dispatcher = request.getRequestDispatcher("ChooseQuestionType.jsp");
        dispatcher.forward(request, response);
      } catch (SQLException e) {
        e.printStackTrace();
        RequestDispatcher dispatcher = request.getRequestDispatcher("Error.html");
        dispatcher.forward(request, response);
      }
    }
  }
Exemple #19
0
 /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   QuizSite qs = QuizSite.getSite();
   String quizId = request.getParameter("id");
   Quiz q = qs.getQuiz(quizId);
   request.getSession().setAttribute("quizBeingTaken", q);
   List<Integer> questionsRemaining = new ArrayList<Integer>();
   Iterator<Question> iter = q.getQuestions().iterator();
   while (iter.hasNext()) {
     questionsRemaining.add(iter.next().getId());
   }
   if (request.getParameterMap().containsKey("practiceMode")
       && Integer.parseInt(request.getParameter("practiceMode")) == 1) {
     request.getSession().setAttribute("practiceMode", 1);
   } else {
     request.getSession().setAttribute("practiceMode", 0);
   }
   request.getSession().setAttribute("questionsRemaining", questionsRemaining);
   request.getSession().setAttribute("quizPageNum", 0);
   request.getSession().setAttribute("score", 0.0);
   request.getSession().setAttribute("startTime", System.currentTimeMillis());
   RequestDispatcher dispatcher = request.getRequestDispatcher("TakeQuiz.jsp");
   dispatcher.forward(request, response);
 }
Exemple #20
0
  @Test
  public void test_없는_문자_입력() throws Exception {

    // given
    Quiz quiz = new Quiz("synapsoft");

    // when
    ResultCode resultCode1 = quiz.runQuiz('d');
    ResultCode resultCode2 = quiz.runQuiz('d');
    ResultCode resultCode3 = quiz.runQuiz('d');
    ResultCode resultCode4 = quiz.runQuiz('d');
    ResultCode resultCode5 = quiz.runQuiz('d');
    ResultCode resultCode6 = quiz.runQuiz('d');
    ResultCode resultCode7 = quiz.runQuiz('d');

    // then
    Assert.assertEquals(resultCode1, ResultCode.NOT_FOUND);
    Assert.assertEquals(resultCode2, ResultCode.NOT_FOUND);
    Assert.assertEquals(resultCode3, ResultCode.NOT_FOUND);
    Assert.assertEquals(resultCode4, ResultCode.NOT_FOUND);
    Assert.assertEquals(resultCode5, ResultCode.NOT_FOUND);
    Assert.assertEquals(resultCode6, ResultCode.NOT_FOUND);
    Assert.assertEquals(resultCode7, ResultCode.FAIL);
  }
Exemple #21
0
  protected void onDestroy() {
    Log.d(DEBUG_TAG, "SHARED PREFERENCES");

    Log.d(
        DEBUG_TAG, "Username is: " + mGameSettings.getString(GAME_PREFERENCES_USERNAME, "Not set"));
    Log.d(DEBUG_TAG, "Email is: " + mGameSettings.getString(GAME_PREFERENCES_SCHOOL, "Not set"));

    // We are not saving the password yet
    Log.d(
        DEBUG_TAG, "Password is: " + mGameSettings.getString(GAME_PREFERENCES_PASSWORD, "Not set"));
    // We are not saving the date of birth yet
    Log.d(
        DEBUG_TAG,
        "DOB is: "
            + DateFormat.format("MMMM dd, yyyy", mGameSettings.getLong(GAME_PREFERENCES_DOB, 0)));
    super.onDestroy();
  }
 @Override
 public void readResponse(ServerResponse response) {
   if (response != null && response.getStatusCode() == HTTP_OK) {
     try {
       List<Quiz> quizzes = Quiz.generateList(response.getEntity());
       if (quizzes.size() == 0) {
         displayMessage(MSG_NO_QUIZ);
       } else {
         quizList.setAdapter(
             new ArrayAdapter<Quiz>(
                 this, android.R.layout.simple_list_item_1, android.R.id.text1, quizzes));
         noQuiz = false;
       }
     } catch (JSONException ex) {
       displayMessage(MSG_FAILED);
     }
   } else {
     displayMessage(MSG_FAILED);
   }
 }
Exemple #23
0
 public String getNextQuestion(int level) {
   int currMax = super.getMaxInt(level, 5);
   type = randomNum.nextInt(6);
   System.out.println("type=" + type);
   String question;
   int correctAnswer = 0;
   int a = randomNum.nextInt(currMax);
   int b = randomNum.nextInt(currMax);
   if (a > b) {
     int temp = a;
     a = b;
     b = temp;
   }
   ++b; // make sure no divide by zero
   if (type == FRACTION_TO_DECIMAL) {
     correctAnswer = ((a * 1000 / b) + 5) / 10;
     question = "what is " + a + "/" + b + " as a decimal (2 decimal places)?";
   } else if (type == FRACTION_TO_PERCENTAGE) {
     correctAnswer = ((a * 1000 / b) + 5) / 10;
     question = "what is " + a + "/" + b + " as a percentage?";
   } else if (type == DECIMAL_TO_PERCENTAGE) {
     correctAnswer = ((a * 1000 / b) + 5) / 10;
     question = "what is " + (correctAnswer / 100.0) + " as a percentage?";
   } else if (type == PERCENTAGE_TO_FRACTION) {
     correctAnswer = ((a * 1000 / b) + 5) / 10;
     question = "what is " + correctAnswer + "% as a fraction (a / b)?";
   } else if (type == DECIMAL_TO_FRACTION) {
     correctAnswer = ((a * 1000 / b) + 5) / 10;
     question = "what is " + (correctAnswer / 100.0) + " as a fraction (a / b)?";
   } else { // percentage to decimal
     correctAnswer = ((a * 1000 / b) + 5) / 10;
     question = "what is " + correctAnswer + "%" + " as a decimal (2 decimal places)?";
   }
   super.setQuestionAnswer(question, correctAnswer);
   return question;
 }
Exemple #24
0
 public static void testHTMLAndXML(Quiz quiz) {
   String[] ans1 = {"Choose..", "Fish", "Dynosaur", "Crocodilia"};
   String[] questions1 = {
     "tyrannosaurus.jpg",
     "shark.jpg",
     "alligator.jpg",
     "crocodile.jpg",
     "apatosaurus.jpg",
     "guppy.jpg"
   };
   Match m1 =
       new Match(
           "Match Question 1",
           "1",
           "choose the right answer to match the picture on the left",
           "f",
           questions1,
           "t",
           ans1,
           "f");
   String[] questions2 = {
     "Tyrannosaurus", "Shark", "Alligator", "Crocodile", "Apatosaurus", "Guppy"
   };
   Match m2 =
       new Match(
           "Match Question 2",
           "1",
           "choose the right answer to match the description on the left",
           "f",
           questions2,
           "f",
           ans1,
           "f");
   quiz.addQuestion(m1);
   quiz.addQuestion(m2);
 }
 @Override
 public void writeToParcel(Parcel dest, int flags) {
   super.writeToParcel(dest, flags);
   dest.writeString(getAnswer());
 }
  /** generate a question with new random parameter */
  public void generateAquestion() {
    if (eq != null) {
      try {
        eq.randomVar();
        if (questionText == null) {
          questionText = eq.getFormedEquation();
        }
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      HashMap<String, Var> variables = eq.getVariables();
      variablesList = new ArrayList<Map.Entry<String, Var>>();
      Iterator<Entry<String, Var>> it = variables.entrySet().iterator();
      while (it.hasNext()) {
        Map.Entry<String, Var> pair = (Map.Entry<String, Var>) it.next();
        variablesList.add(pair);
      }
      stringList = new ArrayList<String>();

      // if newStrFlag is true, start a new string, or continue append on the last one.
      Boolean newStrFlag = true;
      String textArr[] = questionText.split("\\[[^\\] ]+\\]");
      Matcher matcher = Pattern.compile("\\[([^\\] ]+?)\\]").matcher(questionText);

      if (randomPosition) questionIndex = Quiz.random(0, textArr.length - 1);
      else questionIndex = eq.getNumberVariable();
      for (int i = 0; i < textArr.length; ++i) {
        String text = textArr[i];
        if (newStrFlag) {
          stringList.add(text);
          newStrFlag = false;
        } else {
          stringList.set(stringList.size() - 1, stringList.get(stringList.size() - 1) + text);
        }
        if (matcher.find()) {
          String valStr = matcher.group(1);
          if (i == questionIndex) {
            newStrFlag = true;
            if (valStr.equals(eq.getEquation()) || valStr.equals("?")) {
              currentCorrectAnswer = eq.getCorrectAnswer();
            } else {
              currentCorrectAnswer = variables.get(valStr).getOperand();
            }
          } else if (valStr.equals(eq.getEquation()) || valStr.equals("?")) {
            double operand = eq.getCorrectAnswer();
            stringList.set(stringList.size() - 1, stringList.get(stringList.size() - 1) + operand);
          } else {
            double operand = variables.get(valStr).getOperand();
            stringList.set(stringList.size() - 1, stringList.get(stringList.size() - 1) + operand);
          }
        }
      }
      if (newStrFlag) {
        stringList.add("");
      }
      System.out.println(currentCorrectAnswer);

      ArrayList<Answer> ans = new ArrayList<Answer>();
      ans.add(new Answer(new AnswerText(String.valueOf(currentCorrectAnswer))));
      setAns(ans);
    }
  }
Exemple #27
0
 public String getJSONFromContents() {
   Quiz quiz = getQuizFromContents();
   StringBuilder stringBuilder = new StringBuilder();
   quiz.encodeAsJSONItem().appendJSON(stringBuilder);
   return stringBuilder.toString();
 }
Exemple #28
0
  public static Quiz test1() {
    Quiz quiz = new Quiz();
    quiz.setId(1);
    quiz.setName("Animals");
    // for multiChoiceDropDown
    QuestionContainer qc =
        new QuestionContainer(
            new Displayable[] {
              new Text("What is a dinosaur?"),
              new MultiChoiceDropdown(
                  1,
                  1,
                  new Answer[] {
                    new Answer("T-Rex", true), new Answer("Shark"), new Answer("mouse")
                  })
            });
    quiz.addQuestionContainer(qc);

    // for Equation and Fillin, no WarningPattern
    Var x = new Var("x", 0, 99, 1);
    Var y = new Var("y", 0, 99, 1);
    HashMap<String, Var> map = new HashMap<String, Var>();
    map.put("x", x);
    map.put("y", y);
    Equation eq = new Equation("x+y", map);

    qc =
        new QuestionContainer(
            new Displayable[] {new Text("What is "), eq, new Text("?"), new FillIn(3, 1, 1)});
    quiz.addQuestionContainer(qc);

    // for Equation and Fillin, with WarningPattern
    Var x1 = new Var("x1", 0, 99, 1);
    Var y1 = new Var("y1", 0, 99, 1);
    HashMap<String, Var> map1 = new HashMap<String, Var>();
    map.put("x1", x1);
    map.put("y1", y1);
    Equation eq1 = new Equation("x1+y1", map);

    qc =
        new QuestionContainer(
            new Displayable[] {
              new Text("What is "),
              eq1,
              new Text("?"),
              new FillIn(40, 1, 1, null, new NumberWarningPattern(3), null, null)
            });
    quiz.addQuestionContainer(qc);

    qc =
        new QuestionContainer(
            new Displayable[] {
              new Video("1.mpg"),
              new Text("Describe the main character in the video in 200 words or less"),
              new Essay()
            });
    quiz.addQuestionContainer(qc);

    qc =
        new QuestionContainer(
            new Displayable[] {
              new Text("Listen to the audio clip and write down the words"),
              new Audio("1.mp3"),
              new FillIn(5, 1, 1)
            });
    quiz.addQuestionContainer(qc);

    // create two random 3x3 matrices filled with integers [-3..3]
    Matrix m1 = new Matrix(3, 3, -3, 3);
    Matrix m2 = new Matrix(3, 3, -3, 3);
    // create a 3x3 matrix worth 1 point, level 1
    MatrixQuestion m3 = new MatrixQuestion(1, 1, 3, 3);
    quiz.addQuestionContainer(
        qc =
            new QuestionContainer(
                new Displayable[] {
                  new Text("Solve the matrix addition"), m1, new Text("+"), m2, m3
                }));

    return quiz;
  }
Exemple #29
0
  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_util_settings);

    mGameSettings = getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE);
    final EditText usernameText = (EditText) findViewById(R.id.EnterUsername);
    final TextView error = (TextView) findViewById(R.id.eror2);

    /**
     * usernameText.addTextChangedListener(new TextWatcher(){ @Override public void
     * afterTextChanged(Editable arg0) { // TODO Auto-generated method stub
     * App42API.initialize(getApplicationContext(),
     * "33febecb03a579e972755eccde307dd94a279b5cfe348f845b8762f8e3feb2d6",
     * "b5be405b4e76d40a94cdc01250311205b5a7c7b2dc4d003714f24d0df3e219f8");
     *
     * <p>final UserService userService = App42API.buildUserService();
     * App42API.setOfflineStorage(true);
     *
     * <p>userService.getAllUsers(); for(int i=0;i<userService.getAllUsers().size();i++){ String
     * we=userService.getAllUsers().get(i).getUserName().toString(); String ent =
     * usernameText.getText().toString(); if(ent.equals(we)){
     * error.setText(R.string.settings_username_already_used); }else{ error.setText("Username is
     * unique"); }
     *
     * <p>} } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int
     * arg3) { // TODO Auto-generated method stub
     *
     * <p>} @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
     * // TODO Auto-generated method stub
     *
     * <p>}
     *
     * <p>});
     */
    usernameText.setOnKeyListener(
        new View.OnKeyListener() {
          public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN)
                && (keyCode == KeyEvent.KEYCODE_ENTER)) {
              String strUsernameToSave = usernameText.getText().toString();
              // TODO: Save Nickname setting (strNicknameToSave)
              Editor editor = mGameSettings.edit();
              editor.putString(GAME_PREFERENCES_USERNAME, strUsernameToSave);
              editor.commit();
              usernameText.setText(strUsernameToSave);

              return true;
            }
            return false;
          }
        });

    ImageButton ava = (ImageButton) findViewById(R.id.avatar);

    ava.setOnClickListener(
        new View.OnClickListener() {

          @Override
          public void onClick(View v) {
            // TODO Auto-generated method stub
            showDialog(AVATAR_DIALOG_ID);
          }
        });

    final EditText schoolText = (EditText) findViewById(R.id.enterschool);
    schoolText.setOnKeyListener(
        new View.OnKeyListener() {
          public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN)
                && (keyCode == KeyEvent.KEYCODE_ENTER)) {
              String strEmailToSave = schoolText.getText().toString();
              // TODO: Save Nickname setting (strNicknameToSave)
              Editor editor = mGameSettings.edit();
              editor.putString(GAME_PREFERENCES_SCHOOL, strEmailToSave);
              editor.commit();
              schoolText.setText(strEmailToSave);
              return true;
            }
            return false;
          }
        });

    final EditText emailText = (EditText) findViewById(R.id.enterEmail);
    emailText.setOnKeyListener(
        new View.OnKeyListener() {
          public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN)
                && (keyCode == KeyEvent.KEYCODE_ENTER)) {
              String strEmail = emailText.getText().toString();
              // TODO: Save Nickname setting (strNicknameToSave)
              Editor editor = mGameSettings.edit();
              editor.putString(GAME_PREFERENCES_EMAIL, strEmail);
              editor.commit();
              emailText.clearComposingText();
              emailText.setText(null);
              emailText.setText(strEmail);
              return true;
            }
            return false;
          }
        });

    pass = (Button) findViewById(R.id.SetPassword);
    pass.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View view) {
            // TODO Auto-generated method stub
            showDialog(PASSWORD_DIALOG_ID);
          }
        });

    pickDate = (Button) findViewById(R.id.SetDate);
    pickDate.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            showDialog(DATE_DIALOG_ID);
          }
        });

    final Button save = (Button) findViewById(R.id.saveSett);
    save.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            // TODO Auto-generated method
            String username = usernameText.getText().toString();
            String schl = schoolText.getText().toString();
            Editor editor = mGameSettings.edit();
            editor.putString(GAME_PREFERENCES_SCHOOL, schl);
            editor.putString(GAME_PREFERENCES_USERNAME, username);
            editor.commit();
            usernameText.setText(null);
            schoolText.setText(null);
            usernameText.setText(username);
            schoolText.setText(schl);

            Intent i = new Intent(getApplicationContext(), UtilMenu.class);
            startActivity(i);
          }
        });
  }
Exemple #30
0
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_util_scores);
    mGameSettings = getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE);
    final TabHost tbh = (TabHost) findViewById(R.id.tabhost);
    tbh.setup();
    App42API.initialize(
        this,
        "33febecb03a579e972755eccde307dd94a279b5cfe348f845b8762f8e3feb2d6",
        "b5be405b4e76d40a94cdc01250311205b5a7c7b2dc4d003714f24d0df3e219f8");

    TabSpec FunScoresTab = tbh.newTabSpec("FunTab");
    FunScoresTab.setIndicator(
        getResources().getString(R.string.Fu),
        getResources().getDrawable(android.R.drawable.star_on));
    FunScoresTab.setContent(R.id.Scrollfun);
    tbh.addTab(FunScoresTab);

    TextView d = (TextView) findViewById(R.id.nmf);
    TextView ld = (TextView) findViewById(R.id.hilvlf);
    if (mGameSettings.contains(GAME_HIGHEST_LEVEL)) {
      String hl = mGameSettings.getString(GAME_HIGHEST_LEVEL, null);
      ld.setText(hl);

    } else {
      ld.setText("Not Played");
    }
    if (mGameSettings.contains(GAME_PREFERENCES_USERNAME)) {
      String q = mGameSettings.getString(GAME_PREFERENCES_USERNAME, null);
      d.setText(q);

    } else {
      d.setText("Username not set");
    }

    TextView e = (TextView) findViewById(R.id.scoref);
    if (mGameSettings.contains(GAME_PREFERENCES_SCORE_FUN)) {
      String ght = mGameSettings.getString(GAME_PREFERENCES_SCORE_FUN, null);
      e.setText(ght);
    }

    TabSpec SchoolScoresTab = tbh.newTabSpec("SchoolTab");
    SchoolScoresTab.setIndicator(
        getResources().getString(R.string.shu),
        getResources().getDrawable(android.R.drawable.star_on));
    SchoolScoresTab.setContent(R.id.ScrollSchool);
    tbh.addTab(SchoolScoresTab);

    TextView sm = (TextView) findViewById(R.id.nmMath);

    TextView sen = (TextView) findViewById(R.id.nmeng);
    TextView sk = (TextView) findViewById(R.id.nmkis);
    TextView ssi = (TextView) findViewById(R.id.nmsci);
    TextView ssst = (TextView) findViewById(R.id.nmsst);
    TextView scr = (TextView) findViewById(R.id.nmcre);

    TextView lm = (TextView) findViewById(R.id.hilvlMath);
    TextView len = (TextView) findViewById(R.id.hilvlEng);
    TextView lk = (TextView) findViewById(R.id.hilvlKis);
    TextView lsi = (TextView) findViewById(R.id.hilvlSci);
    TextView lsst = (TextView) findViewById(R.id.hilvlSst);
    TextView lcr = (TextView) findViewById(R.id.hilvlCre);

    mGameSettings = getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE);

    if (mGameSettings.contains(GAME_PREFERENCES_USERNAME)) {
      String q = mGameSettings.getString(GAME_PREFERENCES_USERNAME, null);

      sm.setText(q);
      sen.setText(q);
      sk.setText(q);
      ssi.setText(q);
      ssst.setText(q);
      scr.setText(q);

    } else {

      sm.setText("Username not set");
      sen.setText("Username not set");
      sk.setText("Username not set");
      ssi.setText("Username not set");
      ssst.setText("Username not set");
      scr.setText("Username not set");
    }

    if (mGameSettings.contains(GAME_HIGHEST_LEVEL_MATH)) {
      String hlM = mGameSettings.getString(GAME_HIGHEST_LEVEL_MATH, null);
      lm.setText(hlM);

    } else {
      lm.setText("Not Played");
    }
    if (mGameSettings.contains(GAME_HIGHEST_LEVEL_ENG)) {
      String hlEng = mGameSettings.getString(GAME_HIGHEST_LEVEL_ENG, null);
      len.setText(hlEng);

    } else {
      len.setText("Not Played");
    }
    if (mGameSettings.contains(GAME_HIGHEST_LEVEL_KIS)) {
      String hlKis = mGameSettings.getString(GAME_HIGHEST_LEVEL_KIS, null);
      lk.setText(hlKis);

    } else {
      lk.setText("Not Played");
    }
    if (mGameSettings.contains(GAME_HIGHEST_LEVEL_SCI)) {
      String hlSci = mGameSettings.getString(GAME_HIGHEST_LEVEL_SCI, null);
      lsi.setText(hlSci);

    } else {
      lsi.setText("Not Played");
    }
    if (mGameSettings.contains(GAME_HIGHEST_LEVEL_SOCI)) {
      String hlSS = mGameSettings.getString(GAME_HIGHEST_LEVEL_SOCI, null);
      lsst.setText(hlSS);

    } else {
      lsst.setText("Not Played");
    }
    if (mGameSettings.contains(GAME_HIGHEST_LEVEL_CRE)) {
      String hlCre = mGameSettings.getString(GAME_HIGHEST_LEVEL_CRE, null);
      lcr.setText(hlCre);

    } else {
      lcr.setText("Not Played");
    }

    TextView m = (TextView) findViewById(R.id.scoreMath);
    if (mGameSettings.contains(GAME_PREFERENCES_SCORE_MATH)) {
      String sMath = mGameSettings.getString(GAME_PREFERENCES_SCORE_MATH, null);
      m.setText(sMath);

    } else {
      m.setText("Not Played");
    }
    TextView en = (TextView) findViewById(R.id.scoreeng);
    if (mGameSettings.contains(GAME_PREFERENCES_SCORE_ENG)) {
      String sEng = mGameSettings.getString(GAME_PREFERENCES_SCORE_ENG, null);
      en.setText(sEng);

    } else {
      en.setText("Not Played");
    }
    TextView k = (TextView) findViewById(R.id.scorekis);
    if (mGameSettings.contains(GAME_PREFERENCES_SCORE_KIS)) {
      String sKis = mGameSettings.getString(GAME_PREFERENCES_SCORE_KIS, null);
      k.setText(sKis);

    } else {
      k.setText("Not Played");
    }
    TextView s = (TextView) findViewById(R.id.scoresci);
    if (mGameSettings.contains(GAME_PREFERENCES_SCORE_SCI)) {
      String sSci = mGameSettings.getString(GAME_PREFERENCES_SCORE_SCI, null);
      s.setText(sSci);

    } else {
      s.setText("Not Played");
    }
    TextView sst = (TextView) findViewById(R.id.scoresst);
    if (mGameSettings.contains(GAME_PREFERENCES_SCORE_SST)) {
      String sSST = mGameSettings.getString(GAME_PREFERENCES_SCORE_SST, null);
      sst.setText(sSST);

    } else {
      sst.setText("Not Played");
    }
    TextView cr = (TextView) findViewById(R.id.scorecre);
    if (mGameSettings.contains(GAME_PREFERENCES_SCORE_CRE)) {
      String sCRE = mGameSettings.getString(GAME_PREFERENCES_SCORE_CRE, null);
      cr.setText(sCRE);

    } else {
      cr.setText("Not Played");
    }

    TabSpec LeaderBoardTab = tbh.newTabSpec("LeaderBoardTab");
    LeaderBoardTab.setIndicator(
        getResources().getString(R.string.lead),
        getResources().getDrawable(android.R.drawable.star_on));
    LeaderBoardTab.setContent(R.id.list);
    tbh.addTab(LeaderBoardTab);

    uploadScoresleaderboard();
  }