How to MATLAB

By Jenny Wang on May 27, 2019
~3 min. read

Numerical Data Structures

==========================

cell

vector = row/column

matrix = group of vectors

  • is a rectangle

array = 3d matrix

Initialize matrix matrix = [1 1;2 2]

  • ; = new row
  • <space> = next column

Specify # of cells

  • matrix = zeros(numRows, numColumns)
  • matrix = ones(numRows, numColumns)
    • or ones([numRows numColumns])

Call data from all numRows rows or numColumns columns

  • replace with :
  • ex: matrix(:,4)

vector = [1:100]

  • fills vector with numbers 1 to 100

vector(row, col) = 10

  • change cell value

vector(row, col)

  • get number and print it out

sum(vector)

  • sums all numbers in vector

prod(vector)

  • multiply everything in vector

Math between two vectors/matrices

  • use +, -, *, /

Math between correlating cells in vectors/matrices

  • use +, -, .*, ./

vector = vector';

  • make the row vector into a column vector

matrix(:)

  • take all cells in the matrix

=================================================

Other Data Structures

=======================

Strings are in single quotes ‘’

num2string(var);

  • change data type

string2num(var);

  • change data type

=====================================

Miscellaneous Syntax

=======================

NaN = null

% = comment

... at the end of the line when you want to press enter

  • ex:
      var1 *...
      var2
    
  • put semicolons in scripts
    • won’t print onto command window

lowerLimit:upperLimit

  • vector with all numbers from lowerLimit to upperLimit

~ = not

|| = or

&& = and

for loops for i = start:end %do something end

if statemtents if %condition %action else %action end

===============================

Random Functions

==================

vector = xlsread('fileName.extension')

  • Read Exel file

image = imread('imagename');

  • read image

linspace(start, end, n_points);

  • returns equally spaced points
  • includes starting and end points

[x,y] = meshgrid(xVector, yVector)

  • returns all possible coordinates of pts
  • use with linspace

size(vector, <row or column as in 1 or 2>)

  • returns numRows, numColumns
  • don’t specify row or column if want both

imageB = imresize(imageA, scale);

imageB = imresize(imageA, [numRows, numCols]);

  • imageB has numRows rows and numCols cols
  • or put NaN as one of them to preserve aspect ratio

imshow(image);

  • make a window with the image on it

sind(theta)

  • sin

cosd(theta)

  • cos

repmat(vector, numTimes)

  • repeat the vector numTimes horizontally and vertically

repmat(vector, numRows, numColumns)

  • have that many total rows/cols

shuffle(vector)

  • change up the order of all cells, use with repmat

shuffle(vector, dimension)

  • dimension: 1 = Rows change, 2 = Columns change, 3 = next dimension changes, etc

vertcat(vector, vector2, vector3, ...)

  • stacks vectors ontop of each other

horzcat(vector, vector2, vector3, ...)

  • stacks vectors side to side

RandStream.setGlobalStream(RandStream('mt19937ar', 'seed', sum(100*clock)));

  • put it everywhere just in case you want a random number (for real randomness)

randperm(upperLimit, numCells);

  • can’t get the same number twice

randperm(upperLimit)

  • numbers 1~upperLimit are reordered

randi(upperLimit);

  • get one random number

randi(upperLimit, numRows, numCols);

  • random numbers in matrix numRows x numCols

randi([lowerLimit, upperLimit]);

  • number from lowerLimit to upperLimit

randsample(upperLimit, numCells);

  • numCells number of random numbers

randsample([1 2 3], 2)

  • numCells number of rand numbers from the vector

any(vector)

  • returns true if any of cells is nonzero

floor(num)

  • returns num rounded down to whole number

ismember(element, vector)

  • returns true if element is found inside the vector

WaitSecs(seconds);

  • how long to wait

GetSecs()

  • get seconds from start of program
  • use to make sure the time intervals are right

[keyIsDown, secs, keyCode] = KbCheck()

  • if have different keyboards, put 1/2/3/4/5 in parenthesis for specific keyboard
  • keyIsDown = any button down (1 or 0 => true or false)
  • secs = time from GetSecs()
  • keyCode = key that is down
    • ex: strcmp(‘s’, KeyName(keyCode)), see if it is ‘s’

[x,y,clicks] = GetMouse()

  • x, y = mouse position coordinates
  • if clicks = [0,0,0] => no click, [1, 0, 0] = left click
  • test with any(clicks)

GetClicks()

  • get number of mouse clicks

strcmp(string1, string2)

  • returns true if identical, false if not

string = strcat(string1, string2)

  • combine string1 and string2

KeyName('UnifyKeyNames')

  • make codes from key presses the same from macs/windows/etc

save(fileName, 'variable')

  • ex: save('result', 'p', 'q');
  • save some variables in a file (.mat)

string = upper(string)

  • all letters uppercase

isdir(directoryString)

  • true if there already is a directory with that name, false if no
  • example of directoryString is from pwd()

mkdir(directoryString)

  • create a folder with directory directoryString

sortrows(matrix, colNum)

  • make numbers in the colNum-th column be in ascending order

resizem(input, scale)

resizem(input, [numRows, numCols])

  • expand and contract matrix

====================================================

Command Line Commands

=======================

COMMANDS CAN BE PUT INTO SCRIPTS

pwd

  • print your directory
  • usage examples:
      rootDir = pwd();
      resultsDir = [rootDir '/results/']
      if ~isdir(resultsDir) %if don't have this directory already
          mkdir(resultsDir) %make the directory/folder
      end
    

cd(folderName)

  • change directory
  • go one level up => cd ..

ls

  • list of files in the folder

clear all

  • clears variables from other experiments

clc

  • clear command window

===========================================

Keyboard Shortcuts

====================

ctrl+c then s then c then a then enter

  • bring back window (if it crashes)
  • might need to alt+tab (switch windows) before doing above

=================================================================

Psychtoolbox

===============

A library for psychology experiments

Screen has many settings

  • access w/ Screen('something', <specific>, <more specific>, <etc>);
  • Screen('CloseAll');
    • closes all screens
  • Screen('Preference', 'SkipSyncTests', 1);
    • yes to skipping sync tests

[window, rect] = Screen('OpenWindow', 0, [], [500 500 700 700]);

  • open the window
    • 0 = open on this monitor
    • 1 = open on other monitor
  • 2nd matrix = where the screen will be
  • window = pointer
  • rect = (startX, startY, endX, endY)
    • corner coordinates;
  • Screen puts data into window/rect

x = Screen('MakeTexture', window, uint8(image));

  • uint8 because colors in image can’t be > 255

Screen('DrawTextures', window, x);

  • draw the texture. x is from function above

Screen('DrawTextures', window, tid(rand_oranges(i,:)), [], xy_rect, orientation);

  • xy_rect = corners of each picture
  • orientation = degrees of rotation=========================================================================

A = Screen('Flip', window);

  • display onto monitor
  • usually don’t need A

Screen('Flip', window, A + seconds);

  • show a blank screen (if nothing is made with window) second seconds later
  • more accurate than WaitSecs()

KbWait();

  • wait for keyboard input before going on

  • how to get rid of background of image

    • add transparent mask ontop
    • mask must be same size as image
Tags: coding_notes

How to Java (APCS level)

By Jenny Wang on May 27, 2019
~3 min. read

