JUNIOR

ACADEMY

8/13/2016

note

  • When typing commands into the terminal, make sure you know exactly what it's doing
    • Check the man if you don't
  • Same goes for installing packages from apt
    • Don't just immediately apt install ...
    • First, apt search ... and read the description of the package
    • Also, before pressing "y" to confirm the installation, read the dependent packages that will be installed with it
      • If anything looks crazy (file size is huge, too many dependencies), look for alternatives! You don't want to clutter your filesystem

paths

  • When writing out paths for anything (such as arguments), you can write them out as absolute or relative paths.
  • Absolute Paths
    • Points to the file/directory regardless of the current working directory
    • Includes the root
    • Ex. python3 /home/john/Documents/JrDLA/blackhat.py
  • Relative Paths
    • Points to the file/directory starting from the current working directory
    • Written without the root /
    • Ex. pwd == /home/john/
      • python3 Documents/JrDLA/whitehat.py
  • Remember: ~ == /home/yourUserName/

bash review

  • Create a directory ~/Documents/BashExercises and two folders within BashExercises in one command
    • Hint: use the -p option for mkdir
      • ​If you don't know what that does, check the manual!!!
  • Pipeline to grep through your installed packages for feh
    • Hint: use the apt list command
    • If you don't have feh, find and install it through apt
  • Download and install the Sublime Text package from its website on Chromium using dpkg. Then remove it (we'll be using a CLI text editor in this class)

alias

  • You can map complex commands to whatever you would like to simplify them
    • Ex. alias ai='sudo apt install'
    • If I typed in "ai firefox-esr", the shell would interpret it as "sudo apt install firefox-esr"
  • This way, you only have to type what you want to do things
  • You don't have to type out options for things you would always want to use, like alias mv='mv -vi'
  • Type "alias" into the terminal to see your current aliases
  • Try making an alias now
    • alias mv='mv -vi'
    • Move a file with just mv to test it out

alias

  • Close the terminal and reopen it
  • Type alias and you'll see that your new alias disappeared!
    • They only work during that shell session :(
  • If you want to keep your aliases permanently, you have to edit ~/.bashrc
    • ​.bashrc is a shell script that is run every time Bash starts
    • You can add your aliases directly into it, but it's better to make a separate file for management
  • Look at .bashrc and you'll see:

if [ -f ~/.bash_aliases ]; then

    . ~/.bash_aliases

fi

alias

  • In ~, make a file .bash_aliases
    • type your aliases in that file
  • Use the type command (with a command as an arg) to see if a command already exists, and if it does, what it is
    • Try it out: type ls chromium-browser hello
  • Aliases I use:
    • alias acs='sudo apt search'
    • alias ai='sudo apt install'
    • alias grep='grep --color=auto'
    • alias cp='cp -vi'
    • alias mv='mv -vi'
    • alias rm='rm -vI'
    • alias mkdir='mkdir -vp'
    • alias df='df -h'
  • Come up with your own!

permissions

  • GNU/Linux is a multiuser OS
  • Files and commands can only be used and accessed/changed by specific users, whether it's the owner or root
    • Only the owner of a file or a group that is allowed can access a file
      • Ex. Only users in the "sudo" group can use sudo and only root/sudoers can access files outside of /home/*
  • id shows the groups the user is in

permissions

  • Look at the file's current permissions with ls -l
    • On the far left of each file's entry, there are 9 chars
    • drwxrwxrwx (or each character has a dash instead)
    • the first character is the file type
      • - == file
      • d == directory
      • l == link
    • The next 3 are the owner permissions
      • r == readable by file's owner
      • w == writable by file's owner
      • x == executable by file's owner

permissions

  • The next 3 (bits 5-7) are the owner's permissions
    • rwx == readable, writable, and executable by members of the file's owner group
  • The last 3 are the world permissions
    • rwx == readable, writable, and executable by everyone
  • Some examples:
    • -rw-r--r-- is a regular file that is readable and writable by the file's owner, and readable by the owner's group and world (everyone)
    • drwxr-x--- is a directory that the owner may enter, and create, rename, and delete files within it. Only the group can enter, but do nothing else

permissions

  • chmod changes file mode bits
    • chmod -OPTIONS MODE FILE
    • The file's owner or superuser can change the permissions/mode of a file/directory
    • It uses either octal or symbolic representation to do so in the mode part of the command syntax
  • Use octal numbers to represent binary digits (bits) which maps to the file mode
    • 3 digits (ex. 777)
    • Each digit of the octal representation equates to each group of the file mode (first digit is owner, second digit is group owner, third digit is world)
  • Use symbols to change the file mode as well
    • Three parts: who the change affects, which operation will be performed, and which permission will be set

octal

Octal Binary File Mode
0 000 ---
1 001 --x
2 010 -w-
3 011 -wx
4 100 r--
5 101 r-x
6 110 rw-
7 111 rwx

Ex. "chmod 600 foo.txt" sets the mode -rw------- to the file

The most common octals are: 7, 6, 5, 4, and 0

symbols

  • Who it'll affect
    • u is short for user, but means the file owner
    • g is group owner
    • o is short for others but means world
    • a is short for all; u, g, & o combined. Default
  • What will be performed
    • + adds the permission
    • - removes the permission
    • = means only that permission is applied, the rest are removed
  • Permissions
    • rwx
  • Ex. u+x == Add execute permission for owner
    • chmod +w file.txt

ownership

  • chown changes the owner and group owner of a file/directory
    • Use the user or :group to apply that ownership to the file
    • chown bob file.txt

file compression

  • Removes redundancy from data to (in the case of lossless algorithms) preserve the data in a file but make it take up less space
  • gzip - compress & exapnd files
  • bzip2 - block sorting compresser (higher compression at the cost of speed)
  • Download the zip and unzip packages from apt to compress/extract zip archives
    • zip is both a compression tool and an archiver

archiving

  • Archiving is gathering multiple files and bundling them into a single large file
    • Usually used in conjunction with compression and for backups
  • tar - Tape Archiving Utility
    • Files with the .tar* or .tgz extensions are tape archives
    • Syntax: tar mode[options] pathname
      • Modes: c - create an archive, x - extract an archive, t - list the contents of an archive; see the man page for more
    • Options don't need a leading dash, they're appended directly to the mode

tar practice

  • cd into your Documents and make a tar of your BashExercises
    • tar cvf BashExercises.tar BashExercises
    • The mode (c) and the options f (to specify the name) and v (verbose) are joined
    • The mode MUST be specified first
  • List the contents of your tar
    • tar tvf BashExercises.tar
  • Extract the tar into a new location
    • mkdir BE2
    • cd BE2
    • tar xvf ../BashExercises.tar
    • ls

putting tar to use

  • A lot of binary packages that can't be found in the apt repo or don't have a deb file online are usually packaged in a tar archive.
  • If you find software you want to "install", but can't, extract the archive and run the executable bin file!
  • Downloading Firefox Nightly (pre-alpha build)
    • On Chromium, go to: https://nightly.mozilla.org
    • Download the tar.bz2 file Linux (Intel, 64-bit)
    • Navigate to your Downloads and mv the file to your Desktop
    • Extract the tar.bz2 file you just downloaded
    • cd into the resulting directory
    • ./firefox

next week

  • For the GNU/Linux portion of next week, we'll be going over Vim and i3wm
  • Vim is an advanced and feature-heavy text editor
    • Vi IMproved
    • Vi is a text editor that is in every installation of any UNIX-like OS
    • Plugins allow the potential to surpass IDEs
  • i3 is a window manager
    • Instead of a DE, you can use a WM
      • 100x better
    • Maximizes/optimizes space
    • More efficient
    • Can be mouse-free
  • Remind your parents to renew your enrollment!

python

  • Conditional statements
  • Loops
  • Functions

review exercises

  • Create a list of your favorite colors, and then create another list of your favorite fruits.
    • Create a third list, called "favorite_things" with three items in it.
      • The first and third elements of this list will be from your favorite colors, referencing the index of those colors
      •  The second item of this list will be one of the fruits, referencing the index of the fruit.
      • Print out the three lists

if-statements

  • if' is followed by a 'condition' and a colon (:), and if the condition is met, the following block of code executes 
    • ex if age > 17:

print('you are too old!')

  • Conditional operators
    • ==, !=, >, <, >=, <=
  • What is the difference between = and ==?

white space

  • White space is the white space between statements
  • The white space before statements inside of something is important!
  • A block of code is a group of statements, and the white space (tab) separate blocks of code
    • Consistent spacing
  • The 3 dots(. . . instead of >>>) in the interpreter means you're typing in a block of code
  • Blocks placed inside each other require the extra spacing as shown to the right

this is block 1
this is block 1
      this is block 2
      this is block 2
      this is block 2
            this is block 3
            this is block 3
      this is block 2
this is block 1
this is block 1

what else is there?

  • If-statements can be extended with an if-then-else-statement
  • So, if the condition isn't met, it would execute a different block of code (if something is true, then do this, otherwise do that); ex:

>>> age = 18

>>> if age == 12:

. . .      print('Hello')

. . .  else:

. . .      print('Goodbye')

else-if-statements

  • If-statements can be further extended using elif (else-if)
  • If the previous if-statement's condition isn't met (so it evaluates to False), then it check the else-if's condition, and so forth.

elif example

>>> pets = 2

>>> if pets == 1:

. . .      print("You have 1 pet")

. . .  elif pets == 2:

. . .      print("You have 2 pets")

. . .  elif age < 13:

. . .      print("You have less than 3 pets")

. . .  else:

. . .      print("You have more than 2 pets")

 

What will be printed?

combining conditions

  • You can have multiple conditions in any conditional statements, by using and and or

>>> if age ==10 or age == 11 or age ==12:

. . .       print("You are %s" % age)

  • If any of the conditions are met, then the code runs, hence the or

>>> if age >= 10 and age <= 12:

. . .       print("You are %s" % age)

  • In this case, all of the conditions have to be true for the code to run, hence the and

none

  • Another value that can be assigned to a variable is None 
  • This is an empty value, with nothing in it (also known as null or NIL in other languages)
  • None can be used to reset variables and make them unused
  • An example is if we don't want to print a message when a variable is empty
    • >>> money = None
    • >>> if money == None:
    • . . .      print("You have no money!")

exercises

  • Imagine an alien was just shot down in a game. Create a variable called alien_color and assign it a value of 'green', 'yellow', or 'red'
    • Write an if statement to test whether the alien's color is green. If it is, print a message that the player just earned 5 points. If it isn't green, print a statement saying the player earned 10 points.

 

  • Write a sequence of conditional statements (or just one) that prints a number if it is equivalent to 20, 21, 22, 25, 26, 27, or 30)

loops

  • Repeatedly executing code written in the loop until/while a condition is met
  • for loop & while loop
  • How can this be useful?

for loops

  • For loops iterate a limited amount of times through a list with a variable taking on the values in the given list
  • for variable in list:
    • The variable iterates through the list and is assigned the value of the current iteration

  • Like if statements, the for loop is defined with a colon and followed by a block of code that is executed
for x in range(5):
    y = x + 1
    print(x+y)
for s in myList:
    print(s)

for loops

  • The variable that iterates through the list only exists in the for loop, and is purely used for the loop
    • It takes on every value in the list before finishing the loop
  • Example of a for loop: Assuming I earn $35 a week, and I have $0 in my savings account, I can calculate my money earned throughout the weeks for a year!
    • >>> savings = 0
    • >>> for week in range(1, 53):
    • ...     savings = savings + 35
    • ...     print("Week %s = $%s" % (week, savings))

nested loops

  • Try typing this in your interpreter:
    • >>> myList = ['a', 'b', 'c']
    • >>> for u in myList:
    • ...     print(u)
    • ...     for v in myList:
    • ...         print(v)

loop exercise

If you have $100 saved in your bank account, and you obtain 3% interest every year, how much money will you have for each year, up to 10 years?

while we're on loops

  • While loops iterate though the block of code while a condition is met
    • Different from for loops, because it's while condition == true, not iterating through a list
while condition:
    # block of code

while loop example

x = 1
while x < 200:
    x = 2*x
    print(x)

What will this print?

break

  • You can break out of a loop before the condition is met
    • >>> while True:
    • . . .        # tons of code
    • . . .        if someCondition == True:
    • . . .                break
  • Games use while True to keep the game running and refreshing the screen!

another loop exercise

Answer the previous question using a while loop

 

If you don't remember the task:

If you have $100 saved in your bank account, and you obtain 3% interest every year, how much money will you have for each year, up to 10 years?

input()

  • You can take in user-inputted text in the code, and store it in a variable
  • input("text")
    • The user types something in and presses Enter
    • Whatever they typed in is returned by input() as a string
  • >>> name = input("Please enter your name: ")
  • >>> print("Hello, %s!" % name)
  • If they input a number, it is still returned as a string
    • use the int() function to change it to an int
    • >>> age = input("What is your age? ")
    • >>> age = int(age)

functions

  • Functions allow you to write code just once, then reuse that code in your programs multiple times
  • Functions take in parameters, which is a variable you give it that is only available in the body of the function (the block of code inside of it)
def function(parameter):
    # block of code

example of a function

You define (make) the function like this:

def printName(name):
    print("Hello, %s!" % name)

And call (use) it like this:

printName("John")

Which will print:

Hello, John!

example of a function

Another example, except with return instead of print():

def savings(chores, job, spending):
    return chores + job - spending
    # or return(chores+job-spending)

And call it like this:

print(savings(10, 10, 5))
# OR
money = savings(10, 10, 5)

scope

  • Not all variables are accessible from all parts of our program.
  • Where a variable is accessible depends on how it is defined.
  • We call the part of a program where a variable is accessible its scope.
  • ​A variable which is defined in the main body of a file is called a global variable.
    • It will be visible throughout the file, and also inside any file which imports that file.
  • A variable which is defined inside a function is local to that function.
    • It is accessible from the point at which it is defined until the end of the function
# This is a global variable
a = 0

if a == 0:
    # This is still a global variable
    b = 1

def my_function(c):
    # this is a local variable
    d = 3
    print(c)
    print(d)

# Now we call the function, passing the value 7
# as the first and only parameter
my_function(7)

# a and b still exist
print(a)
print(b)

# c and d don't exist anymore -- these statements
# will give us name errors!
print(c)
print(d)

function exercise

  • Write a function called practice_function() that takes in a number as a parameter. If the number is less than 50, print the value. If the number is greater than 50 but less than 1000, print a message. If the number is any other value, return the number, then print it. Call the function for three different values: 5, 50, and 200.

 

  • Write a function called describeCity() that accepts the name of a city and its country as parameters. The function should return a simple sentence (for example: "Honolulu is in the USA"). Call your function for three different cities, store them in a list, and print the items in the list separately.
Made with Slides.com