simulator

edges = {(1,'a'):2,
	(2, 'a'): 2,
	(2, '1'): 3,
	(3, '1'): 3}
	accepting = [ 3 ]

	def fsmsim(string, current, edges, accepting):
		if string == ""
			return current in accepting
		else:
			letter = string[0]
			if (current, letter) in edges:
				destination = edges[(current,letter)]
				remaining_string = string[1:]
				return fsmsim(remaining_string,destination,edges,accepting)
			else:
				return False
	print fsmsim("aaa111",1,edges,accepting)
import re

def umnums(sentence):
	r = r"[0-9]+"
	sum = 0
	for found in re.findall(r,sentence):
		sum = sum + int(found)
	return sum
(?:[a-z]+-[a-z]+)|(?:[a-z]+)
def nfsmsim(string, current edges, accepting):
	if string == "":
		return current in accepting
	else:
		letter = string[0:1]
		if (current, letter) in edges:
			remainder = string[1:]
			newstates = edges[(current, letter)]
			for newstate in newstates:
				if nfsmsim(remainder, newstate, edges, accepting):
					return True
	if current in visited:
		return None
	elif current in accepting:
		return ""
	else:
		newvisited = visited + [current]
		for edge in edges:
			if edge[0] == curent:
				for newstate in edges[edge]:
					foo = nfsmaccepts(nestate, edges, accepting, newvisited)
					if foo != None:
						return edge[1] + foo
		return None

breaking points

Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:19:22) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> "Ada Lovelace".find(" ")
3
>>> "Alan Turing".find("n",4)
9
def myfirst_yoursecond(p,q):
	pindex = p.find(" ")
	qindex = q.find(" ")
	return p[ :pindex] == q[qindex+1:]
>>> "Python is fun".split()
['Python', 'is', 'fun']
>>> "July-August 1842".split()
['July-August', '1842']
>>> "6*9==42".split()
['6*9==42']

Regular expression [1-3][4-8][a-b]

>>> r"[0-9][0-9]"
>>> re.findall(r"[0-9][0-9]", "July 28, 1821")
>>> re.findall(r"[0-9][0-9]", "12345")

r”a+”, r”[0-1]+”
regular expression rule is maximum match eat single match
re.findall(r”[0-9][ ][0-9]+”, “a1 2b cc3 44d”)
r”[0-9]+%”
r”[a-z]+|[0-9]+”,”Goothe 1798″

regexp = r”[a-z]+-?[a-z]+”

>>> re.findall(r”[0-9].[0-9]”, “1a1 222 cc3”)
[‘1a1’, ‘222’]

edges = {(1,'a'):2,
	(2, 'a'): 2,
	(2, '1'): 3,
	(3, '1'): 3}

loop

public void beep()

public boolean checkAlarm()

public void alarm(){
	boolean on = checkAlarm();
	while(on){
		beep();
		on = checkAlarm();
	}

}
String googol = "1";
int len = googol.length();
while(len < 101){
	googol = googol + "0";
	len = googol.length();
}

while loop

public int keepRolling(){
	int dice1 = rollDice();
	int dice2 = rollDice();
	int count = 1;
	while(!(dice1 == dice2)){
		dice1 = rollDice();
		dice2 = rollDice();
		count = count + 1;
	}
	return count;
}
public void raiseAlarm(int numOfWarnings){
	int i = 1;
	while(i <= numOfWarnings){
		System.out.println("warning");
		i = i + 1;
	}
}
public void raiseAlarm(int numOfWarnings){
	for (int i = 1; i <= numOfWarnings; i++){
		System.out.println("Warning");
	}
}

pyramid

public int countBlocks(int levels){
	int sum = 0;
	for(int i = 1; i <= levels; i++)
	{
		sum = sum + i * i; 
	}
    return sum;
}
public int martingale(){
	int money = 1000;
	int target = 1200;
	int bet = 10;
	while(money>bet){
		boolean win = play();
		if(win){
			money += bet;
			bet = 10;
		}
		else {
			money -= bet;
			bet *= 2;
		}
	}
	return money;
}

Function