Accessible methods in the Java Quick Reference

===============================================

Object

  • boolean equals(Object other)
  • String toString()

Integer

  • Integer(int value)
  • int intValue()
    • returns value in int
  • Integer.MIN_VALUE
    • smallest value that can be stored in an int
  • Integer.MAX_VALUE
    • largest value that can be stored in an int

Double

  • Double(double value)
  • double doubleValue()

String

  • int length()
  • String substring(int from, int to)
  • String substring(int from)
  • int indexOf(String str)
  • int compareTo(String other)
    • returns
      • 0 if equivalent
      • some number > 0 if earlier in alphabet
      • some number < 0 if later in alphabet

Math

  • abs(int/double x)
  • pow(double base, double exponent)
  • sqrt(double x)
  • double random()
    • double in the range [0,1)

List<E>

  • int size()
  • boolean add(E obj)
    • returns true after adding it ._.
  • void add(int index, E obj)
  • E get(int index)
    • if it’s a number, returns Integer/smth else
      • (not int/double, but Integer/Double)
  • E set(int index, E obj)
  • E remove(int index)
    • changes indices of next elements. BEWARE IN LOOPS

TERMS

========

  • API = Application Programming Interface
    • methods, routines, etc used to program
  • nested/inner class
      class foo {
          class bar {...}
      }
    
    • ^^ bar is nested class
    • bar sees everything from foo, but isn’t a foo
    • ex: String is a nested class of Object
  • child class
    • class bar extends foo {...}
    • ^^bar is child class
    • bar sees everything from foo, and is a foo

KEYWORDS

===========

implements

  • for interfaces (methods not defined)
  • provide definitions for APIs

extends

  • for Classes (methods defined)
  • parent-child relationship

static

  • modifies/takes stuff from the class
  • nonstatic (aka not putting static there) modifies the instance

Integer/Double

  • can == null => can’t assign null to an int
    • otherwise, it’s the same as int/double in Java 5+

List

  • from index 0
  • see methods
  • to initialize
    • List<Integer/etc> a = Arrays.asList(ele1, ele2, ...);
  • is immutable (cannot be modified)
  • is an interface

