Courses‎ > ‎AP Computer Science‎ > ‎Konstantinovich‎ > ‎

notes

2017-11-16 SSH Keys!

posted Nov 16, 2017, 1:18 PM by Konstantinovich Samuel

SSH keys are used to give you a secure way to access another computer (host) without needing to remember or type your password. After you log in to a linux/mac computer, you can generate a key that will let you log in to OTHER computers without a password. You would generate the key along with a comment like this:
ssh-keygen -t rsa -b 4096 -C "Comment"

Comments are useful if you have multiple computers, you can identify which computer you are using e.g.  -C "stuycsLab"  / -C "macbook"   / -c "DesktopHome"  etc

After creating ssh keys, you can upload them to any linux server that you have SSH access to. This can be conveniently done using the ssh-copy-id tool. Like this:

ssh-copy-id -i ~/.ssh/KEY_NAME user@host

You will then be prompted for your password on that host. After you type in your password you will be able to ssh into the host without using your password. 


The commands I used in class follow this post. They allow me to log into any stuycs lab machine with ssh, FROM any other stuycs lab machine. 

ssh-keygen -t rsa -b 4096 -C "konstans-Laptop"

ssh-copy-id -i ~/.ssh/id_rsa.pub  konstans@marge.stuy.edu

I could also copy it to my digital ocean machine!

ssh-copy-id -i ~/.ssh/id_rsa.pub  konstans@IP_ADDRESS_OF_MY_DO_COMPUTER

I left out the host for security reasons.



2017-11-15

posted Nov 15, 2017, 9:58 AM by Konstantinovich Samuel   [ updated Nov 15, 2017, 10:06 AM ]

GOAL: Practice AP question / Quiz Question!!!!!

My goal is to have you do well, so my proposition:
1. Give a practice quiz now, and get you all acclimated to AP style questions. 
Try this first (only @ stuy)
file:///home/support/konstans/public/APQuestion.pdf
Otherwise Try the file attached at the bottom of the post!

OR

2. Make this a real quiz and watch you all squirm.

I select option 1. Open the PDF, start reading, and write your answers on paper!



2017-11-13

posted Nov 13, 2017, 9:53 AM by Konstantinovich Samuel

Final update on word search:

Goal: Command Line Parsing!


Use a Random object to re-create your random number sequence and reproduce errors / issues.

import java.util.*;
public class rerandom{
    public static void main(String[]args){
	int seed = (int)(Math.random()*100000);
	//seed = 17127;
        //change this to any seed you want.
	System.out.println("This is your seed: "+seed);
	Random randgen = new Random(seed);

	for(int i=0;i<10;i++){
	    System.out.println(randgen.nextInt());
	}
    }
}


Final revision, your puzzle generator is due Monday 11/21/2016 8am.
Overview of new main behavior:
java Driver [rows cols filename [randomSeed [answers]]]  
//square brackets mean optional
This means that each of these are valid:
java Driver
java Driver rows cols filename
java Driver rows cols filename randomSeed  
java Driver rows cols filename randomSeed answers  

1. If no command line arguments are specified, print directions to tell the user how to run the program.
2. rows and cols are the dimensions of the puzzle, filename is the name of the plain text file that contains words. If they are the only parameters passed, you should print the random seed with the puzzle. 
3. The randomSeed can be changed to force the same puzzle to occur again, so you can print the puzzle and the answers later.
4. If the randomSeed is provided, you can have a 4th parameter to display answers. You trigger answer mode by passing the value "key" into the answers parameter. Omitting the answers parameter, or passing any other values will just display the normal puzzle, and not show the answer.
5. Any invalid formatting of the command line arguments should print directions.

so:

java Driver 20 30
 names.txt 124850
//would print the 20x30 puzzle seeded by 124850
java Driver 20 30 names.txt  124850 fish
//would print the 20x30 puzzle seeded by 124850
java Driver 20 30 names.txt  124850 key 
//would print the 20x30 answer key for the puzzle seeded by 124850    (all 3 of these will match)