public void println(String x){
	if(x == null){
		x = "null";
	}
	try {
		ensureOpen();
		textOut.write(x);
	} catch(IOException e){
		trouble = true;
	}
	newLine();
}
boolean playButton; 

public void playMusic(){
    if (playButton){
        System.out.println("Music is playing");
    } else {
    	System.out.println("Music is paused");
    }
}

parameter and argument

public void greeting(String location){
	System.out.println("Hello, " + location);
}
public int likePhoto(int currentLikes, String comment, boolean like){
	System.out.println("Feedback: "+ comment);
	if(like){
		currentLikes = currentLikes + 1;
	}
	System.out.println("Number of likes: " + currentLikes);
	return currentLikes;
}
public double makeChange(double itemCost, double dollarsProvided){
	double change = dollarsProvided - itemCost;
	return change;
}

random number

double randomNumber = Math.random();
randomNumber = randomNumber * 10;
int randomInt = (int) randomNumber;
public int rollDice(){
	double randomNumber = Math.random();
	randomNumber = randomNumber * 6 + 1;
	int randomInt = (int) randomNumber;
	return randomInt;
}

java documentation
https://docs.oracle.com/javase/8/docs/api/java/lang/package-summary.html

Math.random()
https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#random–

self driving car

boolean isLightGreen = true;
boolean isLightYellow = false;

if(isLightGreen){
	double carSpeed = 100;
	System.out.println("Drive!");
	System.out.println("Speed is:" + carSpeed);
} else if(isLightYellow) {
	System.out.println("Slow down.");
} else {
	System.out.println("Stop.");
}

museum ticket

int ticketPrice = 10;
int age = ;
boolean isStudent = ;

if (age <= 15){
	// age is less than or eaual to 15
	ticketPrice = 5;
} else if(age > 60) {
	ticketPrice = 5;
} else if(isStudent) {
	ticketPrice = 5;
}
System.out.println(ticketPrice);

logical operators
age <= 15 || age > 60 || isStudent

if(action && romance){

	System.out.println("this movie include action and romance")
	if(comedy || horror){
		System.out.println("this movie include comedy or horror")
	}
}

switch

int passcode = ;
String coffeeType;
switch(passcode){
	case 555: coffeeType = "Espresso";
		break;
	case 312: coffeeType = "Vanilla latte";
		break;
	case 629: coffeeType = "Drip coffee";
		break;
	default: coffeeType = "Unknown";
		break;
}
System.out.println(coffeeType);

java basic

int passengers;
passengers = 0;
passengers = passengers + 5;
passengers = passengers - 3;
passengers = passengers - 1 + 5;
System.out.println(passengers);

int stops;
int fare;
stops = 0;
fare = 0;
stops = stops + 1;
fare = fare + 5;
stops = stops + 1;
fare = fare + 3;
stops = stops + 1;
fare = fare + 7;
Systeml.out.println(stops);
String driver;
driver = "Hamish";
int letters = driver.length();
System.out.println(letters);

driver = driver.toUpperCase();
System.out.println(driver);
String driverFirstName;
driverFirstName = "Hamish";
String driverLastName;
driverLastName = "Blake";
String driverFullName = driverFirstName + " " + driverLastName;
System.out.println(driverFullName);
System.out.println("The bus made $"+fare+" after "+stops+"stops");

data type

int maxInt = 2147483647;
long muchMore = 2147483647*10000000;
double fraction = 99.275;
String fullText = "(b) WWII ended 1945";
char answer = 'b';
char three = '3';
boolean fact = true;
double current = 17;
double rate = 1.5;
double future = current * rate;
System.out.println(future);
int approx = (int) future;
System.out.println(approx);

casting

int x = 5;
int y = 2;
double div = x/y;
System.out.println(div);
double accurate = (double)x/y;
System.out.println(accurate);

average

double maths=97.5;
double english=98;
double science=83.5;
double drama=75;
double music=96;
double sum=maths+english+science+drama+music;
double average=sum/5;
System.out.println(average);

shader programming

MEMORYY, INSTRUCTION PROCESSING -> CPU
ALGORITHM PROCESSING -> GPU