ArrayList

  • extends AbstractList that extends List
  • from index 0
  • to initialize
    • ArrayList<Integer/etc> a = new ArrayList(Arrays.asList(ele1, ...);
  • is a Class

CONTROL STATEMENTS

=====================

  • enhanced for loop (“for-each”)
      String[] array = {...};
      for (String element : array) {
          //do something for all elements in array
      }
      the same as:
          for (int i=0; i<array.length(); i++) {
              ;
          }
    

SORTS

========

  • insertion sort
  • selection sort
  • bubble sort
  • mergesort
  • heapsort
  • quick sort

==================================================

Java unrelated to APCS

  • concurrency
    • processes happen at the same time
    • use threads
  • immutable
    • that instance cannot be changed after it is made
    • uses the keyword final
  • \unnnn (escape sequence like \n)
    • line break LOL
  • assert <boolean expression>
    • check for bugs in the code
    • if expression after it is false, it stops the program
    • ex: assert varIsTrue == false
Tags: coding_notes

How to C

By Jenny Wang on May 27, 2019
~10 min. read

============================

#include <stdio.h>

  • standard input and output

#include <string.h>

  • strings

#include <stdlib.h>

  • exit() to exit out of code
  • rand() to create random numbers

#include <stdbool.h>

  • booleans
  • can use bool instead of _Bool

#include <ctype.h>

  • getchar() recieves a string/char, can be put in variable
  • putchar(string) display the char
  • isalnum(char) and others (see below)
  • has an alphanumber been passed in? (a for 10, b for 11, etc)

#include <errno.h>

  • error handling

#include <math.h>

  • calculate power of something

Define:

==========

#define MYNAME "Derek Banas"

  • all uppercase, a constant

#undef MYNAME

  • can redefine afterwards

Concepts and Strategies:

==========================

  • main looks like int main(){} and returns a 0 at the end

  • & is to get the pointer, * is for the value
    • inverses
  • Print things on the screen from an array:
    char *randomString = "Just some random stuff";
    while (*randomString){ //null=>0=>ends while    
      putchar(*randomString++); //increment to chars
    }
    //OR
    int i = 0;
    while(randomString[i] != '\0'){
      putchar(randomString[i++]);
    }
    
  • if you initialize a, but don’t give it a value before incrementing it, computer will take whatever was inside the place a is, increment it, and spit it out. “Random garbage”

  • arrays use row-major ordering, so it is array[y][x]

Data Types:

=============

char firstLetter = 'L';
int age = 38; //up to 32000
long int superBigNum = -3229384234; //bigger
float piValue = 3.14; //decimals (38 decimal #s)
double reallyBigPi = 3.1423842323i4uy23i4;

To describe variables:

=========================

unsigned = no negative digits

const = constant, unchanging

size_t = stores the amount of data in bytes

extern = variable was defined elsewhere, but use that var here, too

static = basically a “global” variable with a scope limited to where it was defined - functions: “you can’t call me out of my scope! >:D”

Relational:

=============

TRUE is anything other than 0

  • can an int be used in if(int) ?

FALSE is also 0

>, <, >=, <=, ==, !=, &&, ||

  • result comes out as 1 (true) and 0 (false)

  • !0 equals 1

  • !1 equals 0

  • To choose between two options:

      char* legalAge = (custAge > 21) ? "true" : "false";
    
    • if true, return true. If false, return false
    • can be put inside the %s part of printf()

Casting a value:

==================

  • to temporarily change the type

      //when the two numbers are ints:
      printf("numberEx / numberEx2 : %f", (float)numberEx/numberEx2);
    

Strings:

===========

  • If made by char ex[] = {‘C’, ‘a’, ‘\0’}, include ‘\0’ “naw” to end the string
  • or do char myName[] = “Something” (automagically puts \0)
  • see Functions

Pointers:

============

  • To pass data to other functions so they can use that local variable as well

  • can be in %p and %d (hexidecimal or not)

  • * to get what’s in the pointer
  • & to make it into a pointer

  • print the first index in an array:
    printf("First: %d", *array);
    
  • print any other index because they are next to each other:
    printf("Thrid: %d", *(array + 2));
    

Structs:

===========

  • more than one data type to describe something
  • need * for strings because of pointers

  • Example:
      struct dogs{
    
          const char *name;
          int height; 
    
      };
    
  • use typedef struct to make it so you don’t have to put struct everywhere else
    • “Make a new variable type”

    • Example:

            typedef struct dog{
      
                const char *name;
                int height; 
      
            } dog; //you can call it with dog
                    //can put multiple names
      
  • To put info in:

      struct dog spike = {"Spike", 90};
    
  • To get the info in the struct:
      theName = theDog.name; //use the . OR
      theName = theDog->name; //OR
      theDog->name = theName;
    
  • To get addresses, use theDog.name for strings and
      &theDog.avgHeight for ints
    
  • When struct is passed to function, new struct is created, so need pointers
  • When doing * with structs, use ():
      (*theDog).weight = newWeight;
    
    • OR you can do
        *theDog->weight = newWeight;
      

struct dog cujo2 = cujo;

  • Can copy everything in a struct, including pointers

Union:

========

  • store 1 pieces of data that can be any type, but is not more than one type at a single time

  • Making one:
      typedef union{
            
          short individual;
          float pound;
          float ounce;
    
      } amount; //this union is named amount
    
      //set amount as 16, other values follow
      amount orangeAmt = {.ounce = 16};
    
      //changes the value of the whole union
      orangeAmt.individual = 4;
    
  • BE SURE TO USE THE CORRECT DATA TYPE

  • Can put them in structs
  • To initialize:
    • Ex: orangeProduct is a type of struct named orangeProduct, theAmount is an union, so
        orangeProduct productOrdered = {"Chiquita",
            .theAmount.ounce = 16};
      

Linked List:

==============

  • Essentially make an infinitely long list with structs

  • Format of each struct:

      typedef struct product{
    
          const char *name;
          float price;
    
          struct product *next; //pointer to next struct
    
      } product;
    
  • if pProduct is the pointer of the given product, the next one in the line is pProduct->next

  • Add a new struct to the end:
      tomato.next = &potato;
    
  • add a new product, apple, between potato and lemon:

      potato.next = &apple, apple.next = &lemon, lemon.next = NULL
    
  • To go through all structs:
    • go through all the items through next until you get NULL
  • To search for a struct:
    • recieve a *productName
    • set a varialbe to the first variable in the struct => name
    • use strcmp() to compare
  • Deleting an item:
    • Ex: Tomato, Potato, Lemon
    • see what’s before potato from the time you were scanning for potato
      • potato’s next is now tomato’s next
    • free() potato

Macros:

==========

  • A fragment of code that is given a name
  • name is read => whole code is pasted in
  • conventional = names are all UPPERCASE
  • Ex: #define MACRO_THINGIE 10 -> 10 is put in MACRO_THINGIE, replaces it

  • can make multiple lines
      #define MACRO_NUMBERS 10 \
                              2 \
                              3
      int x[] = {MACRO_NUMBERS};
    
    • makes: int x[] = {10,2,3};
    • weird error line numbers later on tho

Enumerated type

==================== For the times that you don’t need anything else other than what you put inside

Initialize:

==============

typedef enum{ INDIV, OUNCE, POUND } quantity;

To set the value: quantity quantityType = INDIV;

To do somethign:

if (quantityType == INDIV){
    blah blah
}

Line buffering:

=================

storing/scanning an amount of information before something is done to it

File I/O:

===========

  • Print out data from the file:
      char buffer[1000];
      while(fgets(buffer, 1000, pFile) != NULL){
          printf("%s", buffer);
      }
      //OR
      while(fscanf(pFile, "%s", buffer) == 1) 
    
    • returns # other than 1 if it doesn’t pass a string
  • Print directly to the file:
      fputs("Messing with strings", pFile);
    
    • pFile is the way you are entering stuff
  • TO PRINT WHOLE THING, YOUR “CURSOR” HAS TO BE AT BEGINNING

  • To get number of bytes in whole file:
      fseek(pFile, 0, SEEK_END);
      ftell(pFile)
    
    • because the “cursor” is at the end of the file
  • see Functions

Convert any base to any base:

===============================

For startingBase, endingBase, numberToConvert

  • numberToConvert % endingBase => put in array
  • Then numberToConvert = (numberToConvert - <remainder>) / endingBase
    • and so on until you get an error with 1

Convert any base to base 10:

  • ex: binary 110 to base 10
    • (1 * 2^2) + (1 * 2^1) + (0 * 2^0)

chars have values, too!

if(isalpha(number[i])){
    int charCode = ((int)tolower(number[i])) - 87;
    result += charCode * pow(baseFrom, toThePowerOf);
}

Bitwise operators:

====================

& And bitwise operator:

  • 110 & 111 => 1 for every time they’re both 1
    • 110 is result

| Or bitwise operator:

  • 6 | 7 => if either is a 1, return a 1 => 111

^ exclusive or:

  • 6 ^ 7
    • 1 returned if one is a 1, other is 0
    • 001 => 1 is returned

~ bitwise not:

  • ~x
    • if a bit in x == 0, that bit is now = 1
    • if a bit in x == 1, that bit is now = 0
  • negative is the 2’s complement 000000010 => 2 111111101 => complement of 2 111111110 => add 1 to it

  • inverse sign = ~
    • Ex: ~numberSix = -6
  • shift operators:
    • shiftLeftTwo = numberSix << 2;
    • x/pow(2, n) is the same as x>>n
  • bit masking
    • if you want to see what is in some specific spots
    • do 1 for parts you want to see, 0 for others
    • do an AND bitwise operator

Functions:

============

printf("string, int %d, long int %ld, decimal with 2 decimal

  • places shown %.2f”, intValue, longIntValue, floatValue);
  • Displays to terminal
  • Conversion characters:
    • %ld //long
    • %d //int
    • %.5f //prints to 5 decimal places
    • %.15f //used for float and double
    • %c //char
    • %s //string
    • %p //return hexidecimal addresses //also use & => printf(“%p”, &rand1)
  • \n = line, \t = tab, \\ = print, \" = print “

scanf("<data type in format>", &whereToStore, &otherPlace);

  • Ex: scanf(" %d/%d/%d", &month, &day, &year);
  • Store input from user, bulky
  • will overwrite values if there is a data overflow
  • needs the &
  • don’t use %d++ in the “” because it screws up
  • will return a 1 or 0 if compared with == to a number

fgets(storeHere, 30, stdin);

  • like scanf()
  • store the 30 bytes of information in storeHere through stdin
  • adds the \0 character
  • adds new line
  • accepts more than one string

fputs("string here", stdout);

  • string, output method
  • no new line

gets(name);

  • accepts one string and puts it in name
  • no new line. It ends with \0

puts("string here");

  • makes a new line after displaying the string

strcpy(myName, "Bob Joe"); //used to hold "Derek Banas"

  • assign a different value to the variable

strcomp()

  • returns negative # if first string is less than 2nd
  • returns positive # if more (second would come first if alphabetic)
  • returns 0 if equal

strcat(yourCity, yourState);

  • combine the two strings into yourCity

strlcpy(yourCity, "aksjdfl", sizeof(yourCity));

  • cuts off the end of the string so variable doesn’t overflow

strlen(name);

  • returns the length of the variable (number of slots)

theChar = getchar();

  • Takes in chars until enter is pressed

putchar(theChar);

  • print the char on the screen

strrchr(randomString, '\n');

  • returns last occurance of \n in randomString

strchr(randomString, 'a');

  • returns first occurance of a in randomString

tolower(char)

  • makes the letter lower cased
  • Ex: theString[i] = tolower(theString[i]);

toupper(char)

  • makes the letter upper cased

isalnum(char)

  • is it consisting of all numbers?

isalpha(char)

  • alphabetic character

isblank(char)

  • space

isdigit(char)

  • digit

isgraph(char)

  • anything but space

isupper(char)

  • upper cased

islower(char)

  • lower cased

ispunct(char)

  • punctuation

isspace(char)

  • any space

strcmp(string, string)

  • comparing two string sto see if they match
  • returns 0 if they’re the same
  • returns (+) if first string more (further in alpha order)
  • returns (-) if first string is less

exit()

  • Close program. Don’t run anything else.
  • can be (0),(1),(2),(3),(4), etc for personal reference

rand()

  • Create random number
  • To get numbers 1-50: rand() % 50 + 1

break;

  • exit out of an infinite loop (is like exit())
  • used in switch

continue;

  • go back to the beginning of the braces
  • Ex:
      for(blah){ 
          //do something, start here again!
          if (variable == 1){ continue; }
          //don't do this stuff this time
      } 
    
switch(whatToDo){
        
    case(1) : printf("Print the time");
        break;

    default : printf("Bye");
        exit(0);
        break;

    }
  • if whatToDo == 1 (in case(1)), do that
  • go on to other cases
  • default is done if nothing else works
  • if there isn’t a break, it will execute all the other statements after the one it entered in on range is 4…6 instead of 4 or something

sizeof(variableName);

  • returns the number of bytes in there

pRandomNumbers = malloc(amountOfBytesToStore);

  • if fails, stores a NULL
  • Good usage to store a specific number of ints:
    • malloc(amtOfNumbersToStore * sizeof(int))

free(pRandomNumbers);

  • free memory for pRandomNumbers to prevent crashing
  • used for large scale programs that don’t end in a while

pFile* = fopen("fileName.txt", "w");

  • will make the file if it doesn’t exist
  • binary files (.bin) use things like rb+
    • “w” - stuff already inside will be deleted/replaced
    • “a” - append or add new info
    • “r” - read from the file
    • “a+” - start at end of file if it exists and reads and writes
    • “r+” - open at beginning for reading and writing, no delete, no make new file
    • “w+” - delete original (or make new one if no exist), read and write
  • if file wasn’t opened, returns a 1

fprintf(pFile, "%d", randomNumber)

  • print it to the file like printf()
  • file to print to, what to print

fclose(pFile)

  • close the file, if not closed, returns 0
  • if went well, returns 1
      if(fclose(pFile)) != 0){
          printf("Success writing to text");
      }
    