java Driver 10 20 fish.txt 8230 oops
java Driver 10 20 fish.txt 8230     
//would print the 10x20  puzzle seeded by 8230  (both of these will match, neither are answer keys)

Changing the seed, dimensions of the puzzle, or quantity of words, even by a single number/word, will cause a completely different puzzle to occur. 



Write your main in your WordSearch. I will test your program with the 4 different ways of using it above.
java WordSearch
java WordSearch r c mydatafile.txt 
java WordSearch r c mydatafile.txt s
java WordSearch r c mydatafile.txt s key

Then use your main to construct the object and output the appropriate puzzle!


Things to note:
- I am not checking your WordSearch methods! I don't care what you called them. This assignment is a main program that is tested by changing the command line arguments!
- You will need at least one text file to test this. You should have a few, including one with words that are easy to spot (special Characters or repeated letters.)
- You should have public methods in your WordSearch to look at:  
    *puzzle
    *list of added words
    *solution
    *random seed

2017-11-10

posted Nov 10, 2017, 10:17 AM by Konstantinovich Samuel   [ updated Nov 12, 2017, 1:02 PM ]

WordSearch updates

1. Make a plain text file "words.txt" and fill it with whatever words you like. 
   -Put in words with different lengths to help you test
Your text file should be formatted like this:

ham
beef
sushi
turkey
venison
meatloaf



Update to your WordSearch with new instance variables:

//all words from a text file get added to wordsToAdd, indicating that they have not yet been added
private ArrayList<String> wordsToAdd;

//all words that were successfully added get moved into wordsAdded.
private ArrayList<String> wordsAdded;

//a random Object to unify your random calls
private Random randgen;



Update your wordSearch with the methods discussed in class:

//Two Constructors:
public WordSearch( int rows, int cols, String fileName)

public WordSearch( int rows, int cols, String fileName, int randSeed)

//Two Methods
private boolean addWord( int r, int c, String word, int rowIncrement, int colIncrement)
    -when colIncrement and rowIncrement are both 0, return false. 
    -when you successfully add a word, move the word from wordsToAdd to wordsAdded, then return true.
    -return false otherwise. 

private boolean addAllWords()
    -Attempt to add all of the words from the wordsToAdd list. Keep trying many times* or until you run out.
    -Experiment with *many times, maybe 1000 is enough, maybe 10000. If it is slow, cut it down!



Finally, make sure your toString verifies your words are adding properly. Feel free to print the object inside of its own methods as a debug!!!!





import java.util.*; //random, scanner, arraylist
import java.io.*; //file, filenotfoundexception

public class WordSearch{
    private char[][]data;
    private Random randgen;
    private ArrayList<String>wordsToAdd;
    private ArrayList<String>wordsAdded;

}

2017-11-09 HW

posted Nov 9, 2017, 10:07 AM by Konstantinovich Samuel   [ updated Nov 9, 2017, 10:16 AM ]

Goal: Terminal arguments, Files



Terminal commands often have arguments!

Here is how we access them:

//for easy printing of arrays
import java.util.Arrays;
public class Demo1{
  public static void main(String[]args){
    //args has your terminal options
    System.out.println(Arrays.toString(args));
  }
}


Now call your program on the terminal:

java Demo1 fish 123 abba good day

This is like saying: 
    args = {"fish", "123", "abba", "good", "day"};


This can be used to pass values into the program:

public class Demo1b{
  public static void main(String[]args){
    int defaultSize = 10;    

    //get a value from the arguments
    if(args.length > 0){
        defaultSize = Integer.parseInt(args[0]);
    }
    
    //DO STUFF WITH defaultSize

  }  
}






Now let us look at files:

//for file stuff:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Demo2{
  public static void main(String[]args){
    String fileName = "file.txt";
    try{
      File f = new File(fileName);//can combine
      Scanner in = new Scanner(f);//into one line
      
        //NOW read the file here...
      
    }catch(FileNotFoundException e){
      System.out.println("File not found: " + fileName);
      //e.printStackTrace();
      System.exit(1);
    }

    //How can we use the file here? Where should you put it?
  }
}




Reading the file line by line:

while(in.hasNext()){
        String line = in.nextLine();
        //do something with line
        System.out.println(line);
}

Reading the file word by word:

while(in.hasNext()){
        String word = in.next();
        //do something with word
        System.out.println(word);
}

The java Scanner is super useful! It is an easy way to parse through files.





Now let us look at Random:

import java.util.Random;
public class DemoRandom{
  public static void main(String[]args){
    Random rng = new Random();
    for(int i =  0; i < 5; i++ ){
      System.out.println(rng.nextInt() % 1000);
    }
    System.out.println();
    rng = new Random(100);//seed of 100 is stored.
    for(int i =  0; i < 5; i++ ){
      System.out.println(rng.nextInt() % 1000);
    }
  }
}



Homework:   

   /**Attempts to add a given word to the specified position of the WordGrid.
     *The word is added from top left to bottom right, must fit on the WordGrid,
     *and must have a corresponding letter to match any letters that it overlaps.
     *
     *@param word is any text to be added to the word grid.
     *@param row is the vertical locaiton of where you want the word to start.
     *@param col is the horizontal location of where you want the word to start.
     *@return true when the word is added successfully. When the word doesn't fit,
     *or there are overlapping letters that do not match, then false is returned.
     */
    public boolean addWordDiagonal(String word,int row, int col){
    }

-How are Horizontal/Vertical/Diagonal the same/different?
-How can you combine these methods into a much more flexible method?

2017-11-08

posted Nov 8, 2017, 8:47 AM by Konstantinovich Samuel   [ updated Nov 8, 2017, 1:00 PM ]

Goal: Word search design! 

Puzzles like this are common:

U A I F L Q B I D R T V D S S  

D R H N N N K W R N E A P H F  

U J Y M B O A X U S L O G J N  

N U X D L Z E P C A P X V V I  

B O D S J O T X S C L I X R D  

C A C L Y Y S I O T A N U E B  

K H X N M P P R E S L U E T C  

E K O I K I N T F S T T B S S  

S G D C V C D I U B X Z H B I  

H O N F O Z Y P F K S W J O W  

Z E O W V L E A R H R E R L R  

Q W X A T R A O Z M S J E U N  

Z C N Y M V N T O Z U I F L L  

N T W A Y A S Q E L I D F Q X  

X H N T K S O H J W O P J Z X
	 
FIND THE FOLLOWING WORDS:
FISH        LOBSTER    PIZZA       CHOCOLATE
STEAK       SALAD      POPCORN     THOR
LOKI        ZOD        SUPERMAN



You are writing a word search generator. 

The class should be able to:
1. generate an N by M puzzle 
    (A puzzle includes a list of words, and a grid of letters with those words hidden.)
2. add a bunch of words randomly 
3. show the puzzle , or the solution.

Nice features we can add:
4. Use a plain text file as a list of words to add to the puzzle.
5. Be able to reproduce the same puzzle/solution at a later date. This is a VERY useful feature.



IN CLASS:

 Brainstorm with your neighbors on the following points:
 - How to design a data structure to hold the puzzle, words, solution, etc.
 - How the overall program would place the words and how you could view a solution.
 - What tools in java do you need but not have yet?





HW:
Here is a base set of methods to get you started! Complete them!

public class WordSearch{
    private char[][]data;

    /**Initialize the grid to the size specified 
     *fill all of the positions with '_'
     *@param row is the starting height of the WordSearch
     *@param col is the starting width of the WordSearch
     */
    public WordSearch(int rows,int cols){
    }

    /**Set all values in the WordSearch to underscores'_'*/
    private void clear(){
    }