vertextShader: [
	"uniform vec3 uMaterialColor;",
	"uniform vec3 uDirLight;",

	"varying vec3 vColor;",

	"void main(){",
	"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0);",
	"vec3 light = normalize( uDirLight );",

	"float diffuse = max( dot( normal, light), 0.0);",
	"vColor = uMaterialColor * diffuse;",
	"}"
].join("\n"),
uniform vec3 uMaterialColor;
uniform vec3 uDirLight;

varying vec3 vColor;

void main(){
	gl_Position = projectionMath * modelViewMatrix * vec4(position * 1.0);
	vec3 light = normalize( uDirLight );

	float diffuse = max( dot(normal, light), 0.0);
	vColor = uMaterialColor * diffuse;
}

texture and reflection

無題

var geo = new THREE.Geometry();

geo.vertices.push( new THREE.Vector3(0.0, 0.0, 0.0));
geo.vertices.push( new THREE.Vector3(4.0, 0.0, 0.0));
geo.vertices.push( new THREE.Vector3(4.0, 4.0, 0.0));

var uvs = [];
uvs.push( new THREE.Vector2( 0.0, 0.0 ));
uvs.push( new THREE.Vector2( 1.0, 0.0 ));
uvs.push( new THREE.Vector2( 1.0, 1.0 ));

geo.faces.push( new THREE.Face3(0, 1, 2));
geo.faceVertexUvs[ 0 ].push([ uvs[0], uvs[1], uvs[2]]);
var texture = new THREE.Texture();
texture.magFilter = THREE.NearestFilter;
texture.magFilter = THREE.LinearFilter;

texture.minFilter = THREE.NearestFilter;
texture.minFilter = THREE.LinearFilter;
texture.minFilter = THREE.LinearMipMapLinearFilter;

texture.anisotropy = 1;
texture.anisotropy = renderer.getMaxAnisotropy();
var disk = THREE.ImageUnits.loadTexture("textures/disc.png");
var material = new THREE.ParticleBasicMaterial(
	{ size: 35, sizeAttenuation: false, map: disk, tranparent: true});
material.color.setHSL( 0.9, 0.2, 0.6 );

var particles = new THREE.ParticleSystem( geometry, material );
particles.sortParticles = true;
scene.add( particles );
var geometry = new THREE.Geometry();
for ( var i = 0; i < 8000; i ++){
	var vertex = new THREE.Vector3();
	do {
	vertex.x = 2000 * Math.random() - 1000;
	vertex.y = 2000 * Math.random() - 1000;
	vertex.z = 2000 * Math.random() - 1000;
	} while ( vertex.length() > 1000 );
	geometry.vertices.push( vertex );
}
for ( var x = -1000; x <= 1000; x+= 100){
	for ( var y = -1000; y <= 1000; y+= 100){
		for(var z = -1000; z <= 1000; z+= 100){
			var vertex = new THREE.Vector3(x, y, z);
			geometry.vertices.push( vertex );
		}
	}
}
var uvs = [];
uvs.push( new THREE.Vector2(0.75, 0.25));
uvs.push( new THREE.Vector2(1.0, 0.25));
uvs.push( new THREE.Vector2(1.0, 0.5));
uvs.push( new THREE.Vector2(0.75, 0.5));
var texture = THREE.ImageUtils.loadTexture(
	'textures/grass512x512.jpg');
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(10, 10);
var solidGround = new THREE.Mesh(
	new THREE.PlaneGeometry(10000, 10000, 100, 100),
	new THREE.MeshLambertMaterial( { map: texture }));
var texture = THREE.ImageUtils.loadTexture('/media/img/cs291/textures/water.jpg');
var material = new THREE.MeshPhongMaterial({ shininess: 50});
material.specularMap = texture;
var teapotMaterial = new THREE.MeshPhongMaterial(
	{ color: 0x770000, specular:0xffaaaa,
	envMap: textureCube });

camera

fishereye, perspective, photograph

viewSize = 900;
aspectRatio = canvasWidth/canvasHeight;
camera = new THREE.OrthographicCamera(
	-aspectRatio*viewSize/ 2, aspectRatio*viewSize/2,
	viewSize / 2, -viewSize / 2,
	-1000, 1000);