fseek(pFile, 12, SEEK_SET);

  • can use (-) numbers in fseek()
  • 12- move 12 characters => “moving the cursor”
  • Seek things:
    • SEEK_SET - Start from beginning of file
    • SEEK_CUR - Move from current position in file
    • SEEK_END - Based off of end of file
  • in binary mode, need to * number chars to move by the size of each thingie => move 12 => 12 * sizeof(int)

ftell(pFilfe)

  • returns the number of bytes the cursor is from the beginning of the file

perror("Error Occured");

  • prints that and the standard error message

printf("Error Code %d\n", errno);

  • prints error code

fwrite(name, sizeof(name[0]), sizeof(name)/sizeof(name[0]), pFile);

  • Write binary data to file
  • pointer by default
  • variable, size of each element, number of elements, where to print

fread(buffer, 1, fileSize, pFile);

  • dataInFile = fread(blah blah);
  • information goes to buffer, bytes taken from each element,
    • number of elements, read from this place

rewind(pFile);

  • go to beginning of file

pow(base, toThePowerOf);

  • mutiply base and itself toThePowerOf times
Tags: coding_notes

How to Javascript

By Jenny Wang on May 24, 2019
~10 min. read

HTML STUFF

============

<!DOCTYPE html>

<html>

<body onload=function()>

  • onload- does function()

<script>

<h1>

<p id="demo">

  • id- set the id so its elements can be found w/ getElementById() if there is no matching id, creates one at the bottom of the page events: onchange, onclick, onmouseover, onmouseout, onkeydown, onload

<br />

  • inserts a line break there

<noscript>Text to display</noscript>

  • Display that text if javascript is not enabled

<!-- and //-->

  • outline the script with this comment so unsupported computers skip it

<div style="" align="" globalAtribbutes>

  • style- “color:#0000FF” => all text within <div> = that color
  • align- left/right/center/justify(stretch) the elements
    • not supported in HTML5
  • draggable- can click and drag like a picture

<form action="code.php" method="post/get">

  • for organization
  • action- what to do after submit button is clicked
    • if ommitted, looks within the page
  • method- how to submit data, GET = default (data displayed in
  • address field, POST = data hidden

<fieldset>

  • for organization within <form>

<legend>text</legend>

  • “header” for fieldset

<input type="" name="name" value="text" onclick="function()">

  • type- none/text=text box, button=button, radio=multiple choice submit=submit button (see <form>)
  • name- must be included to be submitted within <form>
    • id- can’t be used for <form>
  • value- text to initially display (hint). ‘’ is empty
  • onclick (buttons)- when element is clicked do blah

<audio src="dir or website">

  • holds an audio file
  • audio accessed by through audioElement.play()
  • src- a directory or website that holds the audio file

.innerHTML / .value

  • .value is for buttons, etc
  • .innerHTML is for paragraphs, etc

<strike>text</strike>

  • text has strikethrough

GLOBAL ATTRIBUTES

================== http://www.w3schools.com/TAGS/ref_standardattributes.asp

draggable=true/false

  • click and drag the element like a picture spellcheck=true/false
  • have spellcheck within element or not

EVENT ATTRIBUTES

================= http://www.w3schools.com/TAGS/ref_eventattributes.asp

onclick="function()"

  • do this when the element is clicked
  • for string parameters, use quotes DIFFERENT from the one
    • surrounding the function
    • ex: "function('hi')"

ondblclick="function()" - do this when the element is double clicked

onload="function()" - do this when the element loads

onkeydown="function()" - do this when key is down

====================================================================

====================================================================

====================================================================

JAVASCRIPT STUFF

==================

RANDOM SYNTAX AND STUFF

=======================

<script type="text/JavaScript">script</script>

  • make a js script

<script type="text/JavaScript" src="code.js">

  • reference an external js script

==

  • equals
  • ex: "7" == 7 => true

===

  • strict equals, takes var type into account, too
  • ex: "7" === 7 => false

this

  • the element
  • ex:

      `<button onclick="this.value=Date()> `
    
    • changes button’s own text

typeof <variable>

  • returns type of variable
  • ex: typeof variable == 'undefined'

if a variable doesn’t exist, it basically == false

  • ex: function test(callbackFunction) if (callbackFunction) { callbackFunction(); } }

  • and if I put test() with no callbackFunction, it just doesn’t do anything
  • AKA: can call functions with less arguments than specified

closure: variables created outside an event listener are “kept alive” if the reference in the listener is still there

  • creates memory leaks
  • use $('element').off('event') => ex: $('button').off('click'); “use strict” ontop of the script
  • cannot “pollute the root scope”
    • can’t make a new var to fit the uninitialized a = 2 in the window object
foo: function(){
    //do something
}
  • another way to declare the function foo()