    /**The proper formatting for a WordGrid is created in the toString.
     *@return a String with each character separated by spaces, and rows
     *separated by newlines.
     */
    public String toString(){
    }


    /**Attempts to add a given word to the specified position of the WordGrid.
     *The word is added from left to right, must fit on the WordGrid, and must
     *have a corresponding letter to match any letters that it overlaps.
     *
     *@param word is any text to be added to the word grid.
     *@param row is the vertical locaiton of where you want the word to start.
     *@param col is the horizontal location of where you want the word to start.
     *@return true when the word is added successfully. When the word doesn't fit,
     * or there are overlapping letters that do not match, then false is returned 
     * and the board is NOT modified.
     */
    public boolean addWordHorizontal(String word,int row, int col){
    }

   /**Attempts to add a given word to the specified position of the WordGrid.
     *The word is added from top to bottom, must fit on the WordGrid, and must
     *have a corresponding letter to match any letters that it overlaps.
     *
     *@param word is any text to be added to the word grid.
     *@param row is the vertical locaiton of where you want the word to start.
     *@param col is the horizontal location of where you want the word to start.
     *@return true when the word is added successfully. When the word doesn't fit,
     *or there are overlapping letters that do not match, then false is returned.
     *and the board is NOT modified.
     */
    public boolean addWordVertical(String word,int row, int col){
    }
}

2017-11-06

posted Nov 6, 2017, 9:59 AM by Konstantinovich Samuel   [ updated Nov 6, 2017, 11:25 AM ]

Goal: Arrays in 2D!

int[][]a = new int[4][3];

Remember row vs col:
                 Col 0     Col 1   Col 2
Row 0        a[0][0]   a[0][1] a[0][2]
Row 1        a[1][0]   a[1][1] a[1][2]
Row 2        a[2][0]   a[2][1] a[2][2]
Row 3        a[3][0]   a[3][1] a[3][2]



Practice problems/ Homework, due Monday. Sorry for late post!

2D Array Practice: 


Assume the inputs to your methods are valid 2d arrays. They do NOT have to be rectangular. 
Any method that tries to sum a row/column of a non-existant part of an array should count that value as a 0.
e.g.

[
 [1 2 3]
 [3 3]
 [4 1 1 9]
]

-summing column 2 would be (3 + 1) or just 4. 
-summing column 3 would be 9.
-summing row 1 would be (3+ 3) or 6,
-summing row 3 would be 0 since there are no values.

public class ArrayMethods{

   //PART 1 (these two methods are almost the same! -- I count them as 1 problem)
   public static int rowSum(int[][] AR, int x){}
    //returns the sum of the elements in Row x of AR. 

   public static int columnSum(int[][] AR, int x){}
    //returns the sum of the elements in Column x of AR (careful with rows of different lengths!).

   //PART 2
   public static int[] allRowSums(int[][] AR){}
    //calculates the row sum for every row and returns each of the values in an array. 
    //Index i of the return array contains the sum of elements in row i.

    public static int[] allColSums(int[][] AR){}
    //calculates the column sum for every column and returns each of the values in an array. 
    //Index i of the return array contains the sum of elements in column i, ignoring any rows that are too short.
    //The length of the returned array should be the length of the LONGEST array in AR.

   //PART 3 (just use your part 2 answer... look at the difference in the readability)
   public static boolean isRowMagic(int[][] AR){}
     //checks if the array is row-magic (this means that every row has the same row sum).

   public static boolean isColumnMagic(int[][] AR){}
    //checks if the array is column-magic (this means that every column has the same column sum).

}



Coming up next: You are writing a word search generator. 

The program should be able to:
1. generate an N by M puzzle 
    (A puzzle includes a list of words, and a grid of letters with those words hidden.)
2. generate a solution if requested.

Nice features we can add:
3. Use a plain text file as a list of which which words can be hidden.
4. Be able to reproduce the same puzzle/solution at a later date. This is a VERY useful feature.