camera.position.set( -890, 600, -480 );
cameraControls = new THREE.OrbitAndPanControls(camera, renderer.domElement);
cameraControls.target.set(0, 310, 0);
cameraControls.target.set(-2800, 360, -1600);
camera = new THREE.PerspectiveCamera( 30, aspectRAtio, 1, 10000);
camera.position.set( -170, 170, 40);
cameraControls = new THREE.OrbitAndPanControls(camera, renderer.domElement);
cameraControls.target.set(00, 50, 0);
effectController = {
	fov: 40
};
var gui = new dat.GUI();
var element = gui.add( effectController, "fov", 1.0, 179.0 );
element.name("field of view");

function render(){
	var delta = clock.getDelta();
	cameraControls.update(delta);

	camera.fov = effectController.fov;
	camera.updateProjectionMatrix();
	renderer.render(scene, camera);
}
var canvasWidth = window.innerWidth;
var canvasHeight = window.innerHeight;
renderer.setViewport(
	0.25 * canvasWidth, 0,
	0.5 * canvasWidth, 0.5 * canvasHeight );
frontCam = new THREE.OrthographicCamera(
	-aspectRatio*viewSize / 2, aspectRatio*viewSize / 2,
	viewSize / 2, -viewSize / 2,
	-1000, 1000);
frontCam.up.set( 0, 1, 0);
sideCam = new THREE.OrthographicCamera(
	-aspectRatio*viewSize / 2, aspectRatio*viewSize,
	viewSize / 2, -viewSize / 2,
	-1000, 1000);
sideCam.up.set( 0, 1, 0);

frontCam.position.copy( cameraControls.target);
frontCam.position.x -= 1;
frontCam.lookAt( cameraControls.target );
renderer.setViewport(0, 0.5*canvasHeight, 0.5*canvasWidth, 0.5*canvasHeight);
renderer.render( scene, frontCam );

sideCam.position.copy( cameraControls.target);
sideCam.position.z += 1;
sideCam.lookAt(cameraControls.target);
renderer.setViewport(0.5*canvasWidth, 0.5*canvasWidth, 0.5*canvasHeight);
renderer.render( scene, sideCam );
rearCam.position.copy(camera.position);
rearTarget.copy(camera.position);
rearTarget.sub(cameraControls.target);
rearTarget.add(camera.position);
rearCam.lookAt(rearTarget);

Light makes right

intensity 0 – 1

set directional light

var light = new THREE.DirectionalLight( 0xFFFAAD, 0.7 );
light.position.set( 200, 500, 600 );
scene.add( light);

lignt.position.set( 2, 5, 6);
light.position.set( 0.02, 0.05, 0.06 );
scene.add( new THREE.AmbientLight( 0x222222));

var someMaterial = new THREE.MeshLamberMaterial( );
someMaterial.color.setRGB(0.8, 0.2, 0.1);
someMaterial.ambient.copy( someMaterial.color );
function render(){
	var delta = clock.getDelta();
	cameraControls.update(delta);

	render.render(scene, camera);
}
headlight = new THREE.PointLight( 0xFFFFFF, 1.0 );
scene.add( headlight );
color: full white
intensity: 1.5
location: -400, 1200, 300
angle: 20 degrees
exponent: 1
target position: 0, 200, 0
var light = new THREE.SpotLight( 0xFFFFFF, 1.0 );
light.position.set( -400, 1200, 300);
light.angle = 20 * Math.PI / 180;
light.exponent = 1;
light.target.position.set(0, 200, 0);
scene.add(light);

shadow in three.js

renderer.shadowMapEnabled = true;

spotlight.castShadow = true;
cube.castShadow = true;
cube.receiveShadow = true;

bbird.traverse( function (object){
	object.castShadow = ture;
	object.receiveShadow = true;
	});
light.position.x = Math.cos(
	effectController.angle * Math.PI/180.0 );
light.position.z = Math.sin(
	effectController.angle * Math.PI/180.0 );
light.position.y = Math.sin(effectController.altitude * Math.PI/180.0);

var length = Math.sqrt(1 - light.position.y*light.position.y);
light.position.x = length * Math.cos( effectController.azimuth * Math.PI/180.0);
light.position.z = length * Math.sin( effectController.azimuth * Math.PI/180.0);