try{ throw "error" } catch(e){ switch(e){ case "error" break;}

  • create + manage errors! let
  • block-scoped
  • using x before let statement causes error
  • only defined in its block var
  • function-scoped
  • using x before var statement sets x to undefined that ${var1 + var2} is cool
  • template literals. Replaces “that “ + (var1 + var2) + “ is cool”
  • can do multiline:

      `hi
      there`
    
    • (this has a \n in the middle)

FUNCTIONS/ATTRIBUTES

====================== window.alert(<text or num>); [or just alert()] popup alert

document

  • .write(<text or num or object>);
    • cannot write numbers when it is not in a function
    • only for testing purposes
    • if it is object, can type as "<p>paragraph</p>"
    • string" + num = "stringnum"
    • num + num = sum
  • .getElementById(id);
    • access an HTML element
    • .innerHTML = "text";
      • change the element’s text
  • .body
    • do something to the <body>
    • .appendChild(‘elementVariable’)
      • add the element (ex: button) to the document
  • .createElement("element")
    • ex: “button”, “br” (line break)
    • create the element.
    • can save it w/ var btn = document.createElement("button");
  • .createTextNode("text")
    • create the text node (variable)
    • can save it w/ var t = document.createTextNode("text");

Any element variable (ex: btn)

  • btn.appendChild(textNode)
  • .previousSibling
    • returns element right before it in the parent
  • .replaceChild(newChildElement, oldChildElement)
    • replace the old with the new
    • later do newChild.appendChild(oldChild) to restructure

console.log(text/num, text/num, etc);

  • log text into the console (inspect element)
  • multiple parameters => a space in the

str

  • .indexOf("string"[, fromIndex]);
    • returns first index of “string” within str
      • returns-1 if not found
    • begin looking from the index fromIndex
  • .lastIndexOf("string");
    • returns last index of “string within str
      • returns -1 if there’s nothing
  • .search("string") or .search([regexp object])
    • can use regexp (but slower)
  • .match([regexp object])
    • better search method
    • ex: match(/m/gi) (see regexp)
  • .substr(start, length);
    • start at start and end length chars later
    • start is negative => start from the end of the string
  • .substring(start, end);
    • start at start and end at end
  • .slice(start[, end]);
    • almost same as substring()
    • if start/end are negative, count from the end of the string
      • doesn’t work in Internet Exploerer 8 or earlier
    • only one parameter => slice out the rest of the string
  • .split("searchTerm"[, numElementsToReturn]);
    • return array of str split at the search terms
    • can stop looking for new terms after numElementsToReturn
  • .charAt(index)
    • returns char at the index
  • .replace("findThis", "replaceWithThis");
    • replace all “findThis”’s with the replacement
  • .toLowerCase()
    • returns string in all lowercase
  • .toUpperCase()
    • returns string in all uppercase
  • .strike()
    • returns [str.value]
  • .length
    • returns length of string

element.fireevent(eventStartingWithOn, event)

  • can be used without the () and stuff in it
  • returns if the event was cancelled (ex: can’t click there)
  • eventStartingWithOn/event are more specifications

Math.random()

  • returns rand number from 0 to 1
  • Math.floor(Math.random()*50) for rand int between 0 and 50

Array

  • .splice(index, number) remove element(s) from the array
  • .push(element) add element to end of array
  • .includes(element)
    • returns if the element is in the array
  • .pop() removes and returns last element
  • .shift()
    • removes and returns first element. all elements are shifted left
  • can initialize with var a = [1, 2, 3]
  • adding elements outside the array puts undefined in the middle

      var a = [1, 2, 3]
      a[5] = 0
      // a = [1, 2, 3, undefined, undefined, 0]
    
  • an instanceof Array

EVENTS FOR STUFF

==================

document

  • .ready()
    • does what’s inside () when doc is ready onerror = <function>
  • calls <function> when the document errors.

VARIABLE MAGIC

================

var varName = <something>;

window.varName

  • all global variables in HTML are part of the window object

var car = {brand:"Fiat", price:"3000000000000"};

  • get values with car.price or car[“price”]
  • can have methods as elements
    • use with car.function()

this.innerHTML = <blah>

  • change own element (ex: if in

strings

  • txt.length
    • returns length of string

string objects

  • For var x = new String("Some Text");
    • x == y (another new String()) => false
    • x == x => true
    • != "Some Text"

if variable not given in parameter of function, it = undefined - ex: func(x,y) => use func(1) => y = undefined

2D Array - is arrays in an array - ex: var array = new Array(columns); for (i = 0; i < columnds; i++) { array[i] = new Array(rows); } - access with array[1][2]

PROTOTYPES

=============

  • basically parent classes in java
  • different from classes b/c they are hoisted
    • can be used in lines above it b/c it’s basically in the head
  • create prototype:

      function Person(n, a){
          this.name = n;
          this.age = a;
          this.talk = function() {console.log("Hi")};
      }
    
  • add properties within prototype once made:
    • Person.prototype.newProtoName = "value";
  • create new object from prototype:
    • var joe = new Person("Joe", 70);
  • add property to existing object
    • myObject.newProperty = "value";
    • (creates it automagically for myObject and not prototype)
  • add method to existing object

      myObject.property = function () {
          return "I dunno";
      };
    

object.prototype.isPrototypeOf(obj)

  • returns whether object.prototype is in prototype chain of obj

CLASSES

=========

  • not hoisted

      class B extends A {
          publicField = 0;
          #privateField = 1;
          uninitialized;
    
          constructor(x, y) {
              this.x = x;
              this.y = y;
          }
    
          foo() {
              <function body>
          }
      }
    
  • constructor is named “constructor”
  • don’t put def/var/function keywords in front of methods

REGULAR EXPRESSIONS (regexp)

===============================

  • object representing formatting
  • syntax: /pattern/modifiers
    • pattern- word/char/[multiple things] to look for
    • modifiers- i (case-insensitive),
      • g (global, find multiple matches)
      • m (multi-line matching)
  • ex: str.match(/m/gi)
  • ex: var rEPattern1 = /z/i; reg
    • .exec()
      • returns first match if found
      • returns false if none found
      • if just called for the same string, starts searching after the previous match .test()
      • returns true if found, false if not found
      • if just called for the same string, starts searching after the previous match

BUILT IN VARIABLES

===================== Date()

document.location

  • is website url

HELPER FUNCTIONS

===================

Append text to document body

    document.body.appendChild(document.createTextNode("hi"));

Simulate a click without clicking there

    function eventFire(el, etype){
      if (el.fireEvent) {
        el.fireEvent('on' + etype);
      } else {
        var evObj = document.createEvent('Events');
        evObj.initEvent(etype, true, false);
        el.dispatchEvent(evObj);
      }
    }
  • usage: eventFire(document.getElementById('mytest1'), 'click');

Get mouse coordinates when it changes

(function() {
    document.onmousemove = handleMouseMove;
    function handleMouseMove(event) {
        var dot, eventDoc, doc, body, pageX, pageY;

        event = event || window.event; // IE-ism

        // If pageX/Y aren't available and clientX/Y are,
        // calculate pageX/Y - logic taken from jQuery.
        // (This is to support old IE)
        if (event.pageX == null && event.clientX != null) {
            eventDoc = (event.target && event.target.ownerDocument) || document;
            doc = eventDoc.documentElement;
            body = eventDoc.body;

            event.pageX = event.clientX +
              (doc && doc.scrollLeft || body && body.scrollLeft || 0) -
              (doc && doc.clientLeft || body && body.clientLeft || 0);
            event.pageY = event.clientY +
              (doc && doc.scrollTop  || body && body.scrollTop  || 0) -
              (doc && doc.clientTop  || body && body.clientTop  || 0 );
        }

        // Use event.pageX / event.pageY here
    }
})();

TERMS

========

String interpolation

  • add variable value to a string
  • ex: console.log(var+”hi”);
  • Escaping a letter
    • in a quote "There\'s something"
      • put a slash to print the apostrophe

TIPS

======

  • while testing on a web server
    • disable cache in inspect element
      • Network->Disable cache
  • change order of elements by appending/something the document.getElementById

====================================================================

====================================================================

====================================================================

JQUERY

========

$(thing)

  • means the element is from jquery and should act like one >:D

$(document)

$('button')

  • it’s a button element!
    • .on('event', doThis)
      • ‘event’ is the event psh. ex: ‘click’
      • doThis can be a function

====================================================================

====================================================================

====================================================================

Notes

========

Should probably use a modern front end library like ReactJS so that the site doesn’t become spaghetti code. These notes are a way to get started with HTML and Javascript, but don’t really talk about best coding practices.

Tags: coding_notes

How to Python

By Jenny Wang on October 6, 2018
~10 min. read

Weird things compared to Java

============

  • Passes lists to functions as references
    • list[1] = 2 actually changes data in list
  • No semicolon (;)
  • Tabs/spaces are necessary
  • Print does everything
  • Arrays replaced by lists
  • Comments are # (not //)
  • No main method (type everything together: global vars, functions, statements)
    • runs top to bottom (like javascript)
  • ”” same as ‘’ (aka strings)
  • booleans’ values are 0 or 1 (more below)
  • &&, ||, and ! are written as and, or, and not
  • True and False are capitalized
  • No variable type declaration (ex: var, int, double)
  • “To the power of” is **
    • ex: 2 ** 4 == 16
  • == works for strings
  • Multiline comments use triple quotes “””
    • ex:

        """I am a comment
        that can span
        multiple lines"""
      
  • Continuation character
    • Signifies that the next line is a part of the line above
    • ex:

        var this = \
        some_value
      
  • Functional programming allowed (Use lambda keyword)
    • Can pass functions as variables
  • Define multiple variables on one line
    • ex:

        var1, var2, var3 = val1, val2, val3
      
      • Must have one value per variable
  • Number is True if it isn’t 0 (if you’re not doing ==, but like if or while or smth) None would be False Returns the second to last # if the last # throws an error (ex: 1/0)

Terms

======

docstring

    '''Comment'''
  • Describes something

doctest

    >>> print("Test")
    Test
  • shows that this is how to use the function
  • can do python3 -m doctest to test it.
    • Prints out errors if output isn’t the same as expected

Operators

=========

7 / 2

  • div
  • Returns decimal representation of result

7 // 2

  • floordiv
  • Returns the rounded down integer of the result

booleans

=========

True, False

  • can be evaluated to 1 or 0
    • ex:

        points = isHit*pointsHit + (1-isHit)*pointsMiss
      
      • gives points correctly

not applies to the next boolean

  • ex: not 3 == 2 is True

for loops

=========

for i in range(<number>): does it <number> times consider <number> = len(myList)

for i in range(minIndex, maxIndex):

  • i is from [minIndex, maxIndex)
    • Note the inclusive [ and exclusive )

for elm in myList:

  • like a for-each loop in Java
  • elm is an element in myList

for key in myDictionary:

  • like for-each
  • get the value by doing myDictionary[key]
  • Keys are used in reverse-alphabetical order (z to a)
    • not necessarily in the order they were initialized to

for char in "string":

  • for each character in the string
  • because strings are lists

for index, item in enumerate(list):

  • index is the index of item in the list
  • item is the next item
  • A magical for-each loop with indices too

for a, b in zip(listA, listB):

  • Gives items in pairs. Will stop at the end of the shorter list
  • a is the nth item in listA
  • b is the nth item in listB
  • Can do this for as many lists as you want

for x in set(lst_a).intersection(lst_b):

  • Gives x if x is both in lst_a and lst_b

for x in set(lst_a).difference(lst_b):

  • Gives x if x is in lst_a but not in lst_b

if statements

=============

if <expression>:
    <do something>
elif <expression>:
    <do something>
else:
    <do something else>
<I'm out of the if statement!>

Functions

==========

def funcName(parameters):
    <"fuction docstring"> # Basically a comment to document the code
    <do something>
    <return [expression]>
     ^^^
    <"function docstring">- optional statement to document the function
    <do something>- the code block
    <return [expression]>- the return statement (optional)
                 - no return statement = return None

*args

  • ex: f(*args)
    • function takes in an arbitrary number of arguments
  • ex: run a generic function multiple times:

      def make_avg_f(fn, num_times):
          def avg_f(*args):
              return avg(f(*args))
          return avg_f
      >>> avg_f = make_avg_f(foo, 1000)
      >>> avg_f(foo_arg1, foo_arg2)
      100342342348729
    

Classes

========

class ClassName([BaseClass])
    member_var = True

    def __init__(self[, init_parameter, more, etc, ...]):
        self.init_parameter = init_parameter
    
    def other_method(self[, other_parameter, more, etc, ...]):
        <do something>
  • BaseClass - think about superclasses
    • If it’s not given, BaseClass defaults to object
    • Override methods by just making a new one with the same name/parameters
    • Classes that override don’t need the init() method
  • __init__ must have at least one parameter
    • self will refer to the object being created
  • In the example, .init_parameter is an attribute (no need for doing int attr, etc)
    • Access with my_square = Square() ==> my_square.sides
  • init_parameter is a member variable (not instance variable-to particular instances of the class)
    • only available to members of the ClassName class
  • member_var can be accessed by all objects of the ClassName class
    • But changing the value of one instance with hippo.is_alive = False doesn’t
      • change the value of the other ex: cat.is_alive
  • Use self.var to change any variables for that class’s instance

  • Methods - functions in a class
    • Must take self as first parameter
    • But when calling it, you don’t have to include self inside the ()
    • ex: temp = ClassName() ==> temp.other_method()
  • Call superclass’s methods
    • super(ChildClass’sName, self).super_method()
  • Functions from object
    • .init(self[, other_parameters, etc, …])
      • Think of a constructor
    • .repr(self)
      • Stands for representation
      • Tells Python how to represent the object, ex: when printing
      • ex: def __repr__(self): return "hi"

Lists

=======

  • ARRAYS DO NOT EXIST (but think of them). They are LISTS
  • Note the [] instead of the {} (dictionaries)
  • Use len(list) for number of items

myList = []

  • make a list
  • put values in [] if you want to initialize w/ values
    • ex: list = [2,3]

print myList

  • prints it in the format [value, value, value]

myList[<index or sublist>]

  • index: the index from 0 to len(myList)
  • sublist: : (inclusive:exclusive)
    • ex:
      • [3:5] gives list with elements 3 and 4
      • [:5] gives list w/ elements up until 4 (no 5)
      • [3:] gives list w/ elements 3 up until the end
      • [:] gives entire list
  • ex: myList[0:2] = [0,1]
    • AMAZING
    • array size on left doesn’t have to equal size on right. simply replaces. AMAZING
  • List comprehension for new lists
    • Initialize a fancy list

        [<var and expression] <for loop> [<if statement>]]
      
      • ex: list = [i for i in range(10)]
        • numbers 0 to 9 inclusive
      • ex: list = [i * 2 for i in range(10)]
        • even numbers 0 to 18 inclusive
      • ex: list = [i for i in range(51) if i % 2 == 0]
        • even numbers 0 to 50 inclusive
      • ex: list = [x*2 for x in range(6) if (x*2) % 3 == 0]
        • Even numbers that are divisible by 3 from 0 to 5 inclusive
          • So [6] (which is 3 * 2)
      • Also a good counter
        • ex: list = ["C" for x in range(5) if x < 3]
  • Concatenate lists with +
    • ex: x = [1,2], y=[2,3] => x + y = [1, 2, 2, 3]
  • Create list with repeating values
    • ex: [0] * 5 == [0, 0, 0, 0, 0]
    • ex: [0] * 2 * 2 == [0, 0, 0, 0] (not two lists inside a list)
      • Use .append() instead
  • To print without [] brackets list = [1, 2, 3] ==> " ".join(list) ==> "1 2 3"

  • functions
    • .append(val)
      • Add val into the last slot of the array
    • .count(val)
      • Returns int of the # of occurances of val in the list
    • .index(val)
      • returns index of val in the list
      • BEWARE: throws ValueError if m isn’t in the list
    • .insert(index, item) - inserts item at index (or the end of the list) - ex: insert at 100 then .index => at len(list)
    • .pop(index)
      • Removes item at index and returns it
    • .remove(value)
      • removes first item in the list that matches the value
      • NOTE: NOT THE INDEX
    • .sort(reverse=bool, key=func)
      • sorts items in the list (ex: alphabetical, smallest to largest)
      • modifies the list and doesn’t return a new one
      • reverse=True => descending order. Else or not included, ascending order
      • key=func => applied to the element before sorting
        • ex: lambda pair: pair[0] to sort by the zeroth element of the objects
    • del(list[index])
      • Removes the item at index and won’t return it
    • sum(myList)
      • returns sum of all elements in p

Dictionaries

============

  • Note the {} instead of the [] (lists)
  • Think of structs
  • Access values by looking up a key
  • Can put list in dictionaries O:
  • ex:

      names = {"dog":"Spike", "cat":"Fluffy", "bird":"Sugar"}
      names["dog"] == "Spike"
    
  • ex:

      residents = {1:"Bob", 2:"Joe", 3:"What are more names"}
      residents[1] == "Bob"
    
  • ex:

      dict = {} # Empty dictionary
    
  • ex:

      dict["new key"] = new_value
      adds a new key-value pair to the dictionary
    
  • ex:

      dict["old key"] = new_value
      changes the value associated with the key
    

del dict[key_name]

  • removes key_name and its associated value from the dictionary

  • Functions

    .items()

    • Returns a list of tuples of key-value pairs in the dictionary in no particular order
      • Tuple = group (a key/value pair in this case)

    .keys()

    • Returns list of keys of the dictionary in no particular order .values()
    • Returns list of the dictionary’s values in no particular order

defaultdict(default_value)

  • high performance container datatype that gives default_value if that key isn’t found

Tuple

======

  • An immutable list (unchangeable)
  • Surrounded by ()s and can contain any data type

Data structures

===============

  • Contained within collections
  • deque(iter_for_init[, maxlen]) (“DEHK” pronounciation)
    • Double-sided queue
    • append(x), appendleft(x), extend(iter), extendleft(iter), pop(), popleft()
    • remove(val), reverse(), clear()
    • count(x) - returns # of deque elements equal to x
    • rotate(n=1) shift in circular way to the right
    • maxlen - max length of the deque (corresponding # of items discarded as added if length > maxlen)

Bitwise operators

=================

  • Operators
    • >> - Right shift
      • “divide by 2 and round down”
      • Good for making a mask while not writing all the digits
    • << - Left shift
      • “multiply by 2”
      • Good for making a mask while not writing all the digits
    • & - Bitwise AND
      • “determine if a bit is on”
    • | - Bitwise OR
      • “turn a bit on if it’s off and leave the rest on”
    • ^ - Bitwise XOR
      • “flips a bit wherever there’s a 1 in the mask”
      • ex: 0b0110 ^ 0b1101 = 0b1011
    • ~ - Bitwise NOT
      • Equivalent to adding 1 to the number and making it negative
  • ex: flip nth bit

      num = num ^ 0b1 << (n - 1)
    
  • Denoting bases
    • base 2 - 0b<number>
    • base 8 - 0o<number>
    • base 16 - 0x<number>
  • Helpful functions
    • bin(num)
      • Returns binary representaion of num as a STRING
      • Can input binary, decimal, hex, etc (not string)
    • hex(num)
      • Returns hexadecimal representation of num as a STRING
    • oct(num)
      • Returns octadecimal representation of num as a STRING
    • int(<num as another type>[, baseTheNumCurrentlyIsIn])
      • Normally converts the num as another type to an integer
      • If num is a string, the optional parameter converts it to decimal (int)

Strings

========

***NOTE THE PRESCENCE AND LACK OF . BEFORE THE FUNCTION NAME***

s[index]

  • returns char at index

s[start:end:stride]

  • Returns substring from [start,end) with the step stride
  • Note that both start and end are optional
  • stride - like a step


  • To reverse a string
    • s[::-1] or reversed(s)
  • String Encoding declarations- 'str', u'str', r'str'
    • Are equivalent. They’re strings represented in different ways
    • u => Unicode
    • r => Raw
    • Convert among them with raw(str), unicode(str), str(str)
  • To remove a character ex: s = s[:3] + s[4:] ex: s = s.replace("old", "")
  • Functions
    • ord(char)
      • returns ASCII code of that character
    • chr(<ascii code>)
      • returns character represented by that ASCII code
    • len("string")
      • returns length of string
    • len(string)
      • returns length of string
    • max(string)
      • returns character w/ highest ASCII value in that string
    • min(string)
      • returns character w/ lowest ASCII value in that string
    • str1 in str2
      • returns whether str1 appears in str2
        • ^^ boolean True/False O.o
    • str1 <string comparison> str2
      • >, <, <=, >= compares ASCII values
      • ==, != check by value (not memory location)
    • isalnum(str)
      • returns if the string is alphanumeric
    • isalpha(str)
      • returns True if string contains only alphabets
    • isdigit(str)
      • returns True if string contains only digits
    • isidentifier(str)
      • return True is string is valid identifier
    • isspace(str)
      • returns True if string contains only whitespace
      • includes "\t", "\n", etc
    • endswith(s1: str)
      • returns True if strings ends with substring s1
    • startswith(s1: str)
      • returns True if strings starts with substring s1
    • count(substring)
      • returns number of occurrences of substring the string
    • .find(s1)
      • returns lowest index from where s1 starts in the string, if string not found returns -1
      • INDEXOF()! My love!
    • .rfind(s1)
      • returns highest index from where s1 starts in the string, if string not found returns -1
    • .lower()
      • return string by converting every character to lowercase
    • .upper() return string by converting every character to uppercase
    • .split("str")
      • Returns a list that has elements separated by str
      • The “str” is removed
    • .replace(oldStr, newStr[, numTimes])
      • No numTimes - returns str with every occurrence of old string replaced with new string
      • numTimes - Number of oldStrs to be replaced at maximum

Console Functions

==============

touch <filename.txt>

  • Creates filename.txt in the current directory

print var1[, var2, var3, ...]

  • ex: print p
  • print out to console
  • if variable is an array, prints like [0.1, 0.2] (array elements)
  • NOTE: print (with nothing afterwards) prints an empty line
  • **Putting multiple variables seperated by commas seperates them by a space
  • **print var, means that the next print statement will print on the same line

print("Number: %d, String: %s") % (my_num, my_str)

  • prints the string with %d’s, %s’s, etc replaced by the nth variable in ()

print(var[, end="string"])

  • prints the variable
  • end- prints “string” after printing the var
    • default = “\n”

input("Question")

  • prints question to console and returns the string response
  • NOTE: Returns a string, so to compare numbers, do int(input)

Keywords

========

break

  • exits the for loops

in

  • Returns whether the var is in the list
  • ex: x in range(8) == true
  • ex: x not in range(8) == false

lambda

  • Creates an anonymous function (define functions in-line)
  • Good for passing functions as parameters to functions
  • lambda <parameters>: <return expression>
    • Don’t have to have a parameter but must have a return
      • ex: (lambda: 3)() returns 3
  • ex: foo(lambda x: x % 3 == 0)
    • foo() can use that function as a parameter (renamed in the foo())
  • ex: lambda x: lambda: x
    • Returns a function that returns a number
  • ex: lambda f: f(4)
    • Use a function as a parameter
  • Used with filter()

pass

  • Doesn’t do anything. It’s a good placeholder
    • (; would throw a syntax error)

File I/O

========

  • Open a file

          f = open("filename.txt", "w")
    
    • Then you can f.write, f.close, f.read, etc
  • Functions that can’t be directly invoked
    • __enter__()
    • __exit__()
      • Automatically closes the file afterwards like .close() ex:

              with open("filename", "w" as textfile:
                  textfile.write("Success")
                  <read or write to file>
        
  • Attributes
    • closed
      • Returns True if the file is closed (eg: with .close())
      • Returns False if otherwise
  • Functions
    • open("filename.txt", "mode")
      • “filename.txt” is the filename
      • “mode” -
        • “w” - write
        • “r” - read
        • “r+” - read and write
        • “a” - append to the end of the file
    • .close()
      • Must be done or else text won’t be written properly
      • nd you can’t read until you’re “done” writing
    • .read()
      • Returns literally the whole text file lmao
    • .readline()
      • Returns a line from the file, including the newline
    • .write(str)
      • MUST BE A STRING (use str())
      • Does not add newlines (“\n”); must do it yourself

Multiprocessing

==============

  • multiprocessing.Queue

      >>> q = Queue()
      >>> q.put('something')
      >>> q.get()
      'something'
      >>> q.get() --> blocks and waits forever
    

Built-in Functions

==================

abs(var)

  • Returns abs value of number
  • Only takes one number

dir([obj])

  • Returns obj’s list of attributes
  • If no obj parameter - returns list of names in current local scope
  • ex: import math -> dir(math) is list of vars/funcs in math module
  • Can print dir(obj) to get all attributes

enumerate(list)

  • “supplies a corresponding index to each element in the list that you pass it”
  • Good for for loops
  • Get an index while still using a for-each loop

filter(function, list)

  • Returns list of elements in list that return True when passed through function
  • function- can be made anonymously with lambda keyword

id(var)

  • returns memory address of var
  • id(var1) == id(var2) to see if both point to same object

max(var)

  • Returns max value of var
  • See min(var)

min(var)

  • Returns minimum value of var
    • its value if it’s one number
    • the lowest in the iterable if it is one
  • Best to use it with integers and floats only (not strings)
  • Takes any number of arguments

range(stop)

  • Returns list with numbers 0 to stop - 1

range(start, stop)

  • Returns list with numbers start to stop - 1

range(start, stop, step)

  • Returns list with numbers start to stop - step with step step :P

reversed(str)

  • Returns the string with characters in reverse order

str(obj)

  • Returns a string containing a nicely printable version of the object
  • Think of toString() from Java

sum(list)

  • Returns the sum of the values in list
  • Only for numbers

type(obj)

  • Returns type of obj
  • ex: 1 => <type 'int'>, 2.0 => <type 'float'>, "hi" => <type 'str'>
  • ex: type(1.0) == float, type(1) == int

zip(list1, list2[, list3, list4, ...])

  • Gives pairs of items from each list. Good for for loops
  • Will stop with the shorter list
  • ex: zip([1, 2, 3], [4, 5, 6]) == [(1, 4), (2, 5), (3, 6)]
    • Access result with result[0][0] == 1
    • The () are tuples O:

Cool Modules (like libraries)

=============================

  • Generic import- import <module name>
    • Must use module.function_name() to use function
    • ex: import math
  • Function import- from <module name> import <function/variable>
    • Imports only that function from module
    • Can use function_name to use function instead of module.function()
    • ex: import sqrt from math Universal import- from <module name> import *
    • Imports all functions/variables from the module and don’t use module.function()
    • Makes code confusing b/c high possibility of conflicting names
  • Use functions/variables from:
    • math
      • sqrt(x)
      • returns square root of x
    • random
      • randint(min, max)
      • generates random integer from min to max inclusive
    • from numpy import np
      • good for vectors, matrices (2D arrays w/ extra features), and arrays (any dimension)
      • matrices can use * to multiply (not arrays)
      • arr[::3] etc works
      • arr1 + arr2 is addition of elements and not concatenation (reg lists)
      • .arange(start,end,step)
        • Returns NumPy array with numbers step away from each other from start to end exclusive
      • np.zeros([num_rows, num_cols])
        • Returns NumPy array that contains all 0s
      • np.eye(n)
        • Returns identity NumPy array with n rows and n cols
      • np.empty([m,n], dtype=np.int)
        • Returns empty m x n NumPy array with datatype int inside
      • np.matrix([[a11, a12], [a21, a22]])
        • Returns matrix with initial values
      • np.linspace(start, stop, num_divisions)
        • Returns NumPy array that has num_division numbers from start to stop equally spaced
      • np.concatenate([arr1, arr2, ...], axis)
        • Returns concatenation of arrays
        • axis
          • = 0 => stack vertically (1 ontop of another)
          • = 1 => stack horizontally
        • or np.vstack([arr1, arr2]) and np.hstack([arr1, arr2])
      • .flatten()
        • Returns array in one dimension
      • .reshape([m, n, ...])
        • Returns array with that many rows/columns/any other dimension
        • To get a 1D vector, just put a number inside
      • np.transpose(arr)
        • Returns transpose of arr
        • Also: mat.T
      • np.linalg.inv(arr) Returns inverse of arr
      • np.linalg.solve(a, b)
        • solves Ax = b. And returns as an array
      • np.dot(arr1, arr2)
        • Returns the result of matrix multiplication btwn arr1 and arr2
        • Order matters
      • np.floor(num)
      • np.ceil(num)
      • np.max(arr)
        • Returns max in an array
      • np.min(arr)
      • np.argmax(arr)
        • Returns index of max in an array
      • np.argmin(arr)
      • np.multiply(a, b)
        • Returns the multiplication of a and b element-wise - np.roll(arr, num_cells_to_roll, axis)
        • Shifts cells and puts the excess on the other side vNo need axis arg for 1D array
      • np.diagonal(arr)
        • Return diagonal elements of arr in another arr
    • argparse
      • .ArgumentParser(description="desc")
        • creates parser that you can do:
        • .add_argument("--parsed_name?", "-shortname", action='store_true',help="Runs strategy experiments")
        • .parse_args()
          • Returns parsed arguments in a… struct?
          • args.parsed_name
            • Boolean.
              • True- was included when running the file
              • False- not included when running the file
Tags: coding_notes