IN CLASS:

 Brainstorm with your neighbors on the following points:
 - How to design a data structure to hold the puzzle, words, solution, etc.
 - How the overall program would place the words and how you could view a solution.
 - What tools in java do you need but not have yet?

2017-11-03

posted Nov 2, 2017, 8:24 PM by Konstantinovich Samuel

Look at the ArrayList:
https://www.javatpoint.com/java-arraylist

Notice that it has the same methods as the SuperArray, but it works with any object type!!!

Part I. Practice with the following: (print out after each set of commands)
1. Create an ArrayList of Strings
2. Add the strings "A" through "Z" (all the letters in caps)
3. Replace the vowels with lowercase versions. (Hint, don't count, use the methods to help you figure out position!)
4. Remove Q R S and T from the list. 
5. Move B C and D to the end of the list. 

Part II. 
Complete CodingBat String-3
countYZ 
withoutString 
equalIsNot

Part III.
Finish and submit your OrderedSuperArray on the homework server. 


Part IV. (Optional!) Twice a year we participate in the Pclassic competition at UPenn.
November 18th is this semester's competition.
The cost would be $30 per student for the chartered bus. 

Most of you would want to do the NOVICE problem set. 
It is dangerous to go alone take this: http://pclassic.org/problems
If you want to go, try one problem set by yourself and see what you can do. THEN make a team of 4 people sit down with your team to try to solve another problem set.
You will be much more prepared and confident if you practice!!!!

2017-11-01

posted Nov 1, 2017, 10:21 AM by Konstantinovich Samuel   [ updated Nov 1, 2017, 12:40 PM ]

Goal: Ordered Super Array and Exceptions


How do we create meaningful error messages?

Runtime errors that stop your program:

Syntax is:
throw new ExceptionConstructor();

e.g.
throw new IndexOutOfBoundsException();
throw new UnsupportedOperationException();



Assignment: Due Friday Morning 
Modify your super array, and your OrderedSuperArray

SuperArray
Add one extra constructor:

SuperArray(int startingCapacity)


OrderedSuperArray

Since Constructors are not inherited:

public OrderedSuperArray()  // You already did this!

public OrderedSuperArray(int capacity)  //-> just call super( capacity );

Do this constructor last:

    public OrderedSuperArray(String [] ary) //-> call super and add all the elements


Methods you need to change:

0. CONVERT Your printed error messages in SuperArray into exceptions.

1. set(int index, String element)

    - throw an UnsupportedOperationException

2. add(int index, String element) 

    call add(String) and ignore the index. You should already have this. 

3. You can make the following methods more efficient using a binary Search.  (Discuss today)

    indexOf(String element) HINT: make indexOfBinary(String element) , then compare to the original working method!  

    lastIndexOf(String element)

3. add (String element) 

    You should have already written a private method to find the index that you want to add the element to:

         private int findIndex( String) - a linear search for the proper location.

    Now you can write this alternate version and test against the original findIndex method!

         private int findIndexBinary(String) - a binary search for the proper location




 

2017-10-31

posted Oct 30, 2017, 8:21 PM by Konstantinovich Samuel

Goal: Give in to your hatred... of Java. 

IMPORTANT: 
You cannot hide a public inherited method by making it private. 
-Since all derived classes are expected to function as the base class when storing them in variables, this is not allowed. 

Example: 
Player has a public method attack()
Wizard extends Player. 

Player a = new Wizard();
a.attack();//Wizard cannot make this private, or it would break this functionality.




public class OrderedSuperArray extends SuperArray{

  /*constructor initializes an empty List*/
  public OrderedSuperArray(){
    //Complete this.
  }

  /*call the proper add.*/
  public void add(int index, String value){
    add(value);
  }

  /*Write this method and any
    appropriate helper methods.*/
  public boolean add(String value){
    //add to the correct spot.
    //you may still use super.add(index,value)
    return true;
  }


}

1-10 of 39