├── week6 ├── 1-Multithreading │ ├── WebCrawler │ │ ├── .attach_pid5957 │ │ ├── .settings │ │ │ ├── org.eclipse.m2e.core.prefs │ │ │ └── org.eclipse.jdt.core.prefs │ │ ├── target │ │ │ └── classes │ │ │ │ └── META-INF │ │ │ │ ├── MANIFEST.MF │ │ │ │ └── maven │ │ │ │ └── URLvsURI │ │ │ │ └── URLvsURI │ │ │ │ ├── pom.properties │ │ │ │ └── pom.xml │ │ ├── src │ │ │ └── com │ │ │ │ └── hackbulgaria │ │ │ │ └── corejava │ │ │ │ ├── Main.java │ │ │ │ └── WebCrawler.java │ │ ├── .project │ │ ├── .classpath │ │ └── pom.xml │ ├── Additional multithreading │ │ ├── .idea │ │ │ ├── .name │ │ │ ├── copyright │ │ │ │ └── profiles_settings.xml │ │ │ ├── vcs.xml │ │ │ ├── libraries │ │ │ │ ├── guava_18_0.xml │ │ │ │ └── commons_logging_1_2.xml │ │ │ ├── modules.xml │ │ │ ├── compiler.xml │ │ │ ├── misc.xml │ │ │ └── uiDesigner.xml │ │ ├── lib │ │ │ ├── lib │ │ │ ├── jna-4.1.0.jar │ │ │ ├── guava-18.0.jar │ │ │ ├── httpcore-4.4.1.jar │ │ │ ├── httpmime-4.4.1.jar │ │ │ ├── commons-codec-1.9.jar │ │ │ ├── fluent-hc-4.4.1.jar │ │ │ ├── httpclient-4.4.1.jar │ │ │ ├── commons-logging-1.2.jar │ │ │ ├── jna-platform-4.1.0.jar │ │ │ ├── httpclient-cache-4.4.1.jar │ │ │ └── httpclient-win-4.4.1.jar │ │ ├── src │ │ │ ├── src.zip │ │ │ ├── Main.java │ │ │ ├── AtomicSet.java │ │ │ ├── WebCrawler.java │ │ │ └── ParalelWebCrawler.java │ │ ├── out │ │ │ └── production │ │ │ │ └── NoIdea │ │ │ │ └── src.zip │ │ └── NoIdea.iml │ ├── agenda.md │ ├── pre.md │ ├── MultiWebCrawler │ │ └── com │ │ │ └── hackbulgaria │ │ │ └── corejava │ │ │ └── crawler │ │ │ └── no │ │ │ ├── Main.java │ │ │ ├── AtomicSet.java │ │ │ ├── WebCrawler.java │ │ │ └── ParalelWebCrawler.java │ └── README.md └── 2-Multithreading │ ├── agenda.md │ ├── WaitNotifyMechanism │ ├── .classpath │ ├── .project │ ├── .settings │ │ └── org.eclipse.jdt.core.prefs │ └── src │ │ └── com │ │ └── hackbulgaria │ │ └── corejava │ │ └── WaitNotifyMechanism.java │ ├── pre.md │ └── README.md ├── week1 ├── 1-DebuggingFun │ ├── DebuggingFun │ │ ├── bin │ │ │ └── .gitignore │ │ ├── libs │ │ │ └── commons-io-2.4.jar │ │ ├── src │ │ │ └── com │ │ │ │ └── hackbulgaria │ │ │ │ └── corejava │ │ │ │ ├── FaultyProblem1.java │ │ │ │ ├── FaultyProblem2.java │ │ │ │ ├── FaultyProblem6.java │ │ │ │ ├── FaultyProblem5.java │ │ │ │ ├── FaultyProblem3.java │ │ │ │ ├── FaultyProblem7.java │ │ │ │ ├── FaultyProblem4.java │ │ │ │ └── Utils.java │ │ ├── .project │ │ ├── test │ │ │ └── com │ │ │ │ └── hackbulgaria │ │ │ │ └── corejava │ │ │ │ ├── FaultyProblem5Test.java │ │ │ │ ├── FaultyProblem6Test.java │ │ │ │ ├── FaultyProblem3Test.java │ │ │ │ ├── FaultyProblem7Test.java │ │ │ │ ├── FaultyProblem2Test.java │ │ │ │ ├── FaultyProblem1Test.java │ │ │ │ └── FaultyProblem4Test.java │ │ ├── .classpath │ │ └── .settings │ │ │ └── org.eclipse.jdt.core.prefs │ ├── agenda.md │ ├── prereading.md │ └── README.md └── 2-OOP │ ├── agenda.md │ ├── prereading.md │ └── README.md ├── week5 ├── 1-Servlets-Tomcat │ ├── agenda.md │ ├── rome-1.0.jar │ ├── jdom-1.1.3.zip │ ├── HelloRest.java │ ├── README.md │ └── pre.md └── 2-Annotations-Reflection │ ├── agenda.md │ ├── pre.md │ └── README.md ├── week3 └── 1-Files-Paths-Streams │ ├── testData.zip │ ├── prereading.md │ └── README.md ├── week7 └── 1-Java8 │ ├── Java8Problems │ ├── .settings │ │ ├── org.eclipse.m2e.core.prefs │ │ └── org.eclipse.jdt.core.prefs │ ├── src │ │ └── com │ │ │ └── hackbulgaria │ │ │ └── corejava2 │ │ │ ├── data │ │ │ ├── Gender.java │ │ │ ├── Student.java │ │ │ └── StudentsDataFactory.java │ │ │ └── StudentOperations.java │ ├── .project │ ├── pom.xml │ ├── .classpath │ └── test │ │ └── com │ │ └── hackbulgaria │ │ └── corejava2 │ │ └── StudentOperationsImplTest.java │ ├── prereading.md │ └── README.md ├── Application ├── 4-Convert-To-Greyscale │ ├── images │ │ ├── john-romero.jpg │ │ └── john-romero-greyscale.jpg │ └── README.md ├── README.md ├── 1-Primes-In-An-Interval │ └── README.md ├── 3-Smallest-Substring-Containing-The-Alphabet │ └── README.md └── 2-List-Duplicating-Files │ └── README.md ├── .gitignore ├── week0 ├── 2-TypesArraysStrings │ ├── agenda.md │ ├── Project1 │ │ ├── src │ │ │ └── com │ │ │ │ └── hackbulgaria │ │ │ │ └── corejava │ │ │ │ ├── Problems2Factory.java │ │ │ │ ├── Problems2.java │ │ │ │ └── Problems2Impl.java │ │ ├── .classpath │ │ ├── .project │ │ ├── .settings │ │ │ └── org.eclipse.jdt.core.prefs │ │ └── test │ │ │ └── com │ │ │ └── hackbulgaria │ │ │ └── corejava │ │ │ └── tests │ │ │ └── Problems2Tests.java │ ├── prereading.md │ └── README.md └── 1-JavaPlatformIntroduction │ ├── README.md │ ├── prereading.md │ └── agenda.md ├── week2 ├── 2-Exceptions │ ├── week2 │ │ ├── .classpath │ │ ├── src │ │ │ └── exceptions │ │ │ │ └── example │ │ │ │ ├── Test5.java │ │ │ │ ├── Test4.java │ │ │ │ ├── Test1.java │ │ │ │ ├── Test2.java │ │ │ │ └── Test3.java │ │ ├── .project │ │ └── .settings │ │ │ └── org.eclipse.jdt.core.prefs │ ├── prereading.md │ └── README.md └── 1-CollectionsAndGenerics1 │ ├── prereading.md │ └── README.md ├── week4 ├── 2-REST │ ├── prereading.md │ └── README.md └── 1-Libraries-JSON-HTTPClient │ ├── prereading.md │ └── README.md └── README.md /week6/1-Multithreading/WebCrawler/.attach_pid5957: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /week1/1-DebuggingFun/DebuggingFun/bin/.gitignore: -------------------------------------------------------------------------------- 1 | /com 2 | -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/.idea/.name: -------------------------------------------------------------------------------- 1 | NoIdea -------------------------------------------------------------------------------- /week5/1-Servlets-Tomcat/agenda.md: -------------------------------------------------------------------------------- 1 | - Talk about servlets, Tomcat and enterprise 2 | - experiment with Tomcat 3 | -------------------------------------------------------------------------------- /week5/2-Annotations-Reflection/agenda.md: -------------------------------------------------------------------------------- 1 | - Why Reflection is black magic - how it is useful? 2 | - Annotations -------------------------------------------------------------------------------- /week5/1-Servlets-Tomcat/rome-1.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-2/HEAD/week5/1-Servlets-Tomcat/rome-1.0.jar -------------------------------------------------------------------------------- /week5/1-Servlets-Tomcat/jdom-1.1.3.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-2/HEAD/week5/1-Servlets-Tomcat/jdom-1.1.3.zip -------------------------------------------------------------------------------- /week3/1-Files-Paths-Streams/testData.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-2/HEAD/week3/1-Files-Paths-Streams/testData.zip -------------------------------------------------------------------------------- /week6/2-Multithreading/agenda.md: -------------------------------------------------------------------------------- 1 | - if time permits talk about advanced threading 2 | - using java.util.concurrent 3 | - use concurrent collections -------------------------------------------------------------------------------- /week6/1-Multithreading/agenda.md: -------------------------------------------------------------------------------- 1 | - Threading - simple to advanced stuff 2 | - how to create thread - wait, notify, join 3 | - how to measure and what to monitor -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /week7/1-Java8/Java8Problems/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/lib/lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-2/HEAD/week6/1-Multithreading/Additional multithreading/lib/lib -------------------------------------------------------------------------------- /week6/1-Multithreading/WebCrawler/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /Application/4-Convert-To-Greyscale/images/john-romero.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-2/HEAD/Application/4-Convert-To-Greyscale/images/john-romero.jpg -------------------------------------------------------------------------------- /week1/1-DebuggingFun/DebuggingFun/libs/commons-io-2.4.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-2/HEAD/week1/1-DebuggingFun/DebuggingFun/libs/commons-io-2.4.jar -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/src/src.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-2/HEAD/week6/1-Multithreading/Additional multithreading/src/src.zip -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/lib/jna-4.1.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-2/HEAD/week6/1-Multithreading/Additional multithreading/lib/jna-4.1.0.jar -------------------------------------------------------------------------------- /week6/1-Multithreading/WebCrawler/target/classes/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Built-By: georgi 3 | Build-Jdk: 1.7.0_55 4 | Created-By: Maven Integration for Eclipse 5 | 6 | -------------------------------------------------------------------------------- /Application/4-Convert-To-Greyscale/images/john-romero-greyscale.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-2/HEAD/Application/4-Convert-To-Greyscale/images/john-romero-greyscale.jpg -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/lib/guava-18.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-2/HEAD/week6/1-Multithreading/Additional multithreading/lib/guava-18.0.jar -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/lib/httpcore-4.4.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-2/HEAD/week6/1-Multithreading/Additional multithreading/lib/httpcore-4.4.1.jar -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/lib/httpmime-4.4.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-2/HEAD/week6/1-Multithreading/Additional multithreading/lib/httpmime-4.4.1.jar -------------------------------------------------------------------------------- /week7/1-Java8/Java8Problems/src/com/hackbulgaria/corejava2/data/Gender.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava2.data; 2 | 3 | public enum Gender { 4 | MALE, 5 | FEMALE, 6 | NOT_SURE 7 | } 8 | -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/lib/commons-codec-1.9.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-2/HEAD/week6/1-Multithreading/Additional multithreading/lib/commons-codec-1.9.jar -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/lib/fluent-hc-4.4.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-2/HEAD/week6/1-Multithreading/Additional multithreading/lib/fluent-hc-4.4.1.jar -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/lib/httpclient-4.4.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-2/HEAD/week6/1-Multithreading/Additional multithreading/lib/httpclient-4.4.1.jar -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/lib/commons-logging-1.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-2/HEAD/week6/1-Multithreading/Additional multithreading/lib/commons-logging-1.2.jar -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/lib/jna-platform-4.1.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-2/HEAD/week6/1-Multithreading/Additional multithreading/lib/jna-platform-4.1.0.jar -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/lib/httpclient-cache-4.4.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-2/HEAD/week6/1-Multithreading/Additional multithreading/lib/httpclient-cache-4.4.1.jar -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/lib/httpclient-win-4.4.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-2/HEAD/week6/1-Multithreading/Additional multithreading/lib/httpclient-win-4.4.1.jar -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/out/production/NoIdea/src.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-2/HEAD/week6/1-Multithreading/Additional multithreading/out/production/NoIdea/src.zip -------------------------------------------------------------------------------- /week1/1-DebuggingFun/agenda.md: -------------------------------------------------------------------------------- 1 | - A little recap on our previous meetings 2 | - How to debug in Eclipse 3 | - Debugging problems 4 | - Finish all String problems 5 | - Declaring (static) methods 6 | - Introduction to JUnit 7 | -------------------------------------------------------------------------------- /week1/1-DebuggingFun/prereading.md: -------------------------------------------------------------------------------- 1 | *On Enums in Java* 2 | http://javarevisited.blogspot.com/2011/08/enum-in-java-example-tutorial.html 3 | 4 | *A video for Junit and Eclipse* 5 | http://www.intertech.com/Blog/express-junit-training-video/ -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Mobile Tools for Java (J2ME) 4 | .mtj.tmp/ 5 | 6 | # Package Files # 7 | *.war 8 | *.ear 9 | 10 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 11 | hs_err_pid* 12 | -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/.idea/libraries/guava_18_0.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /week0/2-TypesArraysStrings/agenda.md: -------------------------------------------------------------------------------- 1 | 2 | ### Agenda #2 ### 3 | -Welcome to Eclipse 4 | -Coding style format import 5 | -Import Preferences and Quick Keys setup (Refactor Menu, Create getter, setter) 6 | -Hello world from Eclipse 7 | -Packages,Eclipse Views 8 | -Primitive types, arrays 9 | -if/for/while, switch 10 | -------------------------------------------------------------------------------- /week5/2-Annotations-Reflection/pre.md: -------------------------------------------------------------------------------- 1 | *Annotation & Reflection + example* 2 | http://tutorials.jenkov.com/java-reflection/index.html 3 | http://tutorials.jenkov.com/java/annotations.html 4 | 5 | *Long version of explanations* 6 | http://docs.oracle.com/javase/tutorial/java/annotations/ 7 | http://docs.oracle.com/javase/tutorial/reflect/ -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /week6/1-Multithreading/WebCrawler/target/classes/META-INF/maven/URLvsURI/URLvsURI/pom.properties: -------------------------------------------------------------------------------- 1 | #Generated by Maven Integration for Eclipse 2 | #Wed Jul 30 19:32:34 EEST 2014 3 | version=0.0.1-SNAPSHOT 4 | groupId=URLvsURI 5 | m2e.projectName=WebCrawler 6 | m2e.projectLocation=/home/georgi/Dev/workspace/WebCrawler 7 | artifactId=URLvsURI 8 | -------------------------------------------------------------------------------- /week2/2-Exceptions/week2/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /week6/2-Multithreading/WaitNotifyMechanism/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /week2/2-Exceptions/week2/src/exceptions/example/Test5.java: -------------------------------------------------------------------------------- 1 | package exceptions.example; 2 | 3 | public class Test5 { 4 | static boolean testReturn() { 5 | try { 6 | return true; 7 | } 8 | finally { 9 | return false; 10 | } 11 | } 12 | 13 | public static void main(String[] args) { 14 | System.out.println(testReturn()); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /week1/1-DebuggingFun/DebuggingFun/src/com/hackbulgaria/corejava/FaultyProblem1.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | public class FaultyProblem1 { 4 | public long getLargestPalindrome(long N) { 5 | N--; 6 | if (Utils.isPalindrome(N)) { 7 | return N; 8 | } else { 9 | return getLargestPalindrome(N-1); 10 | } 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /week2/2-Exceptions/week2/src/exceptions/example/Test4.java: -------------------------------------------------------------------------------- 1 | package exceptions.example; 2 | 3 | public class Test4 4 | { 5 | public static void main(String args[]) 6 | { 7 | try 8 | { 9 | System.out.print("Hello world "); 10 | } 11 | finally 12 | { 13 | System.out.println("Finally executing "); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /week1/1-DebuggingFun/DebuggingFun/src/com/hackbulgaria/corejava/FaultyProblem2.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | public class FaultyProblem2 { 4 | 5 | public int getNearestPowerOf2(int x) { 6 | int i = 1; 7 | while (x != 1) { 8 | x /= 2; 9 | i++; 10 | } 11 | 12 | return (int) Math.pow(2, i); 13 | } 14 | 15 | 16 | 17 | 18 | } 19 | -------------------------------------------------------------------------------- /week2/2-Exceptions/week2/src/exceptions/example/Test1.java: -------------------------------------------------------------------------------- 1 | package exceptions.example; 2 | 3 | public class Test1 { 4 | public static void main(String[] args) { 5 | try { 6 | int x = 0; 7 | int y = 5 / x; 8 | } catch (Exception e) { 9 | System.out.println("-exception-"); 10 | } catch (ArithmeticException ae) { 11 | System.out.println("-arithmetic exception-"); 12 | } 13 | System.out.println("-finished-"); 14 | } 15 | } -------------------------------------------------------------------------------- /week0/2-TypesArraysStrings/Project1/src/com/hackbulgaria/corejava/Problems2Factory.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | public class Problems2Factory { 4 | String OATH_TOKEN = "THIS IS MY DEAR PASSWORD"; 5 | 6 | public static Problems2 createProblems2Instance() { 7 | return new Problems2Impl(); 8 | } 9 | 10 | public static void main(String[] args) { 11 | } 12 | 13 | public static void meh(Integer k) { 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /week2/2-Exceptions/week2/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | week2 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /week0/2-TypesArraysStrings/Project1/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /week0/2-TypesArraysStrings/Project1/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | 1 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /week2/2-Exceptions/prereading.md: -------------------------------------------------------------------------------- 1 | *Exceptions hierarch in Java* 2 | http://www.javamex.com/tutorials/exceptions/exceptions_hierarchy.shtml 3 | 4 | *Try/catch/finally example* 5 | http://www.tutorialspoint.com/java/java_exceptions.htm 6 | 7 | *Try with resources in Java 7* 8 | http://www.mkyong.com/java/try-with-resources-example-in-jdk-7/ 9 | 10 | *Overriding methods with Exceptions in java* 11 | http://stackoverflow.com/questions/5875414/method-overriding-and-exceptions 12 | -------------------------------------------------------------------------------- /week1/1-DebuggingFun/DebuggingFun/src/com/hackbulgaria/corejava/FaultyProblem6.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | public class FaultyProblem6 { 4 | public static long pow(int a, int b) { 5 | if (b == 1){ 6 | return a; 7 | } 8 | if (b % 2 == 1) { 9 | return a * pow(a, b - 1); 10 | } else { 11 | long power = pow(a, b / 2); 12 | return power * power; 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /week1/1-DebuggingFun/DebuggingFun/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | DebuggingFun 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /week6/2-Multithreading/WaitNotifyMechanism/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | WaitNotifyMechanism 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /week1/1-DebuggingFun/DebuggingFun/test/com/hackbulgaria/corejava/FaultyProblem5Test.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | public class FaultyProblem5Test { 8 | 9 | @Test 10 | public void test() { 11 | assertEquals(1, FaultyProblem5.kthFac(0, 1)); 12 | 13 | assertEquals(2, FaultyProblem5.kthFac(1, 2)); 14 | 15 | assertEquals(720, FaultyProblem5.kthFac(2, 3)); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /week1/2-OOP/agenda.md: -------------------------------------------------------------------------------- 1 | - Everything is OOP! 2 | - What is a class? What is an object? 3 | - Method overloading, method overriding, virtual functions? 4 | - State/behaviour 5 | - Data Encapsulation, Subtype polymorphism, Liskov Principle 6 | - Object, equals, hashCode, getClass, toString, wait, notify, notifyAll 7 | - Constructors, on object construction in java, what happens on new()... 8 | - Subtyping (extending class) 9 | - interfaces/abstract classes 10 | - invariants 11 | - default & static methods in interfaces (java 8) -------------------------------------------------------------------------------- /week1/1-DebuggingFun/DebuggingFun/src/com/hackbulgaria/corejava/FaultyProblem5.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | 4 | public class FaultyProblem5 { 5 | public static long kthFac(int k, int n) { 6 | long res = 1; 7 | long limit = n; 8 | for (long i = 2; i <= limit; i++) { 9 | res *= i; 10 | if (i == limit && k > 0) { 11 | k--; 12 | limit = res; 13 | } 14 | } 15 | return res; 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /Application/README.md: -------------------------------------------------------------------------------- 1 | # Application problems for Core Java 2 | 3 | ## Problem 1 - Primes in an interval 4 | 5 | [Read the description here.](1-Primes-In-An-Interval) 6 | 7 | ## Problem 2 - List duplicating files 8 | 9 | [Read the description here.](2-List-Duplicating-Files) 10 | 11 | ## Problem 3 - Smallest substring containing the alphabet 12 | 13 | [Read the description here.](3-Smallest-Substring-Containing-The-Alphabet) 14 | 15 | ## Problem 4 - Convert to greyscale 16 | 17 | [Read the description here.](4-Convert-To-Greyscale) 18 | -------------------------------------------------------------------------------- /week1/1-DebuggingFun/DebuggingFun/test/com/hackbulgaria/corejava/FaultyProblem6Test.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | public class FaultyProblem6Test { 8 | 9 | @Test 10 | public void test() { 11 | assertEquals(1, FaultyProblem6.pow(1, 999999999)); 12 | assertEquals(8, FaultyProblem6.pow(2, 3)); 13 | assertEquals(16, FaultyProblem6.pow(2, 4)); 14 | assertEquals(1, FaultyProblem6.pow(4, 0)); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /week1/1-DebuggingFun/DebuggingFun/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /week1/1-DebuggingFun/DebuggingFun/src/com/hackbulgaria/corejava/FaultyProblem3.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | public class FaultyProblem3 { 4 | 5 | public String reverseEveryWordInString(String sentence){ 6 | String[] words = sentence.split(" "); 7 | for (String word: words){ 8 | sentence = sentence.replace(word, reverse(word)); 9 | } 10 | return sentence; 11 | } 12 | 13 | private CharSequence reverse(String word) { 14 | return Utils.reverseMe(word); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /week4/2-REST/prereading.md: -------------------------------------------------------------------------------- 1 | *URL vs URI* 2 | http://stackoverflow.com/questions/176264/whats-the-difference-between-a-uri-and-a-url 3 | 4 | *Reading directly from a URL* 5 | http://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html 6 | 7 | *Apache HTTP Client* 8 | https://hc.apache.org/httpcomponents-client-4.4.x/tutorial/html/index.html 9 | 10 | *Apache HTTP Client Examples* 11 | https://hc.apache.org/httpcomponents-client-4.4.x/examples.html 12 | 13 | *REST* 14 | http://en.wikipedia.org/wiki/Representational_state_transfer, 15 | http://www.looah.com/source/view/2284 16 | -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/NoIdea.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /week6/1-Multithreading/WebCrawler/src/com/hackbulgaria/corejava/Main.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | import java.io.IOException; 4 | import java.net.URI; 5 | import java.net.URISyntaxException; 6 | import java.util.concurrent.ExecutionException; 7 | 8 | public class Main { 9 | public static void main(String[] args) throws IOException, URISyntaxException, InterruptedException, 10 | ExecutionException { 11 | WebCrawler crawler = new WebCrawler(); 12 | 13 | URI startLocation = new URI("http://9gag.com/"); 14 | URI result = crawler.crawl(startLocation, "junk"); 15 | System.out.println("result :" + result.toString()); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /week6/1-Multithreading/WebCrawler/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | WebCrawler 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.m2e.core.maven2Nature 21 | org.eclipse.jdt.core.javanature 22 | 23 | 24 | -------------------------------------------------------------------------------- /week7/1-Java8/Java8Problems/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Java8Problems 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.m2e.core.maven2Nature 21 | org.eclipse.jdt.core.javanature 22 | 23 | 24 | -------------------------------------------------------------------------------- /week6/1-Multithreading/pre.md: -------------------------------------------------------------------------------- 1 | *Oracle's concurency trail* 2 | http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html 3 | *Q&A* 4 | * What is the difference between process and thread? 5 | * What is Runnable? Whats is Tread? 6 | * What are the most important methods in Thread ? 7 | * What is starvation, livelock and deadlock ? 8 | * What is thread interference and memory consistency errors ? 9 | * What is intrinsic lock ? 10 | 11 | *Multithreading example* 12 | http://www.tutorialspoint.com/java/java_multithreading.htm 13 | 14 | *Paralel execution with Executor, Future and Completion Service* 15 | http://www.javapractices.com/topic/TopicAction.do?Id=247 16 | -------------------------------------------------------------------------------- /week2/2-Exceptions/week2/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=1.8 6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 11 | org.eclipse.jdt.core.compiler.source=1.8 12 | -------------------------------------------------------------------------------- /week1/1-DebuggingFun/DebuggingFun/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=1.7 6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 11 | org.eclipse.jdt.core.compiler.source=1.7 12 | -------------------------------------------------------------------------------- /week0/2-TypesArraysStrings/Project1/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=1.7 6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 11 | org.eclipse.jdt.core.compiler.source=1.7 12 | -------------------------------------------------------------------------------- /week6/2-Multithreading/WaitNotifyMechanism/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=1.7 6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 11 | org.eclipse.jdt.core.compiler.source=1.7 12 | -------------------------------------------------------------------------------- /week2/2-Exceptions/week2/src/exceptions/example/Test2.java: -------------------------------------------------------------------------------- 1 | package exceptions.example; 2 | 3 | public class Test2 4 | { 5 | public static void throwIt () 6 | { 7 | System.out.print("-throw it-"); 8 | throw new RuntimeException(); 9 | } 10 | public static void main(String [] args) 11 | { 12 | try 13 | { 14 | System.out.print("-hello-"); 15 | throwIt(); 16 | } 17 | catch (Exception re ) 18 | { 19 | System.out.print("-caught-"); 20 | } 21 | finally 22 | { 23 | System.out.print("-finally-"); 24 | } 25 | System.out.println("-after-"); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Application/4-Convert-To-Greyscale/README.md: -------------------------------------------------------------------------------- 1 | # Problem 4 - Convert To Greyscale - this is optional! 2 | 3 | **This problem is optional. Solve it only if you can!** 4 | 5 | **You can apply with the previous 3 tasks.** 6 | 7 | In a programming language of your choice, implement the following function/method: 8 | ``` 9 | convertToGreyscale(imgPath) 10 | ``` 11 | Given the path of a color image (.jpg, .png, .bmp) create a greyscale version of it and save it. 12 | 13 | ## Examples 14 | **original** 15 | 16 | ![original](images/john-romero.jpg) 17 | 18 | **greyscale** 19 | 20 | ![greyscale](images/john-romero-greyscale.jpg) 21 | 22 | **WARNING!** You are not allowed to use any libraries, you have to write your own algorithm! 23 | -------------------------------------------------------------------------------- /week7/1-Java8/Java8Problems/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=1.8 6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 11 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 12 | org.eclipse.jdt.core.compiler.source=1.8 13 | -------------------------------------------------------------------------------- /week6/1-Multithreading/WebCrawler/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=1.7 6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 11 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 12 | org.eclipse.jdt.core.compiler.source=1.7 13 | -------------------------------------------------------------------------------- /week2/2-Exceptions/week2/src/exceptions/example/Test3.java: -------------------------------------------------------------------------------- 1 | package exceptions.example; 2 | 3 | public class Test3 4 | { 5 | public static void aMethod() throws Exception 6 | { 7 | try /* Line 5 */ 8 | { 9 | throw new Exception(); /* Line 7 */ 10 | } 11 | finally /* Line 9 */ 12 | { 13 | System.out.print("-finally-"); /* Line 11 */ 14 | } 15 | } 16 | public static void main(String args[]) 17 | { 18 | try 19 | { 20 | aMethod(); 21 | } 22 | catch (Exception e) /* Line 20 */ 23 | { 24 | System.out.print("-exception-"); 25 | } 26 | System.out.print("-finished-"); /* Line 24 */ 27 | } 28 | } -------------------------------------------------------------------------------- /week1/1-DebuggingFun/DebuggingFun/test/com/hackbulgaria/corejava/FaultyProblem3Test.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | 8 | public class FaultyProblem3Test { 9 | 10 | private FaultyProblem3 faultyProblem3; 11 | 12 | @Before 13 | public void setUp() { 14 | this.faultyProblem3 = new FaultyProblem3(); 15 | } 16 | 17 | @Test 18 | public void test() { 19 | assertEquals("gnikrow", faultyProblem3.reverseEveryWordInString("working")); 20 | assertEquals("tahw dluoc", faultyProblem3.reverseEveryWordInString("what could")); 21 | assertEquals("si siht laer efil", faultyProblem3.reverseEveryWordInString("is this real life")); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /week1/1-DebuggingFun/DebuggingFun/test/com/hackbulgaria/corejava/FaultyProblem7Test.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | 5 | import org.junit.Test; 6 | 7 | public class FaultyProblem7Test { 8 | 9 | @Test 10 | public void test() { 11 | // Code code = new Code("System.out.println(\"Hello World\");"); 12 | // Utils.eval(code, "Eval"); 13 | 14 | assertEquals(2, FaultyProblem7.binarySearch(3, 1, 2, 3, 4, 5, 6, 7, 8)); 15 | assertEquals(7, FaultyProblem7.binarySearch(8, 1, 2, 3, 4, 5, 6, 7, 8)); 16 | assertEquals(0, FaultyProblem7.binarySearch(1, 1, 2, 3, 4, 5, 6, 7, 8)); 17 | assertEquals(-1, FaultyProblem7.binarySearch(9, 1, 2, 3, 4, 5, 6, 7, 8)); 18 | 19 | 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /week1/1-DebuggingFun/DebuggingFun/test/com/hackbulgaria/corejava/FaultyProblem2Test.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | 8 | public class FaultyProblem2Test { 9 | 10 | private FaultyProblem2 faultyProblem2; 11 | 12 | @Before 13 | public void setUp() { 14 | this.faultyProblem2 = new FaultyProblem2(); 15 | } 16 | 17 | @Test 18 | public void test() { 19 | assertEquals(128, faultyProblem2.getNearestPowerOf2(129)); 20 | assertEquals(128, faultyProblem2.getNearestPowerOf2(240)); 21 | assertEquals(2, faultyProblem2.getNearestPowerOf2(2)); 22 | assertEquals(16, faultyProblem2.getNearestPowerOf2(20)); 23 | assertEquals(1, faultyProblem2.getNearestPowerOf2(1)); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /week6/1-Multithreading/WebCrawler/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /week5/2-Annotations-Reflection/README.md: -------------------------------------------------------------------------------- 1 | ### 1. Declare an annotation type 'ClassInfo' ### 2 | It should contain information about: 3 | - author of the class 4 | - revision of the class (by default it should be 1) 5 | - should the class be 'checked' (by default it should be) //this 'checked' thing is a bogus one, I just made it up so you can use a boolean default 6 | - an array of 'related' classes (Class[]) 7 | 8 | - Annotatate a class with this annotation. Fill in the 'required' information 9 | - In a main method, instantiate the annotated class. Using the `getClass().getAnnotations()`, print out all the annotations declared for your annotated class. 10 | - Now fetch your own annotation using `yourInstance.getClass().getAnnotation(YourAnnotationName.class);` 11 | - Print out all the filled information 12 | 13 | ### 2. JUnit ### 14 | Write an implementation of JUnit framework yourself 15 | -------------------------------------------------------------------------------- /week1/1-DebuggingFun/DebuggingFun/test/com/hackbulgaria/corejava/FaultyProblem1Test.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | 8 | public class FaultyProblem1Test { 9 | 10 | private FaultyProblem1 faultyProgram; 11 | 12 | @Before 13 | public void setUp(){ 14 | this.faultyProgram = new FaultyProblem1(); 15 | } 16 | 17 | //F5 -> IN! 18 | //F6 19 | // | 20 | // next line 21 | //F7 <-- out 22 | 23 | @Test 24 | public void test() { 25 | assertEquals(1, faultyProgram.getLargestPalindrome(2)); 26 | assertEquals(535, faultyProgram.getLargestPalindrome(544)); 27 | assertEquals(121, faultyProgram.getLargestPalindrome(126)); 28 | assertEquals(898, faultyProgram.getLargestPalindrome(908)); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /week6/2-Multithreading/pre.md: -------------------------------------------------------------------------------- 1 | *Deadlock, Livelock, Starvation* 2 | http://docs.oracle.com/javase/tutorial/essential/concurrency/liveness.html 3 | 4 | *Immutable objects and thread safety* 5 | http://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html 6 | 7 | *Lock and Condition objects* 8 | http://docs.oracle.com/javase/tutorial/essential/concurrency/newlocks.html 9 | 10 | *Math.random()* 11 | http://docs.oracle.com/javase/tutorial/essential/concurrency/threadlocalrandom.html 12 | 13 | *Books* 14 | - Concurrent Programming in Java: Design Principles and Pattern (2nd Edition) by Doug Lea, the architect of the Java platform's concurrency framework. 15 | - Java Concurrency in Practice by Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, and Doug Lea. 16 | 17 | 18 | *Lars Vogel's threading tutorial* 19 | http://www.vogella.com/tutorials/JavaConcurrency/article.html#forkjoin 20 | 21 | -------------------------------------------------------------------------------- /week1/1-DebuggingFun/DebuggingFun/src/com/hackbulgaria/corejava/FaultyProblem7.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | import java.lang.Thread.State; 4 | 5 | public class FaultyProblem7 { 6 | public static int binarySearch(int element, int... array) { 7 | // Utils.killMeIfIGetStuck(); 8 | 9 | int low = 0; 10 | int high = array.length - 1; 11 | 12 | int mid = (low + high) / 2; 13 | while (high - low > 1) { 14 | 15 | if (element == array[mid]) { 16 | return mid; 17 | } 18 | if (element < array[mid]) { 19 | high = mid; 20 | } else { 21 | low = mid; 22 | } 23 | } 24 | 25 | if (array[high] == element) 26 | return high; 27 | if (array[low] == element) 28 | return low; 29 | 30 | return -1; // not found 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /week7/1-Java8/prereading.md: -------------------------------------------------------------------------------- 1 | *On functional interfaces* 2 | http://java.dzone.com/articles/introduction-functional-1 3 | http://baddotrobot.com/blog/2014/04/07/functional-interfaces-in-java8/ 4 | Q: Give an example of an interface (or write a sane interface) that is not functional. 5 | Q: Which well known interface from Java 7 is a good candidate to be a functional interface? There are so many, pick one, it's enough. 6 | 7 | *On lambda expressions:* 8 | *Lambda expressions quick-start:* 9 | http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html 10 | http://viralpatel.net/blogs/lambda-expressions-java-tutorial/ 11 | 12 | *Stream API:* 13 | http://java.amitph.com/2014/01/understanding-java-8-streams-api.html 14 | http://java.amitph.com/2014/02/java-8-streams-api-intermediate.html#.VVJEQlSUe00 15 | http://java.amitph.com/2014/02/java-8-streams-api-terminal-operations.html#.VVJFU1SUe00 16 | 17 | -------------------------------------------------------------------------------- /Application/1-Primes-In-An-Interval/README.md: -------------------------------------------------------------------------------- 1 | # Problem 1 - Primes In An Interval 2 | 3 | In a programming language of your choice, implement the following function/method: 4 | ``` 5 | primesInAnInterval(from, to) 6 | ``` 7 | The goal is to return a collection of all the prime numbers in the given interval [from, to] 8 | 9 | ## Examples 10 | ``` 11 | primesInAnInterval(2, 20) -> [2, 3, 5, 7, 11, 13, 17, 19] 12 | primesInAnInterval(10, 30) -> [11, 13, 17, 19, 23, 29] 13 | primesInAnInterval(20, 10) -> invalid input 14 | primesInAnInterval(-20, 10) -> invalid input 15 | ``` 16 | 17 | ## Details 18 | - Make all sorts of checks for the interval - the `from` parameter has to be less than the `to` parameter, they both have to be positive integers etc. etc. 19 | - Design is not important at the moment. You could call the method from the main function, you could export it as a command line tool, you could execute it on a server - your choice 20 | -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/.idea/libraries/commons_logging_1_2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /week6/2-Multithreading/README.md: -------------------------------------------------------------------------------- 1 | ### Reimplement atomic int with Lock objects - test and measure performance 2 | 3 | ### Paralel web crawler 4 | 5 | There is a bottleneck in web crawling - while waiting for an answer from the server, the CPU does nothing. 6 | It would be better to make several requests at once. 7 | 8 | Try to crawl 9gag.com, for instance, and print every page you've visited. See the speed is not that great. 9 | Now Introduce parallelisation and speed up the solution. Use an approach similiar to the approach for task #1. 10 | 11 | If your web crawler project is not working, use the one in this github folder instead. (It's a Maven project, you will need to fetch all dependencies). 12 | 13 | 14 | ### Multiply Matrices 15 | Use the solution you did in the OOP lecture and add functionality to multiply two matrices - think about OOP decision to implement it - think how to speed it up, then measure how faster it is and also measure if CPU is allocated enough. (Team -- design) -------------------------------------------------------------------------------- /week1/1-DebuggingFun/DebuggingFun/src/com/hackbulgaria/corejava/FaultyProblem4.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | public class FaultyProblem4 { 4 | public static boolean areEqual(Integer e, Integer k) { 5 | k++; 6 | k--; 7 | return e == k; 8 | } 9 | 10 | public static boolean areEqual(float a, float b) { 11 | return a == b; 12 | } 13 | 14 | /** 15 | * Return whether there is an index i, 16 | * such that a[i,a.length] equals b[i, a.length]; 17 | * @param a 18 | * @param b 19 | * @return 20 | */ 21 | public static boolean haveEqualSubstrings(String a, String b) { 22 | for (int i = 0; i < a.length(); i++) { 23 | String substringA = a.substring(i, a.length() - 1); 24 | String substringB = b.substring(i, a.length() - 1); 25 | if (substringA.equals(substringB)){ 26 | return true; 27 | } 28 | } 29 | return false; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /week7/1-Java8/Java8Problems/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | Java8Problems 4 | Java8Problems 5 | 0.0.1-SNAPSHOT 6 | 7 | src 8 | test 9 | 10 | 11 | maven-compiler-plugin 12 | 3.1 13 | 14 | 1.8 15 | 1.8 16 | 17 | 18 | 19 | 20 | 21 | 22 | org.reflections 23 | reflections 24 | 0.9.9 25 | 26 | 27 | -------------------------------------------------------------------------------- /week7/1-Java8/Java8Problems/src/com/hackbulgaria/corejava2/data/Student.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava2.data; 2 | 3 | import java.util.Calendar; 4 | 5 | public class Student { 6 | private final String name; 7 | private final int age; 8 | private final double grade; 9 | private final Gender gender; 10 | 11 | /** 12 | * @param name 13 | * @param age 14 | * @param grade - between 2 and 6 15 | */ 16 | public Student(String name, int age, double grade, Gender gender){ 17 | this.name = name; 18 | this.age = age; 19 | this.grade = grade; 20 | this.gender = gender; 21 | } 22 | 23 | public String getName() { 24 | return name; 25 | } 26 | 27 | public int getAge() { 28 | return age; 29 | } 30 | 31 | public double getGrade() { 32 | return grade; 33 | } 34 | 35 | public Gender getGender() { 36 | return gender; 37 | } 38 | 39 | public String getEmail(){ 40 | return name + "_" + (Calendar.getInstance().get(Calendar.YEAR) - age) + "@gmail.com"; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Application/3-Smallest-Substring-Containing-The-Alphabet/README.md: -------------------------------------------------------------------------------- 1 | # Problem 3 - Smallest Substring Containing The Alphabet 2 | 3 | In a programming language of your choice, implement the following function/method: 4 | ``` 5 | smallestSubstringContainingTheAlphabet(str) 6 | ``` 7 | Given a string return the smallest substring that contains every letter from the English alphabet 8 | 9 | ## Examples 10 | 11 | **The output should be what's in the square brackets in the examples, they are there just for clarity** 12 | 13 | ``` 14 | smallestSubstringContainingTheAlphabet("aaaaaabcdefghijklmnopqrstuvwxyz") 15 | -> aaaaa[abcdefghijklmnopqrstuvwxyz] 16 | smallestSubstringContainingTheAlphabet("abcdefghijklmn124345678!@#$%^&*opqrstuvwxyz!*abcdefghijklmn") 17 | -> abcdefghijklmn124345678!@#$%^&*[opqrstuvwxyz!*abcdefghijklmn] 18 | ``` 19 | 20 | 21 | ## Details 22 | 23 | - The string will contain no whitespaces 24 | - The string may contain characters like `, . ~ ! @ # $ %` etc. But nothing outside of ASCII 25 | - The algorithm should be case insensitive 26 | - The order in which the letters are found is irrelevant 27 | -------------------------------------------------------------------------------- /week6/1-Multithreading/WebCrawler/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | URLvsURI 4 | URLvsURI 5 | 0.0.1-SNAPSHOT 6 | 7 | src 8 | 9 | 10 | maven-compiler-plugin 11 | 3.1 12 | 13 | 1.7 14 | 1.7 15 | 16 | 17 | 18 | 19 | 20 | 21 | commons-io 22 | commons-io 23 | 20030203.000550 24 | 25 | 26 | org.apache.httpcomponents 27 | httpclient 28 | 4.3 29 | 30 | 31 | -------------------------------------------------------------------------------- /week7/1-Java8/Java8Problems/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /week6/1-Multithreading/WebCrawler/target/classes/META-INF/maven/URLvsURI/URLvsURI/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | URLvsURI 4 | URLvsURI 5 | 0.0.1-SNAPSHOT 6 | 7 | src 8 | 9 | 10 | maven-compiler-plugin 11 | 3.1 12 | 13 | 1.7 14 | 1.7 15 | 16 | 17 | 18 | 19 | 20 | 21 | commons-io 22 | commons-io 23 | 20030203.000550 24 | 25 | 26 | org.apache.httpcomponents 27 | httpclient 28 | 4.3 29 | 30 | 31 | -------------------------------------------------------------------------------- /week2/1-CollectionsAndGenerics1/prereading.md: -------------------------------------------------------------------------------- 1 | *Simplest use of an ArrayList* 2 | http://www.mkyong.com/java/how-to-loop-arraylist-in-java/ 3 | 4 | *Check out some of the public methods of ArrayList* 5 | See its behaviour, what it can and can't do :) 6 | http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html 7 | 8 | *Some examples of the most used collections class in Java: ArrayList* 9 | http://javarevisited.blogspot.com/2011/05/example-of-arraylist-in-java-tutorial.html 10 | 11 | *Difference between Iterator and ListIterator* (if you are unfamiliar with iterators, skip this one for now : ) 12 | http://stackoverflow.com/questions/10977992/difference-between-iterator-and-listiterator 13 | 14 | *Diagram of ALL of java's collections framework:* 15 | http://www.codejava.net/java-core/collections/overview-of-java-collections-framework-api-uml-diagram 16 | 17 | ####Part 2#### 18 | *A HashMap example* 19 | http://www.tutorialspoint.com/java/java_hashmap_class.htm 20 | 21 | *HashMap vs Hashtable vs TreeMap in Java* 22 | http://www.programcreek.com/2013/03/hashmap-vs-treemap-vs-hashtable-vs-linkedhashmap/ 23 | 24 | *Equals and hashcode in java* 25 | http://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java 26 | 27 | -------------------------------------------------------------------------------- /week7/1-Java8/README.md: -------------------------------------------------------------------------------- 1 | ### Java 8 Problems 2 | 3 | Stream and lambda problems 4 | 1. Download and import the Java8 project to your eclipse or IntellIJ platforms 5 | 2. Subclass the `StudentOperations` interface and add all the methods so it compiles 6 | 3. Run the unit tests. Everything should fail. 7 | 8 | 4. Make them all green : ) 9 | 10 | Gotcha*: 11 | Create a functional interface, that would make the following code compile 12 | X x = () -> () -> () -> () -> () -> () -> () -> () -> () -> () -> () -> () -> () -> () -> () -> () -> null; 13 | 14 | Spliterator task: 15 | 'Spliterator' (`java.util.Spliterator`) is a new term from java8 - you can create streams by supplying spliterators. Spliterator is responsible for partitioning and object and advancing a stream. 16 | 17 | Implement a `SlidingWindowSpliterator` for collections. 18 | 19 | How to verify your spliterator is working correctly: 20 | 21 | ``` 22 | Collection testCollection = Arrays.asList("This","is","a","lame","example"); 23 | Spliterator yourSpliterator = new SlidingWindowSpliterator(testCollection, 2) //2 is the sliding window length 24 | StreamSupport.stream(yourSpliteratorObject).forEach(System.out::println); 25 | ``` 26 | ---- 27 | ``` 28 | This is 29 | is a 30 | a lame 31 | lame example 32 | ``` -------------------------------------------------------------------------------- /week1/2-OOP/prereading.md: -------------------------------------------------------------------------------- 1 | *On OOP in General* 2 | https://www.youtube.com/watch?v=lbXsrHGhBAU 3 | 4 | *OOP Trail @ Oracle* 5 | http://docs.oracle.com/javase/tutorial/java/concepts/index.html 6 | 7 | *Class and Objects @ Oracle (Those pages are actually Sun's property!)* 8 | http://docs.oracle.com/javase/tutorial/java/javaOO/ 9 | http://docs.oracle.com/javase/tutorial/java/concepts/object.html 10 | 11 | *More on Classes and objects* 12 | http://www.javaworld.com/article/2075202/core-java/object-oriented-language-basics-part-1.html?page=1 13 | 14 | *Constructors & new()* 15 | http://www.javaworld.com/article/2076204/core-java/understanding-constructors.html 16 | http://www.javaworld.com/article/2076614/core-java/object-initialization-in-java.html 17 | 18 | *Abstract classes vs Interfaces* 19 | http://www.programmerinterview.com/index.php/java-questions/interface-vs-abstract-class/ 20 | http://www.javaworld.com/article/2077421/learn-java/abstract-classes-vs-interfaces.html?null 21 | 22 | *Override, overload, hide* 23 | http://docs.oracle.com/javase/tutorial/java/IandI/override.html 24 | 25 | *Subtyping & Liskov principle* 26 | https://www.youtube.com/watch?v=IL61KMYK0b8 27 | 28 | *Default Methods* 29 | http://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html 30 | 31 | *Invariants* 32 | http://people.cs.aau.dk/~normark/oop-csharp/html/notes/contracts_themes-class-inv-sect.html 33 | -------------------------------------------------------------------------------- /week0/2-TypesArraysStrings/Project1/src/com/hackbulgaria/corejava/Problems2.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | public interface Problems2 { 4 | boolean isOdd(int number); 5 | 6 | boolean isPrime(int number); 7 | 8 | int min(int... array); 9 | 10 | int kthMin(int k, int[] array); 11 | 12 | float getAverage(int[] array); 13 | 14 | long getSmallestMultiple(int upperBound); 15 | 16 | long getLargestPalindrome(long N); 17 | 18 | int[] histogram(short[][] image); 19 | 20 | long doubleFac(int n); 21 | 22 | long kthFac(int k, int n); 23 | 24 | int getOddOccurrence(int[] array); 25 | 26 | long pow(int a, int b); 27 | 28 | long maximalScalarSum(int[] a, int[] b); 29 | 30 | int maxSpan(int[] array); 31 | 32 | boolean canBalance(int[] array); 33 | 34 | int[][] rescale(int[][] original, int newWidth, int newHeight); 35 | 36 | String reverseMe(String argument); 37 | 38 | String copyEveryChar(String input, int k); 39 | 40 | String reverseEveryWord(String arg); 41 | 42 | boolean isPalindrome(String argument); 43 | 44 | boolean isPalindrome(int number); 45 | 46 | int getPalindromeLength(String input); 47 | 48 | int countOcurrences(String needle, String haystack); 49 | 50 | String decodeURL(String input); 51 | 52 | int sumOfNumbers(String input); 53 | 54 | boolean areAnagrams(String A, String B); 55 | 56 | boolean hasAnagramOf(String string, String string2); 57 | } 58 | -------------------------------------------------------------------------------- /week1/1-DebuggingFun/README.md: -------------------------------------------------------------------------------- 1 | ###Some debugging fun### 2 | 1) Get latest changes from HackBulgaria repo 3 | `git pull` 4 | or 5 | `git clone https://github.com/HackBulgaria/Core-Java-2.git` 6 | 7 | 2) Import the DebuggingFun project in Eclipse 8 | - if you use 'import existing projects Eclipse it will not copy it in your workspace 9 | - if you use 'import from file system' 10 | 11 | 12 | //The ProjectName for all of the three problems below should be 'TDDIntro' 13 | 14 | ###JUnit Hello world### 15 | Implement a method 'getNumberOfDigits(int)' which just counts the number of digits. 16 | 17 | 1) Write the signature of the method 18 | 2) Write the test, make sure it fails beautifully. Think of some edge cases. 19 | 3) Implement the method 20 | 4) Pass your own test! Woohoo! 21 | 22 | 23 | ###Implement a join method### 24 | Java does not have a String join method. Apache StringUtils does have, but, well, that's not an excuse. 25 | 26 | Make a method that joins strings, with a **glue** given from the caller of your method. 27 | 28 | Can you think of a way for it to work with every object, not just string? Even primitives? 29 | 30 | //Glue is the first argument => " " 31 | `stichMeUp(" ", "Днес", "видях", 5, "ходещи", "медузи") => "Днес видях 5 ходещи медузи"` 32 | 33 | 1) Think of a good name for this method 34 | 2) Make a test class 35 | 3) Make several test cases, see that your tests fail mightily : ) 36 | 4) Implement! 37 | 38 | ###Reduce file path! In Java. In a test-driven way. ### 39 | See Problem 27 @ https://github.com/HackBulgaria/Programming101/blob/master/week0/simple_problems2.md 40 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Core-Java-2 2 | 3 | The second edition of the Core Java course in Hack Bulgaria. 4 | 5 | ``` 6 | _____ _ 7 | / ____| | | 8 | | | ___ _ __ ___ | | __ _ __ __ __ _ 9 | | | / _ \ | '__|/ _ \ _ | | / _` |\ \ / // _` | 10 | | |____| (_) || | | __/ | |__| || (_| | \ V /| (_| | 11 | \_____|\___/ |_| \___| \____/ \__,_| \_/ \__,_| 12 | 13 | ``` 14 | 15 | ## Course Program 16 | 17 | **The program is subject to change and will change until it gets to its final form ;)** 18 | 19 | * Week 0 -> Java Platform Introduction, Eclipse/JDK installings and configurations, Types, Arrays, Strings in Java 20 | * Week 1 -> Introduction to debugging, 'Find-the-error-in-the-code-via-debugging' problems, Classes/Overloading/Overriding/OOP, default methods in interfaces, static methods and implementations in interfaces 21 | * Week 2 -> Collections, Generics, Defensive Programming/Error Handling 22 | * Week 3 -> Working with Files, Paths and Streams. 23 | * Week 4 -> Working with external libraries. JSON, HttpClient & email sending. 24 | * Week 5 -> Consuming REST services, Downloading things from the internet, crawling websites & making heartbeat services. 25 | * Week 6 -> Servlets, Tomcat, Annotations, Reflection 26 | * Week 7 -> Multithreading - Parallel Execution, Java concurrency mechanisms 27 | * Week 8 -> Java 8 API & Functional paradigm. 28 | * Week 9 -> Generics 2, Weak pointers, Garbage Collection, More Threading 29 | 30 | -------------------------------------------------------------------------------- /week6/1-Multithreading/MultiWebCrawler/com/hackbulgaria/corejava/crawler/no/Main.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava.crawler.no; 2 | 3 | import java.io.IOException; 4 | import java.net.URI; 5 | import java.net.URISyntaxException; 6 | import java.util.Set; 7 | import java.util.concurrent.ExecutionException; 8 | import java.util.concurrent.ExecutorService; 9 | import java.util.concurrent.Executors; 10 | import java.util.concurrent.atomic.AtomicInteger; 11 | 12 | import com.hackbulgaria.corejava.crawler.no.ParalelWebCrawler; 13 | 14 | public class Main { 15 | public static void main(String[] args) throws IOException, URISyntaxException, InterruptedException, 16 | ExecutionException { 17 | long start = System.currentTimeMillis(); 18 | // WebCrawler crawler = new WebCrawler(); 19 | ExecutorService service = Executors.newCachedThreadPool(); 20 | ParalelWebCrawler crawler = new ParalelWebCrawler(service); 21 | 22 | // String url = "http://9gag.com/"; 23 | // String needle = "junk"; 24 | String url = "http://blog.hackbulgaria.com"; 25 | String needle = "Python"; 26 | 27 | AtomicInteger in = new AtomicInteger(); 28 | 29 | URI startLocation = new URI(url); 30 | crawler.visit(startLocation); 31 | Set result = crawler.crawl(startLocation, needle, in); 32 | 33 | while (!in.compareAndSet(0, 0)) { 34 | synchronized (in) { 35 | in.wait(); 36 | } 37 | } 38 | service.shutdown(); 39 | 40 | System.out.println("result: " + result.toString()); 41 | 42 | for (URI uri : result) { 43 | System.out.println(uri); 44 | } 45 | System.out.println("links: " + result.size()); 46 | System.out.println("time: " + (System.currentTimeMillis() - start)); 47 | } 48 | 49 | } -------------------------------------------------------------------------------- /week0/1-JavaPlatformIntroduction/README.md: -------------------------------------------------------------------------------- 1 | ### Verify java is working and is in $PATH ### 2 | ```java -version``` 3 | 4 | ```javac -version``` 5 | 6 | ```javap -version``` 7 | 8 | Friendly advice: These should be the same version, or you might have a bad time :) 9 | 10 | ### Compiling fun with javac and java### 11 | - Open a terminal. Navigate to any folder whatsoever. Make a new Empty.java file. Try to compile it with javac. See what happens. 12 | - Make a class named Program. Try to compile it with javac. 13 | - Rename the class to Empty. Compile it. 14 | - Make a main method. Make it print "Hello world!". Compile it and run it. 15 | - Make the main method print its arguments (String[] args). Make the for loop as you would make one in C or C++, and use the System.out.println method for printing to the console. 16 | 17 | ### Getting to know what classpath is### 18 | - Open a terminal, navigate to some folder. Make a new A.java file with a legitimate class A declared in it. 19 | - Do the same for a file/class named B. 20 | - Declare a public method in B. 21 | - In class A, make a *main method* 22 | - Instantiate B in it and call B's public method. 23 | - Try, compile and run A. Does it run? Why? How does it know about B? What about import statements? 24 | 25 | - Now move B up one folder to '..' 26 | - Try compiling and running it. 27 | 28 | - Add -cp ".." to your javac command and try again. 29 | 30 | ###Bundle them both### 31 | - jar -c A.class 32 | - Does this command look familiar to you? : ) 33 | 34 | ### Disassembly with javap ### 35 | - Disassemble Empty.class 36 | - Does this look familiar to you? This is what Eclipse is doing when you open a look up a class file with no source attached. 37 | 38 | 39 | -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/src/Main.java: -------------------------------------------------------------------------------- 1 | import com.google.common.util.concurrent.ListeningExecutorService; 2 | import com.google.common.util.concurrent.MoreExecutors; 3 | 4 | import java.io.IOException; 5 | import java.net.URI; 6 | import java.net.URISyntaxException; 7 | import java.util.Set; 8 | import java.util.concurrent.ExecutionException; 9 | import java.util.concurrent.ExecutorService; 10 | import java.util.concurrent.Executors; 11 | import java.util.concurrent.atomic.AtomicInteger; 12 | 13 | public class Main { 14 | public static void main(String[] args) throws IOException, URISyntaxException, InterruptedException, 15 | ExecutionException { 16 | long start = System.currentTimeMillis(); 17 | // WebCrawler crawler = new WebCrawler(); 18 | ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool()); 19 | ParalelWebCrawler crawler = new ParalelWebCrawler(service); 20 | 21 | // String url = "http://9gag.com/"; 22 | // String needle = "junk"; 23 | String url = "http://blog.hackbulgaria.com"; 24 | String needle = "Python"; 25 | 26 | AtomicInteger in = new AtomicInteger(); 27 | 28 | URI startLocation = new URI(url); 29 | crawler.visit(startLocation); 30 | Set result = crawler.crawl(startLocation, needle, in); 31 | 32 | while (!in.compareAndSet(0, 0)) { 33 | synchronized (in) { 34 | in.wait(); 35 | } 36 | } 37 | service.shutdown(); 38 | 39 | System.out.println("result: " + result.toString()); 40 | 41 | for (URI uri : result) { 42 | System.out.println(uri); 43 | } 44 | System.out.println("links: " + result.size()); 45 | System.out.println("time: " + (System.currentTimeMillis() - start)); 46 | } 47 | 48 | } -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 1.8 31 | 32 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /week1/1-DebuggingFun/DebuggingFun/test/com/hackbulgaria/corejava/FaultyProblem4Test.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | public class FaultyProblem4Test { 8 | 9 | @Test 10 | public void testFloats() { 11 | for (int i = 2; i < 97; i++) { 12 | for (int j = 3; j < i * 17; j++) { 13 | float a = (float) i / j; 14 | float b = 1 / ((float) j / i); 15 | System.out.println(a + ", " + b); 16 | assertTrue(FaultyProblem4.areEqual(a, b)); 17 | } 18 | } 19 | } 20 | 21 | @Test 22 | public void testAgainFloats(){ 23 | assertTrue(FaultyProblem4.areEqual(0/6, 0/5)); 24 | assertTrue(FaultyProblem4.areEqual(401/399, 1/(399/401))); 25 | } 26 | 27 | @Test 28 | public void testInts() { 29 | assertTrue(FaultyProblem4.areEqual(4, 4)); 30 | assertTrue(FaultyProblem4.areEqual(0, 0)); 31 | assertTrue(FaultyProblem4.areEqual(500, 500)); 32 | 33 | // Защо са верни горните, а този тест фейлва? ^^^ 34 | assertTrue(FaultyProblem4.areEqual(new Integer(511), (Integer) 511)); 35 | } 36 | 37 | @Test 38 | public void testSubstringEquality() throws Exception { 39 | String a = "how do you do"; 40 | String b = "how do you do"; 41 | 42 | assertTrue(FaultyProblem4.haveEqualSubstrings(a, b)); 43 | 44 | a = "Bearded Man"; 45 | b = "Non-bearded Man"; 46 | assertFalse(FaultyProblem4.haveEqualSubstrings(a, b)); 47 | 48 | a = "Speaks"; 49 | b = "Freaky"; 50 | assertFalse(FaultyProblem4.haveEqualSubstrings(a, b)); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /week7/1-Java8/Java8Problems/src/com/hackbulgaria/corejava2/data/StudentsDataFactory.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava2.data; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class StudentsDataFactory { 7 | public static List getAllStudents(){ 8 | List students = new ArrayList(); 9 | students.add(new Student("Georgi", 19, 2.0f, Gender.MALE)); 10 | students.add(new Student("Dimitur", 21, 2.0f, Gender.MALE)); 11 | students.add(new Student("Vasil", 19, 2.0f, Gender.MALE)); 12 | 13 | students.add(new Student("Tihomir", 20, 3.0f, Gender.MALE)); 14 | students.add(new Student("Ivomir", 20, 3.0f, Gender.MALE)); 15 | students.add(new Student("Vladislav", 21, 3.0f, Gender.MALE)); 16 | 17 | students.add(new Student("Filip", 19, 3.5f, Gender.MALE)); 18 | students.add(new Student("Boris", 20, 3.5f, Gender.MALE)); 19 | 20 | students.add(new Student("Genady", 21, 4.0f, Gender.MALE)); 21 | students.add(new Student("Ivan", 21, 4.0f,Gender.MALE)); 22 | students.add(new Student("Elena", 21, 4.0f, Gender.FEMALE)); 23 | 24 | students.add(new Student("Radoslav", 22, 4.5f, Gender.MALE)); 25 | students.add(new Student("Maria", 22, 4.5f,Gender.FEMALE)); 26 | 27 | students.add(new Student("Teodor", 22, 5.0f,Gender.MALE)); 28 | students.add(new Student("Stanislava", 22, 5.0f, Gender.FEMALE)); 29 | 30 | students.add(new Student("Anton", 20, 5.5f, Gender.MALE)); 31 | students.add(new Student("Marina", 21, 5.5f, Gender.FEMALE)); 32 | students.add(new Student("Salfetka", 21, 5.5f, Gender.FEMALE)); 33 | students.add(new Student("Zlatina", 22, 5.5f, Gender.FEMALE)); 34 | 35 | students.add(new Student("Petar", 19, 6.0f, Gender.MALE)); 36 | students.add(new Student("Yanitsa", 21, 6.0f, Gender.FEMALE)); 37 | return students; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /week0/1-JavaPlatformIntroduction/prereading.md: -------------------------------------------------------------------------------- 1 | ##Start Here!## 2 | 3 | Welcome :) 4 | 5 | Here are a few things you should probably get done before the start of the core java course: 6 | 7 | **1)** Install JDK 8 ( Java SE Development Kit ) - we will work with it 8 | http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html 9 | 10 | **2)** Make sure java binaries are registered in PATH 11 | and that they are **the same version** 12 | 13 | ``` 14 | java -version 15 | 16 | java version "1.8.0_31" 17 | Java(TM) SE Runtime Environment (build 1.8.0_31-b13) 18 | Java HotSpot(TM) 64-Bit Server VM (build 25.31-b07, mixed mode) 19 | ``` 20 | ``` 21 | javac -version 22 | javac 1.8.0_31 23 | ``` 24 | 25 | **3)** Install Eclipse Kepler from Eclipse site: 26 | https://www.eclipse.org/downloads/packages/eclipse-ide-java-developers/lunasr1a 27 | For those who want to read what it is: https://www.eclipse.org/community/eclipse_newsletter/2014/june/article1.php 28 | 29 | **4)** Read the Google style-guide for Java source code: 30 | http://google-styleguide.googlecode.com/svn/trunk/javaguide.html 31 | 32 | We will be using very similiar style guide, but with the following modifications: 33 | - 4 spaces for identation instead of 2. 34 | - 120 lines for line-wrapping instead of 80. 35 | 36 | **5)** Import eclipse preferences (the .epf file) in Eclipse 37 | `File->Import->General->Preferences` 38 | 39 | **6)** Import the code formatter (the .xml file) in Eclipse 40 | `Window->Preferences-> Write 'Format' in the search field up left-> Select the one below 'Java' -> Click on Import` 41 | 42 | **7)** Create yourself a GitHub account! 43 | If you have never worked with git or GitHub, see the excellent article from 44 | HackBulgaria's programming 101 course: 45 | https://github.com/HackBulgaria/Programming101/tree/master/week1/git.md -------------------------------------------------------------------------------- /week4/1-Libraries-JSON-HTTPClient/prereading.md: -------------------------------------------------------------------------------- 1 | *URL vs URI* 2 | http://stackoverflow.com/questions/176264/whats-the-difference-between-a-uri-and-a-url 3 | http://stackoverflow.com/questions/176264/what-is-the-difference-between-a-uri-a-url-and-a-urn/1984225#1984225 4 | https://danielmiessler.com/study/url_vs_uri/ 5 | 6 | *Q&A* 7 | * What is URL? 8 | * What is URI? 9 | * What is URN? 10 | 11 | *Time : 20 min* 12 | 13 | *Reading directly from a URL* 14 | http://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html 15 | 16 | *Time : 40 min* 17 | 18 | *Apache HTTP Client* 19 | https://hc.apache.org/httpcomponents-client-4.4.x/tutorial/html/index.html, 20 | http://stackoverflow.com/questions/7199969/apache-httpcore-simple-server-to-echo-received-post-data 21 | 22 | *Time : 30 min* 23 | 24 | let me google that for you: 25 | * json — http://stackoverflow.com/questions/383692/what-is-json-and-why-would-i-use-it 26 | 27 | *Time : 20 min* 28 | *Q&A* 29 | * What is JSON? 30 | * What is JSON structure? 31 | * Bonus: What is Javascript Object? 32 | http — http://www.w3schools.com/tags/ref_httpmethods.asp 33 | *Time : 30 min* 34 | *Q&A* 35 | * What is HTTP? 36 | * What is HTTP request? 37 | * What is POST, GET, DELETE request? 38 | * What is HTTP response? 39 | * What is HTTP header? 40 | * What is HTTP body? 41 | * What is HTTP query string? 42 | 43 | * SSL — http://info.ssl.com/article.aspx?id=10241 , http://en.wikipedia.org/wiki/Transport_Layer_Security 44 | *Time : 20 min* 45 | * how to import library — http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-(Java) 46 | *Time : 20 min* 47 | * send emails — http://www.tutorialspoint.com/java/java_sending_email.htm , http://commons.apache.org/proper/commons-email/userguide.html 48 | *Time : 40 min* 49 | 50 | *Bonus:* 51 | * http://en.wikipedia.org/wiki/SOLID_(object-oriented_design) 52 | *Time : 30 min* 53 | -------------------------------------------------------------------------------- /week3/1-Files-Paths-Streams/prereading.md: -------------------------------------------------------------------------------- 1 | *Always close streams* 2 | http://www.javapractices.com/topic/TopicAction.do;jsessionid=8DC1E976F93832427DBF51B275870889?Id=8 3 | 4 | *Time : 20 min* 5 | 6 | *try-with-resources recap* 7 | http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html 8 | 9 | *Q&A* 10 | * What is Autoclosable? 11 | * Can try-with-resources be used with more than one resource? 12 | 13 | *Time : 30 min* 14 | 15 | *Buffered reading from File - java* 16 | http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/ 17 | 18 | *Time : 15 min* 19 | 20 | *Buffered writing in File - java* 21 | http://www.mkyong.com/java/how-to-write-to-file-in-java-bufferedwriter-example/ 22 | 23 | *Time : 15 min* 24 | 25 | *Class/Interface Index in java.io* 26 | http://docs.oracle.com/javase/7/docs/api/java/io/package-tree.html 27 | 28 | *Time : 15 min* 29 | 30 | *Closeable's hierarchy (not quite, but well, sort of ...) in java* 31 | http://ttp.essex.ac.uk/images/examples/io_closeable/5.png 32 | 33 | *Time : 15 min* 34 | 35 | *IO trail @ Oracle* 36 | http://docs.oracle.com/javase/tutorial/essential/io/index.html 37 | 38 | *Article for all kinds of links in Windows* 39 | http://comptb.cects.com/overview-to-understanding-hard-links-junction-points-and-symbolic-links-in-windows/ 40 | 41 | *Q&A* 42 | * What is Decorator pattern in Java IO ? http://stackoverflow.com/questions/6366385/decorator-pattern-for-io 43 | * What is Stream? 44 | * What is Byte Stream? 45 | * What is Character Stream? 46 | * What is Buffered Stream? 47 | * What is StreamReader? How to use encoding in Streams? 48 | * What is Path? 49 | * Bonus: What is Glob? 50 | * What fincionality represents File in Java? 51 | * What is Scanner? 52 | * What is RandomAccessFile? 53 | * Bonus: What is filter streams? 54 | * Bonus: What is PrintStream and PrintWriter? 55 | * What kind of Links are there?//symbolic, hard 56 | 57 | *Time: 2H* 58 | -------------------------------------------------------------------------------- /Application/2-List-Duplicating-Files/README.md: -------------------------------------------------------------------------------- 1 | # Problem 2 - List Duplicating Files 2 | 3 | ## Description 4 | 5 | In a programming language of your choice, implement the following function/method: 6 | 7 | ``` 8 | listDuplicatingFiles(dir) 9 | ``` 10 | 11 | Return a collection of all the files in a given directory `dir`. 12 | 13 | When we say "all the files" we mean all the files...recursively. Meaning that the files contained in the subfolders all the way down should also be included. From those files, exclude the ones who are equal to previously discovered files. 14 | 15 | **By equal we mean files with equal contents**. We don't care about the timestamp or the file name. 16 | 17 | ## Examples 18 | Let's say that your current directory looks like this: 19 | ``` 20 | /root 21 | |__readme.md 22 | |__/examples 23 | |__test1.java 24 | |__test2.java 25 | |__/images 26 | |__walter_white.png 27 | |__witcher_3_wallpaper.png 28 | |__/assets 29 | |__witcher.png 30 | ``` 31 | 32 | In the above structure our root folder contains only one file - `readme.md`. 33 | We wish to traverse it to the bottom of the heirarchy, thus the list of all files our program should select is - `readme.md`, `test1.java`, `test2.java`, `walter_white.png`, `witcher_3_wallpaper.png`, `witcher.png`. 34 | And now for the filtering part. `witcher_3_wallpaper.png` and `witcher.png` reside in different directories and have different names, but their contents are the same. The result of the program should be: 35 | ``` 36 | [`readme.md`, `test1.java`, `test2.java`, `walter_white.png`, `witcher_3_wallpaper.png`] 37 | ``` 38 | or 39 | ``` 40 | [`readme.md`, `test1.java`, `test2.java`, `walter_white.png`, `witcher.png`] 41 | ``` 42 | It doesn't matter which file you choose to keep, as long as there are no duplicating ones in the final result 43 | 44 | ## Details 45 | - Check if the directory exists 46 | - And don't forget - locate the files in every level of the root directory and exclude the duplicating ones! 47 | -------------------------------------------------------------------------------- /week0/1-JavaPlatformIntroduction/agenda.md: -------------------------------------------------------------------------------- 1 | ### Agenda #1 ### 2 | - Представете се 3 | - Малко организационно: 4 | - как ще протече курса: 5 | - прочели сте вкъщи материала, който ще използваме днес, 6 | - тук разказваме и обобщаваме материала, 7 | - решаваме задачи и четем още материали тук 8 | - и накрая решавате още повече и четете материали за следващия път вкъщи. 9 | - Java - a little history 10 | + started as 'Oak' in 1991 => дъб 11 | + Created by Sun 12 | + renamed to 'java', due to large ammounts of coffee the team used in development 13 | + released 1995 14 | + James Gosling 15 | + Brian Goetz(threading), Tim Peierls(threading), Joshua Bloch(annotations, collections, try-with-resource), Doug Lea (threading), Mark Reinhold(module system), Alex Buckley(generics), Neal Gafter(javac) (http://enos.itcollege.ee/~jpoial/allalaadimised/jdk7/jls7.pdf) 16 | + Java 17 | + Compile once, run everywhere 18 | #1 Development Platform 19 | 9 Millions Developers 20 | 1 Billion Java Downloads per Year 21 | 3 Billion devices run Java 22 | 97% of Enterprise Desktops run Java 23 | 100% of BLU-RAY Disc Players ship with Java 24 | http://www.javacodegeeks.com/2014/03/java-facts-to-blow-your-mind.html 25 | Jit Compiler in J2SE (Java 1.2) 26 | - Java, JRE, JVM, JDK 27 | - JSR, JCP 28 | - JSE, J2EE, J2ME 29 | - Sun, Oracle, Google 30 | - Cross-platform, compatibility 31 | - Javac 32 | - classpath 33 | 34 | //what IDE does for us 35 | C:\>javac -sourcepath src -classpath classes;lib\Banners.jar ^ 36 | src\farewells\GoodBye.java -d classes 37 | //source and target explanations 38 | C\:>javac -sodurce 1.6 -target 1.6 -bootclasspath C:\jdk1.6.0\lib\rt.jar ^ 39 | -extdirs "" OldCode.java 40 | 41 | //bootclasspath option 42 | 43 | - javap 44 | - the javadoc tool 45 | - jar format 46 | - Common VM Arguments 47 | 48 | - if possible - Welcome to Eclipse 49 | -Coding style format import 50 | -Import Preferences and Quick Keys setup (Refactor Menu, Create getter, setter) 51 | -Hello world from Eclipse 52 | -Packages,Eclipse Views 53 | 54 | 55 | -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/src/AtomicSet.java: -------------------------------------------------------------------------------- 1 | import java.net.URI; 2 | import java.util.Collection; 3 | import java.util.Collections; 4 | import java.util.HashSet; 5 | import java.util.Iterator; 6 | import java.util.Set; 7 | 8 | public class AtomicSet implements Set { 9 | 10 | @Override 11 | public String toString() { 12 | return handle.toString(); 13 | } 14 | 15 | private Set handle = 16 | Collections.synchronizedSet(new HashSet()); 17 | 18 | @Override 19 | public int size() { 20 | return handle.size(); 21 | } 22 | 23 | @Override 24 | public boolean isEmpty() { 25 | return handle.isEmpty(); 26 | } 27 | 28 | @Override 29 | public boolean contains(Object o) { 30 | synchronized (this) { 31 | boolean result = handle.contains(o); 32 | if (!result) { 33 | if (!(o instanceof URI)) { 34 | throw new RuntimeException(o.getClass().toString()); 35 | } 36 | if (!handle.add((URI) o)) { 37 | throw new RuntimeException("Element not added: " + o); 38 | }; 39 | } 40 | return result; 41 | } 42 | } 43 | 44 | @Override 45 | public Iterator iterator() { 46 | return handle.iterator(); 47 | } 48 | 49 | @Override 50 | public Object[] toArray() { 51 | return handle.toArray(); 52 | } 53 | 54 | @Override 55 | public T[] toArray(T[] a) { 56 | return handle.toArray(a); 57 | } 58 | 59 | @Override 60 | public boolean add(URI e) { 61 | return handle.add(e); 62 | } 63 | 64 | @Override 65 | public boolean remove(Object o) { 66 | return handle.remove(o); 67 | } 68 | 69 | @Override 70 | public boolean containsAll(Collection c) { 71 | return handle.containsAll(c); 72 | } 73 | 74 | @Override 75 | public boolean addAll(Collection c) { 76 | return handle.addAll(c); 77 | } 78 | 79 | @Override 80 | public boolean retainAll(Collection c) { 81 | return handle.retainAll(c); 82 | } 83 | 84 | @Override 85 | public boolean removeAll(Collection c) { 86 | return handle.removeAll(c); 87 | } 88 | 89 | @Override 90 | public void clear() { 91 | handle.clear(); 92 | } 93 | 94 | } 95 | -------------------------------------------------------------------------------- /week4/1-Libraries-JSON-HTTPClient/README.md: -------------------------------------------------------------------------------- 1 | ### 1. Send an email 2 | 3 | Send an email to someone with subject and some text. Add an attachment to mail. [here](http://d3dsacqprgcsqh.cloudfront.net/photo/azbW3zq_460sa_v1.gif) 4 | 5 | Integrate and use the apache commons-email library from http://commons.apache.org/proper/commons-email/userguide.html 6 | 7 | Note: The commons-email library depends on the javax.mail library, which you should download from somewhere. 8 | 9 | If you are using gmail's smtp beware : 10 | https://support.google.com/mail/answer/14257 11 | ``` 12 | email.setAuthenticator(new DefaultAuthenticator("username", "password")); 13 | email.setSSLOnConnect(true); 14 | email.setDebug(true); 15 | ``` 16 | 17 | ### 2. JToaster 18 | 19 | Ivan stays a lot on his computer. His mother is afraid it will spoil his vision. 20 | As you know very well, you should take a break of at least 5 minutes (actually, it should be 15, but this *might* be outdated). 21 | 22 | Help Ivan maintain his eagle-like vision. Write a program that shows a notification saying 'Get a little rest, will you?' (or a message of your choosing :D) 23 | 24 | Use the incredibly-complex JToaster library. Download it from http://jtoaster.sourceforge.net/ 25 | Use the methods `showToaster`, `setToasterWidth`, `setToasterHeight`, `setToasterIcon`, `setToasterColor`, `setBackgroundImage`, `setStep`, etc. to customize and make the coolest toaster you can imagine. Also, set a nice background, something like 26 | 27 | *hint*: 28 | ``` 29 | Toaster toasterManager = new Toaster(); 30 | toasterManager.showToaster( "JToaster Hello World!" ); 31 | ``` 32 | 33 | ![This dog] (http://www.mnn.com/sites/default/files/editorial/Corgeek.jpg) 34 | 35 | ### 3. Make a QuickCodeInspector desktop application 36 | 37 | Ever needed to really, really quickly inpsect some code? 38 | Here is a one cool syntax highlighter for java https://code.google.com/p/java-syntax-highlighter/ 39 | 40 | 1) Create a program, that receives a file path as a command-line argument (args[0] in `main(String[] args)`) 41 | 2) For the File given, launch a syntax highlighter windows as the example in the link above. 42 | -------------------------------------------------------------------------------- /week6/1-Multithreading/MultiWebCrawler/com/hackbulgaria/corejava/crawler/no/AtomicSet.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava.crawler.no; 2 | 3 | import java.net.URI; 4 | import java.util.Collection; 5 | import java.util.Collections; 6 | import java.util.HashSet; 7 | import java.util.Iterator; 8 | import java.util.Set; 9 | 10 | public class AtomicSet implements Set { 11 | 12 | @Override 13 | public String toString() { 14 | return handle.toString(); 15 | } 16 | 17 | private Set handle = 18 | Collections.synchronizedSet(new HashSet()); 19 | 20 | @Override 21 | public int size() { 22 | return handle.size(); 23 | } 24 | 25 | @Override 26 | public boolean isEmpty() { 27 | return handle.isEmpty(); 28 | } 29 | 30 | @Override 31 | public boolean contains(Object o) { 32 | synchronized (this) { 33 | boolean result = handle.contains(o); 34 | if (!result) { 35 | if (!(o instanceof URI)) { 36 | throw new RuntimeException(o.getClass().toString()); 37 | } 38 | if (!handle.add((URI) o)) { 39 | throw new RuntimeException("Element not added: " + o); 40 | }; 41 | } 42 | return result; 43 | } 44 | } 45 | 46 | @Override 47 | public Iterator iterator() { 48 | return handle.iterator(); 49 | } 50 | 51 | @Override 52 | public Object[] toArray() { 53 | return handle.toArray(); 54 | } 55 | 56 | @Override 57 | public T[] toArray(T[] a) { 58 | return handle.toArray(a); 59 | } 60 | 61 | @Override 62 | public boolean add(URI e) { 63 | return handle.add(e); 64 | } 65 | 66 | @Override 67 | public boolean remove(Object o) { 68 | return handle.remove(o); 69 | } 70 | 71 | @Override 72 | public boolean containsAll(Collection c) { 73 | return handle.containsAll(c); 74 | } 75 | 76 | @Override 77 | public boolean addAll(Collection c) { 78 | return handle.addAll(c); 79 | } 80 | 81 | @Override 82 | public boolean retainAll(Collection c) { 83 | return handle.retainAll(c); 84 | } 85 | 86 | @Override 87 | public boolean removeAll(Collection c) { 88 | return handle.removeAll(c); 89 | } 90 | 91 | @Override 92 | public void clear() { 93 | handle.clear(); 94 | } 95 | 96 | } 97 | -------------------------------------------------------------------------------- /week7/1-Java8/Java8Problems/src/com/hackbulgaria/corejava2/StudentOperations.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava2; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | import com.hackbulgaria.corejava2.data.Gender; 7 | import com.hackbulgaria.corejava2.data.Student; 8 | 9 | public interface StudentOperations { 10 | 11 | public double getAverageMark(); 12 | 13 | public List getAllPassing(); 14 | 15 | public List getAllFailing(); 16 | 17 | /** 18 | * Split the list of students into two groups - a group with equal or higher marks than the given `splitMark` ('true') 19 | * and the one with lower marks than the given `splitMark` ('false') 20 | * @return 21 | */ 22 | public Map> splitStudentsByMarks(float splitMark); 23 | 24 | public List orderByMarkDescending(); 25 | 26 | public List orderByMarkAscending(); 27 | /** 28 | * @return clusterize the students by their marks and return all the 29 | * students with the highest mark. 30 | * 31 | * Example: If Georgi and Ivo have 32 | * 6.0, but Radoslav has 5.0, you have to return Georgi and Ivo, but 33 | * not Radoslav 34 | */ 35 | public List getStudentsWithLowestMarks(); 36 | 37 | public List getStudentsWithHighestMarks(); 38 | 39 | /** 40 | * @return a map consisting of a List of marks per a given age, e.g. 41 | * result.get(20) would return the list of all the marks of the 42 | * students that are 20 years old. 43 | */ 44 | public Map> getMarksDistributionByAge(); 45 | 46 | public Map getAverageMarkByGender(); 47 | 48 | /** 49 | * example: Return a map that contains 50 | * 4.5 -> 3 times 51 | * 4.0 -> 2 times. 52 | * 2.0 -> 8 times. 53 | * @return 54 | */ 55 | public Map getMarksDistribution(); 56 | 57 | /** 58 | * @return "first@email.com, second@email.com, third@email.com..." 59 | */ 60 | public String getEmailToHeader(); 61 | 62 | 63 | /** 64 | * Split the students by their gender, and then partition them by their age 65 | */ 66 | public Map>> splitStudentMarksByGenderAndThenByAge(); 67 | } 68 | -------------------------------------------------------------------------------- /week6/2-Multithreading/WaitNotifyMechanism/src/com/hackbulgaria/corejava/WaitNotifyMechanism.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | public class WaitNotifyMechanism { 4 | public static long startTime = System.currentTimeMillis(); 5 | public static Integer counter = 0; 6 | public static final Object monitor = new Object(); 7 | private static int turn = 0; 8 | 9 | public static void increment() { 10 | System.out.println("Incrementing from Thread : " + Thread.currentThread().getName() + " " + counter ); 11 | counter++; 12 | } 13 | 14 | public static void main(String[] args) throws InterruptedException { 15 | Thread t1 = new Thread() { 16 | public void run() { 17 | for (int i = 0; i < 2_000_000; i++) { 18 | synchronized (monitor) { 19 | while (turn != 1) { 20 | try { 21 | monitor.wait(); 22 | } catch (InterruptedException e) { 23 | e.printStackTrace(); 24 | } 25 | 26 | } 27 | increment(); 28 | 29 | turn = (turn + 1) % 2; 30 | monitor.notify(); 31 | } 32 | 33 | } 34 | } 35 | }; 36 | Thread t2 = new Thread() { 37 | 38 | public void run() { 39 | for (int i = 0; i < 2_000_000; i++) { 40 | synchronized (monitor) { 41 | while (turn != 0) { 42 | try { 43 | monitor.wait(); 44 | } catch (InterruptedException e) { 45 | e.printStackTrace(); 46 | } 47 | } 48 | 49 | increment(); 50 | 51 | turn = (turn + 1) % 2; 52 | monitor.notify(); 53 | } 54 | } 55 | } 56 | }; 57 | t1.setName("T1"); 58 | t2.setName("T2"); 59 | t1.start(); 60 | t2.start(); 61 | t1.join(); 62 | t2.join(); 63 | System.out.println(counter); 64 | System.out.println(System.currentTimeMillis() - startTime); 65 | } 66 | } -------------------------------------------------------------------------------- /week5/1-Servlets-Tomcat/HelloRest.java: -------------------------------------------------------------------------------- 1 | package test; 2 | 3 | import java.io.DataOutputStream; 4 | import java.io.IOException; 5 | import java.io.OutputStream; 6 | import java.lang.annotation.Annotation; 7 | import java.lang.reflect.Type; 8 | import java.util.Date; 9 | 10 | import javax.ws.rs.GET; 11 | import javax.ws.rs.POST; 12 | import javax.ws.rs.Path; 13 | import javax.ws.rs.Produces; 14 | import javax.ws.rs.WebApplicationException; 15 | import javax.ws.rs.core.MediaType; 16 | import javax.ws.rs.core.MultivaluedMap; 17 | import javax.ws.rs.ext.MessageBodyWriter; 18 | import javax.ws.rs.ext.Provider; 19 | 20 | @Path("/hello") 21 | public class HelloRest { 22 | @GET 23 | public String hello() { 24 | return "Hello world @ " + new Date().toString(); 25 | } 26 | 27 | @POST 28 | public String helloPost() { 29 | return "Hello world post @ " + new Date().toString(); 30 | } 31 | 32 | @Path("/student") 33 | @GET 34 | @Produces("application/json") 35 | public Student getStudent() { 36 | return new Student("ivan", "ivanov"); 37 | } 38 | } 39 | 40 | @Provider 41 | @Produces("application/json") 42 | class JSONBodyWriter implements MessageBodyWriter { 43 | 44 | @Override 45 | public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { 46 | System.out.println("isWriteable called..."); 47 | return type == Student.class; 48 | } 49 | 50 | @Override 51 | public long getSize(Student myBool, Class type, Type genericType, 52 | Annotation[] annotations, MediaType mediaType) { 53 | // deprecated by JAX-RS 2.0 and ignored by Jersey runtime 54 | return 0; 55 | } 56 | 57 | 58 | @Override 59 | public void writeTo(Student st, 60 | Class type, 61 | Type genericType, 62 | Annotation[] annotations, 63 | MediaType mediaType, 64 | MultivaluedMap httpHeaders, 65 | OutputStream entityStream) 66 | throws IOException, WebApplicationException { 67 | 68 | StringBuilder sb = new StringBuilder(); 69 | sb.append("{\"fn\":\"").append(st.getFn()).append("\",\"ln\":\"").append(st.getLn()).append("\"}"); 70 | DataOutputStream dos = new DataOutputStream(entityStream); 71 | dos.writeUTF(sb.toString()); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /week0/2-TypesArraysStrings/prereading.md: -------------------------------------------------------------------------------- 1 | ###Recap of what we did the last time:### 2 | 3 | The 'git/github'/recap article (if you are not familiar with git/github) 4 | https://github.com/HackBulgaria/Programming101/blob/master/week1/git.md 5 | 6 | 7 | JRE, JDK, JVM (if you still don't know what they are) 8 | http://stackoverflow.com/questions/11547458/what-is-differences-between-jvm-jdk-jre-openjdk 9 | 10 | Path and classpath (if you are having trouble differentiating those two) 11 | http://docs.oracle.com/javase/tutorial/essential/environment/paths.html 12 | 13 | On debugging with Eclipse 14 | https://blog.codecentric.de/en/2013/04/again-10-tips-on-java-debugging-with-eclipse/ 15 | 16 | Primitive Data types in Java 17 | http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html 18 | 19 | Arrays in Java 20 | http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html 21 | http://stackoverflow.com/questions/2267790/how-are-arrays-implemented-in-java 22 | http://docs.oracle.com/javase/specs/jls/se8/html/jls-10.html#jls-10.8 23 | 24 | Some Q&A 25 | http://docs.oracle.com/javase/tutorial/java/nutsandbolts/QandE/questions_variables.html 26 | 27 | Operators 28 | http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html 29 | http://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html 30 | 31 | On Control flow - if, for, while, do-while, switch 32 | http://docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html 33 | 34 | 35 | 36 | ###For our second meeting : ) ### 37 | 38 | 39 | Wrapper Classes 40 | http://en.wikipedia.org/wiki/Primitive_wrapper_class 41 | 42 | On autoboxing and unboxing in Java 43 | http://javarevisited.blogspot.com/2012/07/auto-boxing-and-unboxing-in-java-be.html 44 | 45 | On instanceof and isAssignableFrom 46 | http://stackoverflow.com/questions/496928/what-is-the-difference-between-instanceof-and-class-isassignablefrom 47 | 48 | Most important stuff on String 49 | http://javarevisited.blogspot.com/2013/07/java-string-tutorial-and-examples-beginners-programming.html 50 | 51 | StringBuilder vs StringBuffer? 52 | http://javarevisited.blogspot.com/2011/07/string-vs-stringbuffer-vs-stringbuilder.html 53 | 54 | On Unicode (Joel on Software) 55 | http://www.joelonsoftware.com/articles/Unicode.html 56 | 57 | On String interning 58 | http://en.wikipedia.org/wiki/String_interning 59 | http://java-performance.info/string-intern-in-java-6-7-8/ 60 | 61 | Introduction to JUnit 62 | http://courses.cs.washington.edu/courses/cse143/11wi/eclipse-tutorial/junit.shtml -------------------------------------------------------------------------------- /week5/1-Servlets-Tomcat/README.md: -------------------------------------------------------------------------------- 1 | ### 1. Servlet/HelloWorld 2 | - Create an Http Servlet. Override the `doGet` method, and write 'HelloWorld!' to the response's outputStream. 3 | - Run your application on Eclipse ('Run as Server'). 4 | - See your own message at 'localhost:8080/YourAppName/YourServletName' 5 | - Make your servlet respond at 'localhost:8080/YourAppName/' (Edit the @WebServlet annotation path to '/') 6 | - See that your servlet now responds at 'localhost:8080/YourAppName/' 7 | - Now undo your change (restore the @WebServlet annotation path). 8 | - Right click on your project -> Java EE tools -> Generate Deployment descriptor stub. 9 | - - You will now have a 'web.xml' file. It is called a deployment descriptor. 10 | - - Edit the deployment descriptor, and add a first welcome-file tag pointing to 'YourServletName'. We want to register the servlet as a welcome page for your server :) 11 | - Check the 'html source code' returned by your servlet. You will see no HTML tags. Why? 12 | - Write an HTML response to your client. For instance `

Now that's a big title!

` 13 | 14 | Congratulations. You've just witnessed what ASP/JSP/PHP is all about. We are not going to do any of that ~~sh**~~ stuff. 15 | 16 | 17 | ### 2. Simple news agregator 18 | Do you know what an [RSS](http://en.wikipedia.org/wiki/RSS) is? 19 | It is a simple format for describing **content** (just the content, and not it's visualization). It is an XML-based format. 20 | 21 | [This is an RSS](http://www.sportal.bg/uploads/rss_category_2.xml) 22 | Your task is simple - create a service (using just a servlet), that shows the latest news **in bulgarian** in the following categories: 23 | - General/Bulgaria 24 | - Technology 25 | - Sport 26 | 27 | Write the ~~ugliest~~ simplest html output you possibly can. 28 | Something like is completely OK. 29 | ![this](http://i.imgur.com/uZvmOlRl.jpg) 30 | 31 | 32 | If you don't know HTML, it's okay, just check http://www.w3schools.com/html/html_basic.asp You'll learn a few tricks in no time. 33 | 34 | Hints: 35 | - Pick some RSS feed links from popular news websites. Dnevnik.bg, sportal.bg, etc have RSS feed functionality. Maybe even FMI had one? 36 | - Do not parse the XML yourself. There are libraries for that, use the ones given in this github folder (the ROME library). 37 | - Add both jars in the WEB-INF/lib folder. Don't do anything after that, Eclipse will automatically add them to the project's build path. 38 | - Use this ROME tutorial: http://blog.manishchhabra.com/2011/10/rome-library-example-for-parsing-rss-and-atom-feeds/ 39 | 40 | 41 | ### 3. Simple JSON pretty printer service. 42 | Just look at the JSON at http://hackbulgaria.com/api/checkins . It is horrible - completely unreadable. What are the elements? What are the JSON objects? You cannot easily tell. 43 | 44 | - Deploy a servlet, that accepts a named "POST" parameter "json". 45 | - Read the json as a POST parameter given to the request (as a parameter from the `HttpServletRequest` via the `getParameter` method.) 46 | - Use google gson to pretty-print the json given. 47 | - See how to it here: http://stackoverflow.com/questions/4105795/pretty-print-json-in-java 48 | -------------------------------------------------------------------------------- /week6/1-Multithreading/WebCrawler/src/com/hackbulgaria/corejava/WebCrawler.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | import java.io.IOException; 4 | import java.net.MalformedURLException; 5 | import java.net.URI; 6 | import java.net.URISyntaxException; 7 | import java.util.ArrayList; 8 | import java.util.Collections; 9 | import java.util.HashSet; 10 | import java.util.List; 11 | import java.util.Set; 12 | import java.util.concurrent.ExecutionException; 13 | import java.util.regex.Matcher; 14 | import java.util.regex.Pattern; 15 | 16 | import org.apache.commons.io.IOUtil; 17 | import org.apache.http.HttpResponse; 18 | import org.apache.http.client.HttpClient; 19 | import org.apache.http.client.methods.HttpGet; 20 | import org.apache.http.client.utils.URIUtils; 21 | import org.apache.http.impl.client.DefaultHttpClient; 22 | 23 | public class WebCrawler { 24 | private final Set visitedUrls = Collections.synchronizedSet(new HashSet()); 25 | 26 | public URI crawl(URI currentLocation, final String needle) throws URISyntaxException, MalformedURLException, 27 | InterruptedException, ExecutionException { 28 | String urlContents = downloadContents(currentLocation); 29 | visitedUrls.add(currentLocation); 30 | 31 | if (urlContents.contains(needle)) { 32 | return currentLocation; 33 | } else { 34 | for (String link : getAllLinks(urlContents)) { 35 | final URI asUri = normalizeLink(currentLocation, link); 36 | if (!visitedUrls.contains(asUri) && isInsideDomain(currentLocation, asUri)) { 37 | URI result = crawl(asUri, needle); 38 | if (result != null) { 39 | return result; 40 | } 41 | } 42 | } 43 | } 44 | return null; 45 | } 46 | 47 | private static boolean isInsideDomain(URI currentLocation, URI asUrl) throws URISyntaxException { 48 | return currentLocation.getHost().equals(asUrl.getHost()); 49 | } 50 | 51 | private URI normalizeLink(URI currentLocation, String link) throws MalformedURLException, URISyntaxException { 52 | URI uri = new URI(link); 53 | if (uri.getScheme() != null && uri.getHost() != null) { 54 | return uri; 55 | } 56 | return URIUtils.resolve(currentLocation, uri); 57 | } 58 | 59 | private static String downloadContents(URI startLocation) throws URISyntaxException { 60 | HttpClient httpClient = new DefaultHttpClient(); 61 | System.out.println("Currently crawling : " + startLocation); 62 | HttpGet get = new HttpGet(startLocation); 63 | try { 64 | HttpResponse response = httpClient.execute(get); 65 | String contents = IOUtil.toString(response.getEntity().getContent()); 66 | return contents; 67 | } catch (IOException e) { 68 | e.printStackTrace(); 69 | // IO Error when connecting to the server, whatever, just return 70 | // empty contents 71 | return ""; 72 | } 73 | } 74 | 75 | private static List getAllLinks(String content) { 76 | ArrayList resultList = new ArrayList<>(); 77 | String regex = ""; 78 | Pattern pattern = Pattern.compile(regex); 79 | Matcher matcher = pattern.matcher(content); 80 | while (matcher.find()) { 81 | resultList.add(matcher.group(1)); 82 | } 83 | return resultList; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /week5/1-Servlets-Tomcat/pre.md: -------------------------------------------------------------------------------- 1 | *In short, what is a servlet?* 2 | http://stackoverflow.com/questions/7213541/what-is-java-servlet 3 | 4 | *This is how you create your first servlet* 5 | http://www.journaldev.com/1854/java-web-application-tutorial-for-beginners 6 | 7 | *If you want to learn more about servlets here is a short book (or an extended tutorial)* 8 | http://pdf.coreservlets.com/Servlet-Basics.pdf 9 | 10 | *And of course, Oracle's documentation on servlets __#tl;dr__* 11 | http://docs.oracle.com/javaee/6/tutorial/doc/bnafe.html 12 | 13 | *Eclipse EE* 14 | https://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/lunar 15 | 16 | *TomEE JAX-RS* 17 | http://www.apache.org/dyn/closer.cgi/tomee/tomee-1.7.1/apache-tomee-1.7.1-jaxrs.zip 18 | 19 | ### Stop the Tomcat instance launched from Eclipse 20 | Shutdown Eclipse's use of tomcat. We will not let Eclipse manage tomcat for us this time. 21 | Forget Run as -> Server. We won't be using that again. 22 | 23 | If you do not have running Tomcat instance from Eclipse, you don't have to do anything. 24 | Else, just click on the red button in the'Servers' view. 25 | 26 | (If you've just launched Eclipse, you don't have to do anything) 27 | 28 | ### Check out tomcat's installation directory 29 | -Go to your tomcat installation directory. For me, it was `/home/georgi/Dev/tomcat/` 30 | -Do an `ls` and notify me when you get there. 31 | 32 | - `tomcat/bin` => All the binaries for tomcat. If you need to start or stop tomcat, there are the binaries you need. 33 | - `tomcat/conf` => All the configuration files for tomcat. tomcat-user.xml and others 34 | - `tomcat/webapps` => The most important folder of all. You must delpoy your web applications here. 'Deploying' means copying one .war file to your webapps dir. 35 | 36 | One web application = one .war file. It's like a .jar file, but it means 'webarchive' (.war). 37 | 38 | -Start your tomcat using `startup.sh` or `startup.bat` in the `/bin/` folder. 39 | 40 | -Go to http://localhost:8080 . Do you see the cat? You need to see the cat. 41 | -Now take a look at http://localhost:8080/examples/ 42 | 43 | -Take a note - if you let eclipse manage your tomcat, you won't see neither a cat nor examples. 44 | 45 | -Edit the tomcat-users.xml file in `your-tomcat-dir/conf`. See the commented lines and add *2 roles* one with a `rolеname="manager"` and the other with a `rolеname="manager-gui"`. 46 | -Create a user with username "a" and password "a" with the role of "manager-gui" 47 | -Create a user with username "test" and password "test" with the role of "manager" 48 | -Save tomcat-users.xml 49 | 50 | -Open http://localhost:8080/manager . Authenticate with "a"/"a". 51 | -What you are seeing now is something called the "Tomcat Manager". Here you can see what applications do you have deployed, which of them are running, etc. If you have any problems with web applications, that's the place to check first: 52 | -1) Your web application should be DEPLOYED 53 | -2) Your web application should be RUNNING 54 | 55 | ### In Eclipse 56 | - Create your Dynamic Web project. Name your project 'NewsService'. 57 | - Create a servlet echoing "Hello World!" to the writer in the `doGet` method 58 | - Add apache's commons-io library. 59 | 60 | -------------------------------------------------------------------------------- /week1/1-DebuggingFun/DebuggingFun/src/com/hackbulgaria/corejava/Utils.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | import java.io.File; 4 | import java.io.FileWriter; 5 | import java.io.IOException; 6 | import java.io.Writer; 7 | import java.lang.Thread.State; 8 | import java.net.MalformedURLException; 9 | import java.net.URL; 10 | import java.net.URLClassLoader; 11 | 12 | import javax.tools.JavaCompiler; 13 | import javax.tools.ToolProvider; 14 | 15 | import org.apache.commons.io.FileUtils; 16 | 17 | public class Utils { 18 | public static String reverseMe(String argument) { 19 | return new StringBuilder(argument).reverse().toString(); 20 | } 21 | 22 | public static boolean isPalindrome(String argument) { 23 | return argument.equals(reverseMe(argument)); 24 | } 25 | 26 | public static boolean isPalindrome(long number) { 27 | return isPalindrome(String.valueOf(number)); 28 | } 29 | 30 | public static void killMeIfIGetStuck() { 31 | final Thread threadToKill = Thread.currentThread(); 32 | new Thread(new Runnable() { 33 | 34 | @Override 35 | public void run() { 36 | try { 37 | Thread.sleep(2000); 38 | if (threadToKill.getState().equals(State.RUNNABLE) && "binarySearch".equals(threadToKill.getStackTrace()[0].getMethodName())) { 39 | 40 | // every time you do this Barekov gets another vote! 41 | threadToKill.stop(); 42 | } 43 | } catch (final InterruptedException e) { 44 | e.printStackTrace(); 45 | } 46 | } 47 | }).start(); 48 | } 49 | 50 | 51 | 52 | public static Class eval(Code code, String fileName) { 53 | File root = new File(isWindows()? "C:\\" : "/tmp/java-fun/"); 54 | File sourceFile = new File(root, fileName + ".java"); 55 | root.mkdirs(); 56 | 57 | try { 58 | FileUtils.write(sourceFile, code.wrappedCode); 59 | } catch (IOException e) { 60 | e.printStackTrace(); 61 | } 62 | 63 | JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler(); 64 | javaCompiler.run(null, null, null, sourceFile.getPath()); 65 | 66 | URLClassLoader urlClassLoader = null; 67 | try { 68 | urlClassLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() }); 69 | } catch (MalformedURLException e1) { 70 | e1.printStackTrace(); 71 | } 72 | try { 73 | return Class.forName(fileName, true, urlClassLoader); 74 | } catch (ClassNotFoundException e) { 75 | e.printStackTrace(); 76 | } 77 | return null; 78 | } 79 | 80 | private static boolean isWindows() { 81 | return System.getProperty("os.name").toLowerCase().contains("win"); 82 | } 83 | 84 | public static class Code { 85 | private String wrappedCode; 86 | 87 | public Code(String code){ 88 | this.wrappedCode = "public class Eval { static { " + code + " } } "; 89 | } 90 | 91 | @Override 92 | public String toString() { 93 | return wrappedCode + super.toString(); 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /week6/1-Multithreading/README.md: -------------------------------------------------------------------------------- 1 | ### A demonstration of a race condition 2 | Create a project 'Threads'. 3 | 4 | Create a static variable `counter`. 5 | Create two threads - A and B. 6 | In their `run()` methods just increment the shared variable 2_000_000 times. 7 | 8 | Start the two threads, join them, and print out `counter`. What happens? Why? 9 | Print out the time needed. 10 | 11 | ##### Introduce critical blocks 12 | Now wrap the incrementing in a synchronized block in each thread. (They should be **synchronized on the same monitor**). 13 | First, wrap the whole `for` statements in a synchronized blocks. 14 | 15 | See the result is now correct, and observe the minor performance penalty. 16 | 17 | Now, move the synochronized block `inside` the `for` statements. 18 | Notice the increased performance penalty. 19 | Experiment different ways to write it and see what is the behavior. 20 | 21 | ##### Replace the synchronized blocks with a call to a synchronized method increment() 22 | 23 | ##### Replace the synchronized stuff with an AtomicInteger. Notice the performance penalty! 24 | 25 | ##### Replace the Atomic Integer with wait/notify + mutex variable mechanism 26 | The scenario we want is the following: 27 | - Thread A obtains the mutex (`wait()`s until the mutex is available) 28 | - Works (increments the integer) 29 | - Then calls `notify` on the monitor 30 | - Which fires the Thread B, which does the same 31 | 32 | 33 | ### Implement a simple blocking queue. 34 | A blocking queue is just like a regular queue, with the difference that if someone calls `poll()` and the queue is empty, the call is blocked until somebody adds an element to the queue. After an element is added, the caller (the one who called `poll()`) gets unblocked and the `poll()` call returns. 35 | 36 | ### Bonus: 37 | Introduce classical very common interview scenario *Producer - Consumer problem*. Create several threads (Producers) that only produce `add(E e)` in your queue and several threads (Consumers) that only consume `poll()` from your queue. Your blocking queue should have a max size. When a max size is reached all producers are halted until some object have been consumed. 38 | 39 | 40 | 41 | ### Paralel minimal point calculations 42 | 43 | Create a static method `generatePoints()` which returns a `List` - `create your Point impl (with maybe different implementations)` 44 | Implement it, generating a 100 000 points (in java that is written `100_000`) points with random coordinates - ranging from 0 to 10_000. 45 | 46 | Now, for each of those points, I'd like you to find it's nearest point. Do this in a method `Map getNearestPoints(List generatedPoints)` 47 | 48 | It takes a while. By calculations, it should take like lots of seconds to complete (depending on your CPU speed). 49 | 50 | Now introduce some multithreading to speed it up. 51 | Declare and implement a method `doCalculations(List inPoints, int indexFrom, int indexTo, Map outMap)`. 52 | Move calculations logic from `getNearestPoints` to `doCalculations`, but work strictly from `indexFrom`, to `indexTo`. 53 | 54 | Now in `getNearestPoints(List generatedPoints)` method, start two Threads that call `doCalculations`, in their run methods, one from 0 to half of the elements, the other from half of the elements to the last of them. 55 | 56 | Measure speedup between the two implementations (See `System.currentTimeMillis()`). 57 | 58 | Introduce a third and forth thread. Does your implementation go faster? 59 | 60 | Think how to generalize the number of threads and how to implement it. 61 | -------------------------------------------------------------------------------- /week4/2-REST/README.md: -------------------------------------------------------------------------------- 1 | ### 1. Download a file with java 2 | Using only URL and the stream classes, download this photo: http://d3dsacqprgcsqh.cloudfront.net/photo/aozrdx0_700b.jpg to a location of your choosing 3 | 4 | ##### Now accept files from the command line and label your program the 'java wget'. Woohoo! 5 | 6 | ### 2. Make a simple website crawler 7 | Have you grown tiiiiiiired of looking for stuff on websites that simply seems is not in the navigation menu at all? 8 | You grow tired of that... and suddenly, baaaam! Someone skypes you the link. It was there, how could I have not seen it. 9 | 10 | 11 | Today, we will put an end to that. 12 | 13 | Write a simple web crawler, that is receiving a URL as a command line parameter and a "needle" to search for. 14 | Needle is text, usually a sentence. 15 | 16 | What your crawler should do is simple 17 | - GET the contents of the URL received 18 | - Check if the contents contain "needle" 19 | - If they do, output the URL and exit 20 | - If they don't, **get all the links** from the URL given and repeat for every link. 21 | 22 | Hints/tips: 23 | - **Don't go out of the website's scope** - if a link in `abv.bg` points to google, well, don't follow google, please... 24 | - **Don't visit the same URL twice** 25 | - **Use regular expressions** for getting links. If you are unfamiliar with them, use the following method: 26 | ```java 27 | private static List getAllLinks(String content) { 28 | ArrayList resultList = new ArrayList<>(); 29 | String regex = ""; 30 | Pattern pattern = Pattern.compile(regex); 31 | Matcher matcher = pattern.matcher(content); 32 | while (matcher.find()) { 33 | resultList.add(matcher.group(1)); 34 | } 35 | return resultList; 36 | } 37 | ``` 38 | - **If you are not comfortable with even using something as ugly as regular expressions, you can do it with regular string matching. It will be harder though :(** 39 | - Use small websites for testing. For example, http://ebusiness.free.bg is one site you can use. It has very, very few links. (Search for the word 'Револвираща'.) 40 | 41 | ### 3. Get/print all the people that have signed for more than 1 course at Hack Bulgaria. 42 | Some people have signed for Core Java. 43 | Some people have signed for Front-end Javascript. 44 | Some people have signed for Angular-JS. 45 | 46 | They are people that have signed for more than one course. 47 | Using the https://hackbulgaria.com/api/students/ API, the [Jettison library](http://jettison.codehaus.org/) and [Apache HttpClient](http://hc.apache.org/httpclient-3.x/tutorial.html), consume the REST service given and print out all the people, who have signed for more that 1 course. 48 | 49 | 50 | ##### Addendum: Print out the people with the most visits. 51 | See, whenever you visit HackBulgaria and use our WiFi, your MAC addresses get logged. If you have 'filled the forms' when registering at the HackBulgaria website, you can now see who has been coming and who hasn't been coming to the lectures. 52 | 53 | ``` 54 | {"date": "2014-06-05", "student_id": 35, "student_courses": [{"group": 1, "name": "Frontend JavaScript"}], "student_name": "Светимир Игнатов"} 55 | ``` 56 | 57 | Using https://hackbulgaria.com/api/checkins/, the [Jettison library](http://jettison.codehaus.org/) and [Apache HttpClient](http://hc.apache.org/httpclient-3.x/tutorial.html), consume the REST service given and print out pairs of String-Integer, where the key (String) is the name of a Person, and the value (Integer) is the number of times he was at HackBulgaria. Sort the pairs when printing - people with more checkins should come before people with less checkins. 58 | 59 | Hint : At present 27/04/2015 the site of hackbulgaria uses TLSv1.2 wih AES_256_CBC with SHA1 for message authentication and EDCHE_RSA for key exchange mechanism. In short this is not supported by default from the java. Here is a [link](http://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html#SunJCEProvider) for the curious. 60 | This is easy to fix however. 61 | Step 1: Download [Java Cryptography Extension (JCE)](http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html) 62 | Step 2: Locate your jre. Replace 2 jars (local_policy.jar и US_export_policy.jar) in jre\lib\security with the new from JCE. 63 | Step 3: Run [this code](http://pastebin.com/WsPY7u2M) and see if TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is in the enabled section of the output. 64 | -------------------------------------------------------------------------------- /week0/2-TypesArraysStrings/Project1/src/com/hackbulgaria/corejava/Problems2Impl.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | public class Problems2Impl implements Problems2 { 4 | 5 | @Override 6 | public boolean isOdd(int number) { 7 | return false; 8 | } 9 | 10 | @Override 11 | public boolean isPrime(int number) { 12 | // TODO Auto-generated method stub 13 | return false; 14 | } 15 | 16 | @Override 17 | public int min(int... array) { 18 | // TODO Auto-generated method stub 19 | return 0; 20 | } 21 | 22 | @Override 23 | public int kthMin(int k, int[] array) { 24 | // TODO Auto-generated method stub 25 | return 0; 26 | } 27 | 28 | @Override 29 | public float getAverage(int[] array) { 30 | // TODO Auto-generated method stub 31 | return 0; 32 | } 33 | 34 | @Override 35 | public long getSmallestMultiple(int upperBound) { 36 | // TODO Auto-generated method stub 37 | return 0; 38 | } 39 | 40 | @Override 41 | public long getLargestPalindrome(long N) { 42 | // TODO Auto-generated method stub 43 | return 0; 44 | } 45 | 46 | @Override 47 | public int[] histogram(short[][] image) { 48 | // TODO Auto-generated method stub 49 | return null; 50 | } 51 | 52 | @Override 53 | public long doubleFac(int n) { 54 | // TODO Auto-generated method stub 55 | return 0; 56 | } 57 | 58 | @Override 59 | public long kthFac(int k, int n) { 60 | // TODO Auto-generated method stub 61 | return 0; 62 | } 63 | 64 | @Override 65 | public int getOddOccurrence(int[] array) { 66 | // TODO Auto-generated method stub 67 | return 0; 68 | } 69 | 70 | @Override 71 | public long pow(int a, int b) { 72 | // TODO Auto-generated method stub 73 | return 0; 74 | } 75 | 76 | @Override 77 | public long maximalScalarSum(int[] a, int[] b) { 78 | // TODO Auto-generated method stub 79 | return 0; 80 | } 81 | 82 | @Override 83 | public int maxSpan(int[] array) { 84 | // TODO Auto-generated method stub 85 | return 0; 86 | } 87 | 88 | @Override 89 | public boolean canBalance(int[] array) { 90 | // TODO Auto-generated method stub 91 | return false; 92 | } 93 | 94 | @Override 95 | public int[][] rescale(int[][] original, int newWidth, int newHeight) { 96 | // TODO Auto-generated method stub 97 | return null; 98 | } 99 | 100 | @Override 101 | public String reverseMe(String argument) { 102 | // TODO Auto-generated method stub 103 | return null; 104 | } 105 | 106 | @Override 107 | public String copyEveryChar(String input, int k) { 108 | // TODO Auto-generated method stub 109 | return null; 110 | } 111 | 112 | @Override 113 | public String reverseEveryWord(String arg) { 114 | // TODO Auto-generated method stub 115 | return null; 116 | } 117 | 118 | @Override 119 | public boolean isPalindrome(String argument) { 120 | // TODO Auto-generated method stub 121 | return false; 122 | } 123 | 124 | @Override 125 | public boolean isPalindrome(int number) { 126 | // TODO Auto-generated method stub 127 | return false; 128 | } 129 | 130 | @Override 131 | public int getPalindromeLength(String input) { 132 | // TODO Auto-generated method stub 133 | return 0; 134 | } 135 | 136 | @Override 137 | public int countOcurrences(String needle, String haystack) { 138 | // TODO Auto-generated method stub 139 | return 0; 140 | } 141 | 142 | @Override 143 | public String decodeURL(String input) { 144 | // TODO Auto-generated method stub 145 | return null; 146 | } 147 | 148 | @Override 149 | public int sumOfNumbers(String input) { 150 | // TODO Auto-generated method stub 151 | return 0; 152 | } 153 | 154 | @Override 155 | public boolean areAnagrams(String A, String B) { 156 | // TODO Auto-generated method stub 157 | return false; 158 | } 159 | 160 | @Override 161 | public boolean hasAnagramOf(String string, String string2) { 162 | // TODO Auto-generated method stub 163 | return false; 164 | } 165 | 166 | } 167 | -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/src/WebCrawler.java: -------------------------------------------------------------------------------- 1 | import java.io.IOException; 2 | import java.net.MalformedURLException; 3 | import java.net.URI; 4 | import java.net.URISyntaxException; 5 | import java.nio.charset.StandardCharsets; 6 | import java.util.Collections; 7 | import java.util.HashSet; 8 | import java.util.Set; 9 | import java.util.concurrent.ExecutionException; 10 | import java.util.regex.Matcher; 11 | import java.util.regex.Pattern; 12 | 13 | import org.apache.http.HttpResponse; 14 | import org.apache.http.client.HttpClient; 15 | import org.apache.http.client.methods.HttpGet; 16 | import org.apache.http.client.utils.URIUtils; 17 | import org.apache.http.impl.client.DefaultHttpClient; 18 | import org.apache.http.util.EntityUtils; 19 | 20 | public class WebCrawler { 21 | private final Set visitedUrls = Collections 22 | .synchronizedSet(new HashSet()); 23 | 24 | // private final Set finalResult = Collections.synchronizedSet(new 25 | // HashSet()); 26 | 27 | public Set crawl(URI currentLocation, final String needle) 28 | throws URISyntaxException, MalformedURLException, 29 | InterruptedException, ExecutionException { 30 | Set finalResult = Collections.synchronizedSet(new HashSet()); 31 | String urlContents = downloadContents(currentLocation); 32 | visitedUrls.add(currentLocation); 33 | 34 | if (urlContents.contains(needle)) { 35 | // return 36 | finalResult.add(currentLocation); 37 | System.out.println("found in " + currentLocation); 38 | } 39 | { 40 | Set allLinks = getAllLinks(urlContents); 41 | removeNotNeededLinks(allLinks); 42 | for (String link : allLinks) { 43 | final URI asUri = normalizeLink(currentLocation, link); 44 | if (asUri != null && !visitedUrls.contains(asUri) 45 | && isInsideDomain(currentLocation, asUri)) { 46 | Set result = crawl(asUri, needle); 47 | if (result != null) { 48 | finalResult.addAll(result); 49 | } 50 | } 51 | } 52 | } 53 | return finalResult; 54 | } 55 | 56 | private void removeNotNeededLinks(Set allLinks) { 57 | if (allLinks.contains("#")) { 58 | allLinks.remove("#"); 59 | } 60 | } 61 | 62 | private static boolean isInsideDomain(URI currentLocation, URI asUrl) 63 | throws URISyntaxException { 64 | return currentLocation.getHost().equals(asUrl.getHost()); 65 | } 66 | 67 | private URI normalizeLink(URI currentLocation, String link) 68 | throws MalformedURLException, URISyntaxException { 69 | URI uri = null; 70 | try { 71 | uri = new URI(link); 72 | } catch (URISyntaxException e) { 73 | System.out.println(e); 74 | return null; 75 | } 76 | 77 | if (uri.getScheme() != null && uri.getHost() != null) { 78 | return uri; 79 | } 80 | return URIUtils.resolve(currentLocation, uri); 81 | } 82 | 83 | private static String downloadContents(URI startLocation) 84 | throws URISyntaxException { 85 | HttpClient httpClient = new DefaultHttpClient(); 86 | System.out.println("Currently crawling : " + startLocation); 87 | HttpGet get = new HttpGet(startLocation); 88 | try { 89 | HttpResponse response = httpClient.execute(get); 90 | String contents = EntityUtils.toString(response.getEntity(), 91 | StandardCharsets.UTF_8); 92 | return contents; 93 | } catch (IOException e) { 94 | e.printStackTrace(); 95 | // IO Error when connecting to the server, whatever, just return 96 | // empty contents 97 | return ""; 98 | } finally { 99 | httpClient.getConnectionManager().shutdown(); 100 | } 101 | } 102 | 103 | private static Set getAllLinks(String content) { 104 | Set resultList = new HashSet<>(); 105 | // ArrayList resultList = new ArrayList<>(); 106 | String regex = ""; 107 | Pattern pattern = Pattern.compile(regex); 108 | Matcher matcher = pattern.matcher(content); 109 | while (matcher.find()) { 110 | resultList.add(matcher.group(1)); 111 | } 112 | return resultList; 113 | } 114 | 115 | private boolean testSharp(Set visitedUrls, URI uri) { 116 | boolean result = true; 117 | String url = uri.toString(); 118 | if (url.endsWith("#")) { 119 | url = url.substring(0, url.length() - 1); 120 | try { 121 | if (visitedUrls.contains(new URI(url))) { 122 | result = false; 123 | } 124 | } catch (URISyntaxException e) { 125 | // TODO Auto-generated catch block 126 | e.printStackTrace(); 127 | } 128 | if (result && url.endsWith("/")) { 129 | url = url.substring(0, url.length() - 1); 130 | try { 131 | if (visitedUrls.contains(new URI(url))) { 132 | result = false; 133 | } 134 | } catch (URISyntaxException e) { 135 | // TODO Auto-generated catch block 136 | e.printStackTrace(); 137 | } 138 | } 139 | } else { 140 | System.out.println(url); 141 | url += "#"; 142 | try { 143 | if (visitedUrls.contains(new URI(url))) { 144 | result = false; 145 | } 146 | } catch (URISyntaxException e) { 147 | e.printStackTrace(); 148 | } 149 | } 150 | // if (!result) 151 | // System.out.println("uri:" +uri +" "+visitedUrls); 152 | return result; 153 | } 154 | } -------------------------------------------------------------------------------- /week6/1-Multithreading/MultiWebCrawler/com/hackbulgaria/corejava/crawler/no/WebCrawler.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava.crawler.no; 2 | 3 | import java.io.IOException; 4 | import java.net.MalformedURLException; 5 | import java.net.URI; 6 | import java.net.URISyntaxException; 7 | import java.nio.charset.StandardCharsets; 8 | import java.util.Collections; 9 | import java.util.HashSet; 10 | import java.util.Set; 11 | import java.util.concurrent.ExecutionException; 12 | import java.util.regex.Matcher; 13 | import java.util.regex.Pattern; 14 | 15 | import org.apache.http.HttpResponse; 16 | import org.apache.http.client.HttpClient; 17 | import org.apache.http.client.methods.HttpGet; 18 | import org.apache.http.client.utils.URIUtils; 19 | import org.apache.http.impl.client.DefaultHttpClient; 20 | import org.apache.http.util.EntityUtils; 21 | 22 | public class WebCrawler { 23 | private final Set visitedUrls = Collections 24 | .synchronizedSet(new HashSet()); 25 | 26 | // private final Set finalResult = Collections.synchronizedSet(new 27 | // HashSet()); 28 | 29 | public Set crawl(URI currentLocation, final String needle) 30 | throws URISyntaxException, MalformedURLException, 31 | InterruptedException, ExecutionException { 32 | Set finalResult = Collections.synchronizedSet(new HashSet()); 33 | String urlContents = downloadContents(currentLocation); 34 | visitedUrls.add(currentLocation); 35 | 36 | if (urlContents.contains(needle)) { 37 | // return 38 | finalResult.add(currentLocation); 39 | System.out.println("found in " + currentLocation); 40 | } 41 | { 42 | Set allLinks = getAllLinks(urlContents); 43 | removeNotNeededLinks(allLinks); 44 | for (String link : allLinks) { 45 | final URI asUri = normalizeLink(currentLocation, link); 46 | if (asUri != null && !visitedUrls.contains(asUri) 47 | && isInsideDomain(currentLocation, asUri)) { 48 | Set result = crawl(asUri, needle); 49 | if (result != null) { 50 | finalResult.addAll(result); 51 | } 52 | } 53 | } 54 | } 55 | return finalResult; 56 | } 57 | 58 | private void removeNotNeededLinks(Set allLinks) { 59 | if (allLinks.contains("#")) { 60 | allLinks.remove("#"); 61 | } 62 | } 63 | 64 | private static boolean isInsideDomain(URI currentLocation, URI asUrl) 65 | throws URISyntaxException { 66 | return currentLocation.getHost().equals(asUrl.getHost()); 67 | } 68 | 69 | private URI normalizeLink(URI currentLocation, String link) 70 | throws MalformedURLException, URISyntaxException { 71 | URI uri = null; 72 | try { 73 | uri = new URI(link); 74 | } catch (URISyntaxException e) { 75 | System.out.println(e); 76 | return null; 77 | } 78 | 79 | if (uri.getScheme() != null && uri.getHost() != null) { 80 | return uri; 81 | } 82 | return URIUtils.resolve(currentLocation, uri); 83 | } 84 | 85 | private static String downloadContents(URI startLocation) 86 | throws URISyntaxException { 87 | HttpClient httpClient = new DefaultHttpClient(); 88 | System.out.println("Currently crawling : " + startLocation); 89 | HttpGet get = new HttpGet(startLocation); 90 | try { 91 | HttpResponse response = httpClient.execute(get); 92 | String contents = EntityUtils.toString(response.getEntity(), 93 | StandardCharsets.UTF_8); 94 | return contents; 95 | } catch (IOException e) { 96 | e.printStackTrace(); 97 | // IO Error when connecting to the server, whatever, just return 98 | // empty contents 99 | return ""; 100 | } finally { 101 | httpClient.getConnectionManager().shutdown(); 102 | } 103 | } 104 | 105 | private static Set getAllLinks(String content) { 106 | Set resultList = new HashSet<>(); 107 | // ArrayList resultList = new ArrayList<>(); 108 | String regex = ""; 109 | Pattern pattern = Pattern.compile(regex); 110 | Matcher matcher = pattern.matcher(content); 111 | while (matcher.find()) { 112 | resultList.add(matcher.group(1)); 113 | } 114 | return resultList; 115 | } 116 | 117 | private boolean testSharp(Set visitedUrls, URI uri) { 118 | boolean result = true; 119 | String url = uri.toString(); 120 | if (url.endsWith("#")) { 121 | url = url.substring(0, url.length() - 1); 122 | try { 123 | if (visitedUrls.contains(new URI(url))) { 124 | result = false; 125 | } 126 | } catch (URISyntaxException e) { 127 | // TODO Auto-generated catch block 128 | e.printStackTrace(); 129 | } 130 | if (result && url.endsWith("/")) { 131 | url = url.substring(0, url.length() - 1); 132 | try { 133 | if (visitedUrls.contains(new URI(url))) { 134 | result = false; 135 | } 136 | } catch (URISyntaxException e) { 137 | // TODO Auto-generated catch block 138 | e.printStackTrace(); 139 | } 140 | } 141 | } else { 142 | System.out.println(url); 143 | url += "#"; 144 | try { 145 | if (visitedUrls.contains(new URI(url))) { 146 | result = false; 147 | } 148 | } catch (URISyntaxException e) { 149 | e.printStackTrace(); 150 | } 151 | } 152 | // if (!result) 153 | // System.out.println("uri:" +uri +" "+visitedUrls); 154 | return result; 155 | } 156 | } -------------------------------------------------------------------------------- /week0/2-TypesArraysStrings/README.md: -------------------------------------------------------------------------------- 1 | ###1. Is it an odd number?### 2 | ```boolean isOdd(int n)``` 3 | Return whether n is an odd number 4 | 5 | ###2. Is N prime?### 6 | ```boolean isPrime(int N)``` 7 | 8 | ###3. Find the minimum element of an array### 9 | ```int min(int... array)``` 10 | 11 | ###4. Find the kth minimal element of an array### 12 | ```int kthMin(int k, int[] array)``` 13 | *There will be no duplicates in the array. If they are duplicates in the test, ignore them (my bad).* 14 | 15 | ###5. Find the average(средно аритметично) of the elements of an array### 16 | ```int getAverage(int[] array);``` 17 | 18 | ###6. Double factorial### 19 | ```long doubleFac(int n);``` 20 | return 21 | E.g. if n=3, => (3!)! = 6! = 720 22 | 23 | ###7. Kth factorial### 24 | ```long kthFac(int k, int n);``` 25 | Get the kthFactorial of n. k is guaranteed to be positive. 26 | *Bonus* no "helper" methods, no recursion :) 27 | 28 | ###8. Smallest multiple### 29 | ```long getSmallestMultiple(int upperBound);``` 30 | 31 | Find the smallest (positive) number, that can be divided by each of the numbers from 1 to *upperBound*. 32 | 33 | ###9. Find the largest integer palindrome number up to N### 34 | ```long getLargestPalindrome(long N);``` 35 | 36 | 1234321 is a palindrome. You are given a number => *N*. 37 | Find the largest number < N, that is a palindrome. 38 | 39 | *Bonus* do this without using Collections.sort 40 | 41 | ###10. Grayscale image histogram### 42 | ```int[] histogram(short[][] image)``` 43 | 44 | A histogram is a representation of distribution of some data. 45 | 46 | Here you receive a grayscale image matrix (*image*). Each of the matrix's values will be between 0 and 255. 47 | Return an array *result*, which is a histogram of *image* => the value of *result[i]* should be the ammount of times *i* is in the matrix *image*. 48 | 49 | ###11. Raise an integer to a power of another### 50 | ```long pow(int a, int b)``` 51 | 52 | Write a O(log(b)) solution. 53 | 54 | ###12. Find the only number, that occurs odd times in an array### 55 | ```int getOddOccurrence(int... array)``` 56 | 57 | Every element in array will occur an even ammount of times. There will be exactly one element 58 | Example: {1,2,2,1,3,4,3,4,4,6,5,6,5} => 4 occurs only an odd number of times. 59 | 60 | ###13. Maximal scalar product### 61 | ```long maximalScalarSum(int[] a, int[] b)``` 62 | You are given two vectors, *a* and *b*. Let a be ```{a1,a2,a3}``` and b be ```{b1,b2,b3}```. The scalar product of vectors *a* and *b* is the number ```a1*b1 + a2*b2 + a3*b3``` 63 | 64 | Find a permutation of a, and a permutation of b, for which their scalar product is the largest possible. 65 | 66 | ###14. Max span### 67 | ```int maxSpan(int[] numbers)``` 68 | Consider the leftmost and righmost appearances of some value in an array. We'll say that the "span" is the number of elements between the two inclusive. A single value has a span of 1. Returns the largest span found in the given array. 69 | 70 | maxSpan({1, 2, 1, 1, 3}) → 4 71 | maxSpan({1, 4, 2, 1, 4, 1, 4}) → 6 72 | maxSpan({1, 4, 2, 1, 4, 4, 4}) → 6 73 | 74 | ###15. Can balance?### 75 | ```boolean canBalance(int[] numbers)``` 76 | 77 | canBalance({1, 1, 1, 2, 1}) → true 78 | canBalance({2, 1, 1, 2, 1}) → false 79 | canBalance({10, 10}) → true 80 | 81 | Return true if there is an element in the array, where you can split the array in half and the sum of left side would be equal to the sum of the right part. 82 | 83 | ###16. Rescale an image using nearest neighbour interpolation### 84 | ```int[][] rescale(int[][] original, int newWidth, int newHeight)``` 85 | 86 | You are given an image *original*. Rescale it to newWidth, newHeight, using nearest neighbour interpolation. (See http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation) 87 | 88 | 89 | ###17. Reverse a String### 90 | `String reverseMe(String argument)` 91 | 92 | ###18. Reverse each word in a String### 93 | `String reverseEveryChar(String arg)` 94 | 95 | `reverseEveryChar("What is this") => tahW si siht` 96 | 97 | ###18. Is this string a palindrome### 98 | `boolean isPalindrome(String argument)` 99 | 100 | ###19. Is this number a palindrome### 101 | `boolean isPalindrome(int argument)` 102 | 103 | 104 | ###18. Copy every character K times ### 105 | `String copyEveryChar(String input, int k)` 106 | 107 | `copyEveryChar("tldr", 3) => "tttllldddrrr"` 108 | Important Note: There is an error in the unit test. 109 | If you are failing on this line: 110 | `assertEquals("ttt www rrr", problems2.copyEveryChar("t w r", 2));` 111 | It is because is shoud be "3" instead of "2" as an argument at the end. 112 | (My bad). 113 | 114 | 115 | 116 | ###19. Check for palindrome length around '*' ### 117 | `int getPalindromeLength(String input)` 118 | 119 | `getPalindromeLength("taz*zad") => 2` 120 | 121 | ###20. Count number of (non-overlapping) occurences ### 122 | `int countOcurrences(String needle, String haystack)` 123 | `countOcurrences("da", "daaadaadada") => 4` 124 | 125 | *Bonus* Only 1 line of code allowed. No loops :) 126 | 127 | ###21. Decode an URL ### 128 | Input 'kitten%20pic.jpg' 129 | Output 'kitten pic.jpg' 130 | %20=>' ' 131 | %3A=>':' 132 | %3D=>'?' 133 | %2F=>'/' 134 | `String decodeUrl(String input)` 135 | 136 | 1 line of code is allowed. 137 | 138 | ###22. Sum all the numbers in a String### 139 | `int sumOfNumbers(String input)` 140 | 141 | Sum all of the numbers in the String. Ignore the characters. 142 | `sumOfNumbers("abc123dd34") => 157` 143 | `sumOfNumbers("12 99 1) => 112` 144 | 145 | ###23. Is String A an anagram of String B?### 146 | `boolean anagram(String A, String B)` 147 | See http://en.wikipedia.org/wiki/Anagram 148 | 149 | No HashMaps, hashSets, or such stuff allowed : ) 150 | Note: The last unit test is a *faulty* one. Delete it. (My bad). 151 | ###24. Is an anagram of String A a susbstring in B?### 152 | `boolean hasAnagramOf(A,B)` 153 | Return whether an anagram of String A can be found in String B. 154 | 155 | 156 | ###25. Convert To Greyscale 157 | 158 | Implement the following function/method: 159 | ``` 160 | convertToGreyscale(imgPath) 161 | ``` 162 | Given the path of a color image (.jpg, .png, .bmp) create a greyscale version of it and save it. 163 | 164 | **WARNING!** You are not allowed to use any libraries, you have to write your own algorithm! 165 | -------------------------------------------------------------------------------- /week2/2-Exceptions/README.md: -------------------------------------------------------------------------------- 1 | All tasks should go into 'Exceptions1' project in your workspace. 2 | 3 | ### 1. Unchecked (runtime) exception example usage 4 | Design an unchecked Exception class "DatabaseCorruptedException", which is to be thrown whenever a corrupted database object is detected (e.g. "" for username in table `Users`). 5 | Use good and concise exception message, explaining what is wrong with the object `User` object - for this excercise you can assume that the `username` field is "". 6 | 7 | *Database Corruption is not expected to happen. People should not need to 'catch' an eventual database corruption on every interaction/transaction with a database, because this is not an expected situation and it is not OK to be fault-tolerant on such scenarios* 8 | 9 | Make a method that throws this exception. Use it and see your message in the stack trace. 10 | 11 | ### 2. Checked exception example usage 12 | Imagine you are designing an API for using services. 13 | 14 | *In the real world, services break all the time. Network connections go down, firewalls go crazy, routers get re(s)tarted, etc. It is more or less expected of you to be network fault-tolerant, as networks are not perfect and they just can't be.* 15 | 16 | For this task, you need to **first create an Exception class, a checked one (`extends Exception`), give it a good long-ish name, like `ServiceNotAvailableAtTheMoment`, and encapsulate some information about the situation in the exception.** For example, it would be cool if in the exception message you write possible reasons for the service breakdown, what could have gotten wrong, etc. 17 | 18 | *Exceptions messages and traces are watched by **developer**. It is a sign of courtesy and respectfullness to write good, descriptive and concise exception messages to help people that investigate when things go wrong.* 19 | 20 | After you are done designing your good looking Exception class, you should declare your a method (e.g. `useService`) that is **declared to throw your exception**. 21 | After you are done with that, try and use your method. 22 | Observe how every time you use it, you are forced to think *what will happen if this service fails?*. 23 | 24 | 25 | ### 3. Make the 'Time' class fool-proof 26 | Remember you wrote a `Time` class, some weeks ago? Go back, copy your class into your project and **make it fool-proof**. Protect the poor public user of your class using exceptions. Think of some unpleasent (or edge-case) situations that may occur while using your class. 27 | 28 | Hint: Check http://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html and 29 | http://stackoverflow.com/questions/15208544/when-should-illegalargumentexception-be-thrown 30 | 31 | ### 4. Do not allow them to insert null as a key! 32 | You know HashMap in java. They are completely happy with (null, null) key-value pairs. 33 | Let's say we are not happy with this being the default behavior. Especially for **keys**. 34 | 35 | Extends `HashMap` and make it optional for your class to accept null **keys**, but by default, set this option to `false`. (Use a flag, make a constructor with the option.) 36 | Fix the `put`, `get` methods accordingly to allow or not allow null keys. 37 | What should you do in those methods if your object is set not to allow null keys? Throw your very own, good-named, custom-made exception with a good message, of course. 38 | 39 | ### 5. Impement your very own immutable and unmodifiable list 40 | Create a class 'ImmutableList', which implements List. It's okay to extend something else. 41 | Your delcaration should be like this: 42 | `public class Immutable extends ArrayList` 43 | 44 | Unmodifiable collection is collection which oce crated can not accept new ellements and its ellements can not be removed.Its add and remove methods should throw exception. 45 | 46 | immutable collection is when its ellements can not be changed once put in it. 47 | 48 | Of course, in order for your class to be immutable, you need good constructors. 49 | Make a constructor that accepts a `Collection collection` in which you add all the elements from `collection` to your list, and forbid anyone to modify it by throwing an exception when anyone tries to do that. 50 | 51 | Implement `Arrays.asList()` factory method functionality - declare a static method ` List asList(T... arguments)`. 52 | Use the `@SafeVarargs` annotation on top of your method declararation to tell the compiler you won't be naughty. 53 | 54 | Hint: In the `get` method return a clone of the element, so it can't be modified from the outside. Use Apache Commons for object cloning https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/SerializationUtils.html 55 | 56 | ##Bonus!## 57 | ### Implement a XmlMarkupBuilder class ### 58 | Make an easy to use XmlMarkupBuilder class, which creates a **valid xml** 59 | 60 | We won't worry about namespaces here. By valid, I mean having the `` declaration, and having only tags, attributes, and text between a tag opening and tag closing. 61 | 62 | For instance: 63 | ``` 64 | 65 | attr 66 | 67 | 68 | 69 | 70 | Hey dude check it out 71 | why are you out of scope, man? 72 | 73 | 74 | ``` 75 | 76 | Your class should support these operations: 77 | ```java 78 | XmlMarkupBuilder openTag(String tagName); 79 | XmlMarkupBuilder addAttr(String attrName, String attrValue); // valid only when you have a tag opened! 80 | XmlMarkupBuilder addText(String text); 81 | XmlMarkupBuilder closeTag(); //close the last opened tag. 82 | XmlMarkupBuilder finish(); //close all tags and finelize your object. Any open,addAttr or other calls to your object, should throw an Exception. 83 | String getResult(); //let's stay close to http://en.wikipedia.org/wiki/Builder_pattern 84 | ``` 85 | 86 | Example usages of your `XmlMarkupBuilder` class 87 | ```java 88 | XmlMarkupBuilder markupBuilder = new XmlMarkupBuilder(); 89 | 90 | //http://en.wikipedia.org/wiki/Fluent_interface ftw 91 | String validMarkup = markupBuilder.openTag("body").addAttr("background","0xFF0000").addText("Helo HTML!").finalize().getResult(); 92 | markupBuilder.closeTag() //BOOOM! Object finalized! Exception! 93 | ............... 94 | XmlMarkupBuilder markupBuilder = new XmlMarkupBuilder(); 95 | markupBuilder.openTag("a").closeTag().openTag("a") //BOOOM! You need to have a root XML object, XML is not a list! 96 | ............... 97 | XmlMarkupBuilder markupBuilder = new XmlMarkupBuilder(); 98 | markupBuilder.openTag("a").closeTag().closeTag() //BOOOM! What the hell are we closing?! 99 | ............... 100 | XmlMarkupBuilder markupBuilder = new XmlMarkupBuilder(); 101 | markupBuilder.openTag("a").closeTag().addAttribute("href","https://www.youtube.com/watch?v=P5ft_7Bcyc4") //BOOOM! What are you adding attribute to? 102 | 103 | and so on and so on 104 | ``` 105 | -------------------------------------------------------------------------------- /week6/1-Multithreading/MultiWebCrawler/com/hackbulgaria/corejava/crawler/no/ParalelWebCrawler.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava.crawler.no; 2 | 3 | import java.io.IOException; 4 | import java.net.MalformedURLException; 5 | import java.net.URI; 6 | import java.net.URISyntaxException; 7 | import java.nio.charset.StandardCharsets; 8 | import java.util.ArrayList; 9 | import java.util.Collections; 10 | import java.util.HashSet; 11 | import java.util.List; 12 | import java.util.Set; 13 | import java.util.concurrent.ExecutionException; 14 | import java.util.concurrent.ExecutorService; 15 | import java.util.concurrent.Executors; 16 | import java.util.concurrent.Future; 17 | import java.util.concurrent.atomic.AtomicInteger; 18 | import java.util.regex.Matcher; 19 | import java.util.regex.Pattern; 20 | import java.util.stream.Collectors; 21 | 22 | import org.apache.http.HttpResponse; 23 | import org.apache.http.client.HttpClient; 24 | import org.apache.http.client.methods.HttpGet; 25 | import org.apache.http.client.utils.URIUtils; 26 | import org.apache.http.impl.client.DefaultHttpClient; 27 | import org.apache.http.util.EntityUtils; 28 | 29 | public class ParalelWebCrawler { 30 | private final Set visitedUrls = new AtomicSet(); 31 | private ExecutorService service; 32 | 33 | public ParalelWebCrawler(ExecutorService service) { 34 | this.service = service; 35 | } 36 | 37 | public Set crawl(URI currentLocation, final String needle, AtomicInteger parentInt) throws URISyntaxException, MalformedURLException, InterruptedException, ExecutionException { 38 | Set finalResult = Collections.synchronizedSet(new HashSet()); 39 | // visitedUrls.add(currentLocation); 40 | String urlContents = downloadContents(currentLocation); 41 | if (urlContents.contains(needle)) { 42 | // return 43 | finalResult.add(currentLocation); 44 | System.out.println("found in " + currentLocation); 45 | } 46 | { 47 | Set allLinks = getAllLinks(urlContents); 48 | removeNotNeededLinks(allLinks); 49 | 50 | AtomicInteger i = new AtomicInteger(); 51 | List filterURIs = filterURIs(currentLocation, allLinks); 52 | List>> futures = new ArrayList>>(); 53 | for (URI link : filterURIs) { 54 | if (!visitedUrls.contains(link)) { // visitedUrls.add(currentLocation); 55 | i.incrementAndGet(); 56 | futures.add(service.submit( () -> { 57 | Set crawl = crawl(link, needle, i); 58 | i.decrementAndGet(); 59 | // parent notify 60 | synchronized (i) { 61 | i.notify(); 62 | } 63 | return crawl; 64 | })); 65 | } 66 | } 67 | 68 | 69 | // while children not finished - wait 70 | // don't wait if children not started 71 | while (!i.compareAndSet(0, 0)) { 72 | synchronized (i) { 73 | i.wait(); 74 | } 75 | } 76 | 77 | for (Future> resultFuture : futures) { 78 | Set result = resultFuture.get(); 79 | if (!result.isEmpty()) { 80 | finalResult.addAll(result); 81 | } 82 | } 83 | } 84 | return finalResult; 85 | } 86 | 87 | private List filterURIs(URI currentLocation, Set allLinks) { 88 | List filteredLinks = allLinks.stream().map( 89 | link -> { 90 | try { 91 | return normalizeLink(currentLocation, link); 92 | } catch (Exception e) { 93 | e.printStackTrace(); 94 | return false; 95 | } 96 | }) 97 | .filter(link -> { 98 | return link != null; 99 | }) 100 | .filter(url -> { 101 | try { 102 | return isInsideDomain(currentLocation, (URI)url); 103 | } catch (Exception e) { 104 | // TODO Auto-generated catch block 105 | e.printStackTrace(); 106 | return false; 107 | } 108 | }) 109 | .collect(Collectors.toList()); 110 | 111 | List res = new ArrayList(); 112 | for (Object uri : filteredLinks) { 113 | res.add((URI)uri); 114 | } 115 | return res; 116 | } 117 | 118 | private void removeNotNeededLinks(Set allLinks) { 119 | if (allLinks.contains("#")) { 120 | allLinks.remove("#"); 121 | } 122 | } 123 | 124 | private static boolean isInsideDomain(URI currentLocation, URI asUrl) 125 | throws URISyntaxException { 126 | return currentLocation.getHost().equals(asUrl.getHost()); 127 | } 128 | 129 | private URI normalizeLink(URI currentLocation, String link) 130 | throws MalformedURLException, URISyntaxException { 131 | URI uri = null; 132 | try { 133 | uri = new URI(link); 134 | } catch (URISyntaxException e) { 135 | System.out.println(e); 136 | return null; 137 | } 138 | 139 | if (uri.getScheme() != null && uri.getHost() != null) { 140 | return uri; 141 | } 142 | return URIUtils.resolve(currentLocation, uri); 143 | } 144 | 145 | private static String downloadContents(URI startLocation) 146 | throws URISyntaxException { 147 | HttpClient httpClient = new DefaultHttpClient(); 148 | System.out.println("Currently crawling : " + startLocation); 149 | HttpGet get = new HttpGet(startLocation); 150 | try { 151 | HttpResponse response = httpClient.execute(get); 152 | String contents = EntityUtils.toString(response.getEntity(), 153 | StandardCharsets.UTF_8); 154 | return contents; 155 | } catch (IOException e) { 156 | e.printStackTrace(); 157 | // IO Error when connecting to the server, whatever, just return 158 | // empty contents 159 | return ""; 160 | } finally { 161 | httpClient.getConnectionManager().shutdown(); 162 | } 163 | } 164 | 165 | private static Set getAllLinks(String content) { 166 | Set resultList = new HashSet<>(); 167 | // ArrayList resultList = new ArrayList<>(); 168 | String regex = ""; 169 | Pattern pattern = Pattern.compile(regex); 170 | Matcher matcher = pattern.matcher(content); 171 | while (matcher.find()) { 172 | resultList.add(matcher.group(1)); 173 | } 174 | return resultList; 175 | } 176 | 177 | private boolean testSharp(Set visitedUrls, URI uri) { 178 | boolean result = true; 179 | String url = uri.toString(); 180 | if (url.endsWith("#")) { 181 | url = url.substring(0, url.length() - 1); 182 | try { 183 | if (visitedUrls.contains(new URI(url))) { 184 | result = false; 185 | } 186 | } catch (URISyntaxException e) { 187 | // TODO Auto-generated catch block 188 | e.printStackTrace(); 189 | } 190 | if (result && url.endsWith("/")) { 191 | url = url.substring(0, url.length() - 1); 192 | try { 193 | if (visitedUrls.contains(new URI(url))) { 194 | result = false; 195 | } 196 | } catch (URISyntaxException e) { 197 | // TODO Auto-generated catch block 198 | e.printStackTrace(); 199 | } 200 | } 201 | } else { 202 | System.out.println(url); 203 | url += "#"; 204 | try { 205 | if (visitedUrls.contains(new URI(url))) { 206 | result = false; 207 | } 208 | } catch (URISyntaxException e) { 209 | e.printStackTrace(); 210 | } 211 | } 212 | // if (!result) 213 | // System.out.println("uri:" +uri +" "+visitedUrls); 214 | return result; 215 | } 216 | 217 | public void visit(URI loc) { 218 | visitedUrls.add(loc); 219 | } 220 | } -------------------------------------------------------------------------------- /week1/2-OOP/README.md: -------------------------------------------------------------------------------- 1 | ###OOP fun!### 2 | 3 | ###1### 4 | Make a class Car. 5 | Make several(at least 4) subtypes of Car, representing the different brands of cars - Audi, BMW, Wolkswagen (of course!), etc. 6 | 7 | Later, for the Audi type you need to return its mileage, because all the German brand manufacturers require it - how you will do it? 8 | 9 | ###2### 10 | 11 | Make a class `Time` to hold information about the current time and *the current date* . 12 | 13 | Make an *easy-to-use* constructor (from client perspective), that would represent the time and date the client wants to hold in your class. 14 | 15 | Implement the toString() method, returning the time and date in format : "hh:mm:ss dd.MM.YY". 16 | 17 | Check out String.format method 18 | 19 | *Bonus* 20 | Make a factory method `now()` for your class, returning the Time at the present moment :) 21 | 22 | See http://en.wikipedia.org/wiki/Factory_method_pattern 23 | 24 | ###3### 25 | 26 | Make a class `Pair`, representing a pair of *Objects* (later we will revisit this with Generics) 27 | 28 | Create getter methods for the first and second member of the pair. 29 | http://stackoverflow.com/questions/2036970/how-do-getters-and-setters-work 30 | 31 | Implement the toString method, giving a meaningful representation of the class. 32 | Override the equals method from Object => two pairs are equal if both their members are equal. 33 | 34 | Make the class *immutable*. 35 | ###4### 36 | 37 | Create and implement a class `StackImpl`, representing a... well, stack. 38 | 39 | Think about all the required (public) operations needed, so that one can use a stack class. You know, stuff like actually pushing an element, popping an element, length, clear, isEmpty, stuff like that. Think about the return types of those operations (see task 5, you may get a hint about one). *Extract them all to an interface `Stack`, which your class should implement*. 40 | 41 | ###5### 42 | 43 | Create an implementation of your `Stack` interface, which has the added invariant: 44 | -It does not allow an element to be duplicated. If there is an element 'a' in the stack, and some smart guy pushes 'a' again, his operation should fail, and the smart guy should have a way to know this. 45 | 46 | 47 | ###6### 48 | 49 | Implement a (doubly-linked) list (using ints only). Just as before, extract all of its required public operations in an interface. Some of those operations are add, *remove*, size, get(int elementIndex), getHead (getFirst), getTail(getLast), etc. 50 | Think good and hard about your implementation, and whether you will need another class for a List Node. 51 | 52 | ###7### 53 | Implement your own `Stack` with your own (doubly) `LinkedList` class : ) 54 | 55 | *Bonus* implement a unique stack just as before, but using your `LinkedList` and an *anonymous implementation*, combined with a factory method. 56 | See http://www.programmerinterview.com/index.php/java-questions/java-anonymous-class-example/ 57 | 58 | Return your anonymous implementation from a factory method! 59 | 60 | ###8### 61 | Make a mutable class 'Matrix' represeting a NxM (Pixel[][]) matrix. `Pixel` is a POJO containing three float values - R, G, B. Think good about your constructors, your data. Your goal is to make this class as convenient as possible for the person using it. 62 | 63 | Your class `Matrix` should have another cool thing about it => it would allow operations with every pixel. 64 | In order for this to work, your class should declare a public method `operate(MatrixOperation op)` 65 | 66 | Where `MatrixOperation` is an interface, containing a method 'Pixel withPixel(int x, int y, Pixel[][] matrix)'. 67 | *Think - why are we getting x, y, and the matrix instead of just passing the pixel value?* 68 | 69 | Implement the toString(), converting the whole matrix into a String in a way that it would be visible on the console. 70 | 71 | The method should `operate(MatrixOperation op)` should call the `withPixel` method for every x and y in the matrix and assign the result of `withPixel` to the matrix. 72 | 73 | Now that you have this, implement: 74 | - brightness reduce 75 | - grayscale 76 | - gaussian blur (optional) 77 | 78 | ###9### 79 | Create a friendly interactive calculator in java 80 | Bundle, execute and test your program as a jar file. 81 | 82 | Example usage of your program: 83 | ``` 84 | java -jar yourJar.jar 85 | Hello! 86 | 87 | Enter expression:> 5 88 | Output:> 5.0 89 | Enter expression:> 3 + (5 + 9*7 + 9) 90 | Output:> 78 91 | Enter expression:> 4*(4 + 5) 92 | Output:> 36 93 | Enter expression:> exit 94 | 95 | Bye! 96 | ``` 97 | 98 | 99 | Supported operations: 100 | - addition 101 | - multiplication 102 | - division (this is not integer division! 2/3 = 0.666666667, not 0!) 103 | - brackets 104 | - Negative numbers. 105 | 106 | Multiplication and addition take precedence and have higher priority than addition. 107 | Priority list: () before * before / before + before - 108 | 109 | Your program should support a *variable* ammount of spaces in the expression, as shown in the output below. 110 | 111 | *Hints* 112 | - Use this class if you have trouble reading from system.in: https://gist.github.com/GeorgiPachov/bcc51f1fc3b3a1de1bce 113 | - Write this program in a TDD way, but *iteratively*. Start from the easiest 'features', add tests for them,and build up on them after you are sure they are rock-solid. 114 | - Do not worry about invalid input: 115 | `123/213/123/1/2/23/3 //order of divisions is undefined here, do what is easier for you.` 116 | `(12 + 5) + 65) //brackets mashup => this is invalid input` 117 | `(12++-*3) //operators mashup => this is invalid input` 118 | - There is no need to use any collections here. 119 | - There is no need to use any generics here. 120 | - There is no need to use any regular expressions here. You will probably just need to escape some stuff when calling `String.replace`, e.g. to replace a '+', you will need to call `someString.replace("\\+","my replaced output)` (because + is from regex syntax. And because `replace` accepts a regex input as a String, not as a Pattern, which is actually not the smartest decision in the world). 121 | 122 | But if you think regexes will help you here and will make your life easier, you are free to use them. 123 | Use http://docs.oracle.com/javase/tutorial/essential/regex/ for reference 124 | and http://www.tutorialspoint.com/java/java_regular_expressions.htm for example usage. 125 | 126 | 127 | *Bonus challenge objectives* 128 | - Use less than 120 lines of code in total for all classes. (not counting bonuses implementations and unit tests, you can test as much as you like there!) 129 | - Add factorial operation support. It should precede multiplication and division, but bracket rules should apply. 130 | Examples: 131 | ``` 132 | java -jar your Jar.jar: 133 | Hello! 134 | 135 | Output:> 5.0 136 | Enter expression:> (5+3)! 137 | Output:> 40320.0 138 | Enter expression:> (2*3 + 1*3)! 139 | Output:> 362880.0 140 | Enter expression:> 9! 141 | ``` 142 | - Add 'power' support: 2^3 = 8, 3^2 = 9, etc. It has the same priority as multiplication! 143 | Examples: 144 | ``` 145 | java -jar your Jar.jar: 146 | Hello! 147 | 148 | Enter expression:> 3^2 + 2^3 149 | Output:> 17.0 150 | Enter expression:> 2^3 + (5+3)^2 151 | Output:> 72.0 152 | Enter expression:> 2^3! + 5*((3+2!)^2) 153 | Output:> 189.0 154 | ``` 155 | -Add support for mashed up user input: E.g. 2+3\ should be parsed as 2+3. Discourage any symbols different from the ones you are interested in. //regexes will probably help you here, although the difference with/without is ~2 lines of code. 156 | -------------------------------------------------------------------------------- /week7/1-Java8/Java8Problems/test/com/hackbulgaria/corejava2/StudentOperationsImplTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.hackbulgaria.corejava2; 5 | 6 | import static org.junit.Assert.assertEquals; 7 | import static org.junit.Assert.assertTrue; 8 | import static org.junit.Assert.fail; 9 | 10 | import java.lang.reflect.InvocationTargetException; 11 | import java.util.List; 12 | import java.util.Map; 13 | import java.util.Set; 14 | 15 | import org.junit.Before; 16 | import org.junit.Test; 17 | import org.junit.runners.model.InitializationError; 18 | import org.reflections.Reflections; 19 | 20 | import com.hackbulgaria.corejava2.data.Gender; 21 | import com.hackbulgaria.corejava2.data.Student; 22 | import com.hackbulgaria.corejava2.data.StudentsDataFactory; 23 | 24 | /** 25 | * @author georgi 26 | * 27 | */ 28 | public class StudentOperationsImplTest { 29 | private StudentOperations studentOperations; 30 | private java.util.List allStudents; 31 | 32 | @Before 33 | public void setup() throws InitializationError, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { 34 | Reflections reflections = new Reflections(getClass().getPackage().getName()); 35 | Set> subtypes = reflections.getSubTypesOf(StudentOperations.class); 36 | if (subtypes.isEmpty()){ 37 | throw new InitializationError("You have not subclassed" + StudentOperations.class.getCanonicalName()); 38 | } 39 | if (subtypes.size() > 1){ 40 | throw new InitializationError("One subclass of " + StudentOperations.class.getCanonicalName() + " will do, No need for more."); 41 | } 42 | this.allStudents = StudentsDataFactory.getAllStudents(); 43 | this.studentOperations = subtypes.iterator().next().getConstructor(java.util.List.class).newInstance(allStudents); 44 | } 45 | 46 | @Test 47 | public void testGetStudentsWithLowestMarks() throws Exception { 48 | java.util.List students = studentOperations.getStudentsWithLowestMarks(); 49 | assertTrue(students.size() == 3); 50 | assertTrue(students.stream().filter(s -> s.getGrade() != 2.0f).count() == 0); 51 | } 52 | 53 | @Test 54 | public void testGetStudentsWIthHighestMarks() throws Exception{ 55 | List students = studentOperations.getStudentsWithHighestMarks(); 56 | assertTrue(students.size() == 2); 57 | assertTrue(students.stream().filter(s -> s.getGrade() != 6.0f).count() == 0); 58 | } 59 | 60 | /** 61 | * Test method for {@link com.hackbulgaria.corejava2.StudentOperationsImpl#getAllPassing()}. 62 | */ 63 | @Test 64 | public void testGetAllPassing() { 65 | List students = studentOperations.getAllPassing(); 66 | assertTrue(students.stream().filter(s -> s.getGrade() < 3.0f).count() == 0); 67 | } 68 | 69 | /** 70 | * Test method for {@link com.hackbulgaria.corejava2.StudentOperationsImpl#getAllFailing()}. 71 | */ 72 | @Test 73 | public void testGetAllFailing() { 74 | List students = studentOperations.getAllFailing(); 75 | assertTrue(students.stream().filter(s -> s.getGrade() >= 3.0f).count() == 0); 76 | } 77 | 78 | /** 79 | * Test method for {@link com.hackbulgaria.corejava2.StudentOperationsImpl#getAverageMark()}. 80 | */ 81 | @Test 82 | public void testGetAverageMark() { 83 | double avgMark = studentOperations.getAverageMark(); 84 | assertTrue(String.valueOf(avgMark).startsWith("4.142")); 85 | } 86 | 87 | /** 88 | * Test method for {@link com.hackbulgaria.corejava2.StudentOperationsImpl#splitStudentsByMarks(float)}. 89 | */ 90 | @Test 91 | public void testSplitStudentsByMarks() { 92 | Map> map = studentOperations.splitStudentsByMarks(3.5f); 93 | System.out.println(map.get(Boolean.TRUE).size()); 94 | assertTrue(map.get(Boolean.TRUE).size() == 15); 95 | } 96 | 97 | /** 98 | * Test method for {@link com.hackbulgaria.corejava2.StudentOperationsImpl#orderByMarkDescending()}. 99 | */ 100 | @Test 101 | public void testOrderByMarkDescending() { 102 | List students = studentOperations.orderByMarkDescending(); 103 | for (int i = 1; i < students.size(); i++){ 104 | Student prev = students.get(i-1); 105 | assertTrue(prev.getGrade() >= students.get(i).getGrade()); 106 | } 107 | } 108 | 109 | /** 110 | * Test method for {@link com.hackbulgaria.corejava2.StudentOperationsImpl#orderByMarkAscending()}. 111 | */ 112 | @Test 113 | public void testOrderByMarkAscending() { 114 | List students = studentOperations.orderByMarkAscending(); 115 | for (int i = 1; i < students.size(); i++){ 116 | Student prev = students.get(i-1); 117 | assertTrue(prev.getGrade() <= students.get(i).getGrade()); 118 | } 119 | } 120 | 121 | /** 122 | * Test method for {@link com.hackbulgaria.corejava2.StudentOperationsImpl#getMarksDistributionByAge()}. 123 | */ 124 | @Test 125 | public void testDistributeByAge() { 126 | Map> gradesByAge = studentOperations.getMarksDistributionByAge(); 127 | assertTrue(gradesByAge.get(20).stream().reduce(Double::sum).get().compareTo(15.0) == 0); 128 | } 129 | 130 | /** 131 | * Test method for {@link com.hackbulgaria.corejava2.StudentOperationsImpl#getAverageMarkByGender()}. 132 | */ 133 | @Test 134 | public void testGetAverageMarkByGender() { 135 | Map avg= studentOperations.getAverageMarkByGender(); 136 | assertTrue(avg.keySet().size() == 2); 137 | double maleAvg = allStudents.stream().filter(s -> s.getGender().equals(Gender.MALE)).mapToDouble(Student::getGrade).average().getAsDouble(); 138 | assertTrue(avg.get(Gender.MALE).compareTo(maleAvg) == 0); 139 | } 140 | 141 | /** 142 | * Test method for {@link com.hackbulgaria.corejava2.StudentOperationsImpl#getMarksDistribution()}. 143 | */ 144 | @Test 145 | public void testDistributeMarks() { 146 | Map distribution = studentOperations.getMarksDistribution(); 147 | assertTrue(distribution.get(2.0) == 3); 148 | assertTrue(distribution.get(6.0) == 2); 149 | assertTrue(distribution.get(4.5) == 2); 150 | } 151 | 152 | /** 153 | * Test method for {@link com.hackbulgaria.corejava2.StudentOperationsImpl#getEmailToHeader()}. 154 | */ 155 | @Test 156 | public void testGetEmailToHeader() { 157 | String expectedResult = "Georgi_1996@gmail.com, Dimitur_1994@gmail.com, Vasil_1996@gmail.com, Tihomir_1995@gmail.com, Ivomir_1995@gmail.com, Vladislav_1994@gmail.com, Filip_1996@gmail.com, Boris_1995@gmail.com, Genady_1994@gmail.com, Ivan_1994@gmail.com, Elena_1994@gmail.com, Radoslav_1993@gmail.com, Maria_1993@gmail.com, Teodor_1993@gmail.com, Stanislava_1993@gmail.com, Anton_1995@gmail.com, Marina_1994@gmail.com, Salfetka_1994@gmail.com, Zlatina_1993@gmail.com, Petar_1996@gmail.com, Yanitsa_1994@gmail.com"; 158 | assertEquals(expectedResult.replaceAll("\\s+", "").toLowerCase(), studentOperations.getEmailToHeader().replaceAll("\\s+", "").toLowerCase()); 159 | } 160 | 161 | /** 162 | * Test method for {@link com.hackbulgaria.corejava2.StudentOperationsImpl#splitStudentMarksByGenderAndThenByAge()}. 163 | */ 164 | @Test 165 | public void testSplitStudentMarksByGenderAndThenByAge() { 166 | Map>> map = studentOperations.splitStudentMarksByGenderAndThenByAge(); 167 | assertTrue(map.keySet().size() == 2); 168 | assertTrue(map.get(Gender.MALE).get(20).size() == 4); 169 | assertTrue(map.get(Gender.MALE).get(21).size() == 4); 170 | } 171 | 172 | } 173 | -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/src/ParalelWebCrawler.java: -------------------------------------------------------------------------------- 1 | import java.io.IOException; 2 | import java.net.MalformedURLException; 3 | import java.net.URI; 4 | import java.net.URISyntaxException; 5 | import java.nio.charset.StandardCharsets; 6 | import java.util.ArrayList; 7 | import java.util.Collections; 8 | import java.util.HashSet; 9 | import java.util.List; 10 | import java.util.Set; 11 | import java.util.concurrent.Callable; 12 | import java.util.concurrent.ExecutionException; 13 | import java.util.concurrent.ExecutorService; 14 | import java.util.concurrent.atomic.AtomicInteger; 15 | import java.util.regex.Matcher; 16 | import java.util.regex.Pattern; 17 | import java.util.stream.Collectors; 18 | 19 | import java.util.AbstractCollection; 20 | import java.util.AbstractSet; 21 | import java.util.concurrent.ConcurrentSkipListSet; 22 | 23 | import org.apache.http.HttpResponse; 24 | import org.apache.http.client.HttpClient; 25 | import org.apache.http.client.methods.HttpGet; 26 | import org.apache.http.client.utils.URIUtils; 27 | import org.apache.http.impl.client.DefaultHttpClient; 28 | import org.apache.http.util.EntityUtils; 29 | import com.google.common.util.concurrent.*; 30 | 31 | public class ParalelWebCrawler { 32 | private final Set visitedUrls = new AtomicSet(); 33 | private ListeningExecutorService service; 34 | 35 | public ParalelWebCrawler(ListeningExecutorService service) { 36 | this.service = service; 37 | } 38 | 39 | public Set crawl(URI currentLocation, final String needle, AtomicInteger parentInt) throws URISyntaxException, 40 | MalformedURLException, InterruptedException, ExecutionException { 41 | Set finalResult = new ConcurrentSkipListSet(); 42 | // visitedUrls.add(currentLocation); 43 | String urlContents = downloadContents(currentLocation); 44 | if (urlContents.contains(needle)) { 45 | // return 46 | finalResult.add(currentLocation); 47 | System.out.println("found in " + currentLocation); 48 | } 49 | { 50 | Set allLinks = getAllLinks(urlContents); 51 | removeNotNeededLinks(allLinks); 52 | 53 | AtomicInteger i = new AtomicInteger(); 54 | List filterURIs = filterURIs(currentLocation, allLinks); 55 | for (URI link : filterURIs) { 56 | if (!visitedUrls.contains(link)) { // visitedUrls.add(currentLocation); 57 | i.incrementAndGet(); 58 | ListenableFuture> a = service.submit(new Callable>() { 59 | @Override 60 | public Set call() throws Exception { 61 | Set crawl = crawl(link, needle, i); 62 | /*i.decrementAndGet(); 63 | // parent notify 64 | synchronized (i) { 65 | i.notify(); 66 | }*/ 67 | return crawl; 68 | } 69 | }); 70 | 71 | Futures.addCallback(a, new FutureCallback>() { 72 | @Override 73 | public void onSuccess(Set result) { 74 | finalResult.addAll(result); 75 | } 76 | 77 | @Override 78 | public void onFailure(Throwable throwable) { 79 | 80 | } 81 | }); 82 | } 83 | 84 | } 85 | 86 | 87 | // while children not finished - wait 88 | // don't wait if children not started 89 | /* 90 | while (!i.compareAndSet(0, 0)) { 91 | synchronized (i) { 92 | i.wait(); 93 | } 94 | } 95 | 96 | for (ListenableFuture> resultListenableFuture : futures) { 97 | Set result = resultListenableFuture.get(); 98 | if (!result.isEmpty()) { 99 | finalResult.addAll(result); 100 | } 101 | } 102 | */ 103 | } 104 | return finalResult; 105 | } 106 | 107 | private List filterURIs(URI currentLocation, Set allLinks) { 108 | List filteredLinks = allLinks.stream().map( 109 | link -> { 110 | try { 111 | return normalizeLink(currentLocation, link); 112 | } catch (Exception e) { 113 | e.printStackTrace(); 114 | return false; 115 | } 116 | }) 117 | .filter(link -> { 118 | return link != null; 119 | }) 120 | .filter(url -> { 121 | try { 122 | return isInsideDomain(currentLocation, (URI)url); 123 | } catch (Exception e) { 124 | // TODO Auto-generated catch block 125 | e.printStackTrace(); 126 | return false; 127 | } 128 | }) 129 | .collect(Collectors.toList()); 130 | 131 | List res = new ArrayList(); 132 | for (Object uri : filteredLinks) { 133 | res.add((URI)uri); 134 | } 135 | return res; 136 | } 137 | 138 | private void removeNotNeededLinks(Set allLinks) { 139 | if (allLinks.contains("#")) { 140 | allLinks.remove("#"); 141 | } 142 | } 143 | 144 | private static boolean isInsideDomain(URI currentLocation, URI asUrl) 145 | throws URISyntaxException { 146 | return currentLocation.getHost().equals(asUrl.getHost()); 147 | } 148 | 149 | private URI normalizeLink(URI currentLocation, String link) 150 | throws MalformedURLException, URISyntaxException { 151 | URI uri = null; 152 | try { 153 | uri = new URI(link); 154 | } catch (URISyntaxException e) { 155 | System.out.println(e); 156 | return null; 157 | } 158 | 159 | if (uri.getScheme() != null && uri.getHost() != null) { 160 | return uri; 161 | } 162 | return URIUtils.resolve(currentLocation, uri); 163 | } 164 | 165 | private static String downloadContents(URI startLocation) 166 | throws URISyntaxException { 167 | HttpClient httpClient = new DefaultHttpClient(); 168 | System.out.println("Currently crawling : " + startLocation); 169 | HttpGet get = new HttpGet(startLocation); 170 | try { 171 | HttpResponse response = httpClient.execute(get); 172 | String contents = EntityUtils.toString(response.getEntity(), 173 | StandardCharsets.UTF_8); 174 | return contents; 175 | } catch (IOException e) { 176 | e.printStackTrace(); 177 | // IO Error when connecting to the server, whatever, just return 178 | // empty contents 179 | return ""; 180 | } finally { 181 | httpClient.getConnectionManager().shutdown(); 182 | } 183 | } 184 | 185 | private static Set getAllLinks(String content) { 186 | Set resultList = new HashSet<>(); 187 | // ArrayList resultList = new ArrayList<>(); 188 | String regex = ""; 189 | Pattern pattern = Pattern.compile(regex); 190 | Matcher matcher = pattern.matcher(content); 191 | while (matcher.find()) { 192 | resultList.add(matcher.group(1)); 193 | } 194 | return resultList; 195 | } 196 | 197 | private boolean testSharp(Set visitedUrls, URI uri) { 198 | boolean result = true; 199 | String url = uri.toString(); 200 | if (url.endsWith("#")) { 201 | url = url.substring(0, url.length() - 1); 202 | try { 203 | if (visitedUrls.contains(new URI(url))) { 204 | result = false; 205 | } 206 | } catch (URISyntaxException e) { 207 | // TODO Auto-generated catch block 208 | e.printStackTrace(); 209 | } 210 | if (result && url.endsWith("/")) { 211 | url = url.substring(0, url.length() - 1); 212 | try { 213 | if (visitedUrls.contains(new URI(url))) { 214 | result = false; 215 | } 216 | } catch (URISyntaxException e) { 217 | // TODO Auto-generated catch block 218 | e.printStackTrace(); 219 | } 220 | } 221 | } else { 222 | System.out.println(url); 223 | url += "#"; 224 | try { 225 | if (visitedUrls.contains(new URI(url))) { 226 | result = false; 227 | } 228 | } catch (URISyntaxException e) { 229 | e.printStackTrace(); 230 | } 231 | } 232 | // if (!result) 233 | // System.out.println("uri:" +uri +" "+visitedUrls); 234 | return result; 235 | } 236 | 237 | public void visit(URI loc) { 238 | visitedUrls.add(loc); 239 | } 240 | } -------------------------------------------------------------------------------- /week6/1-Multithreading/Additional multithreading/.idea/uiDesigner.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | -------------------------------------------------------------------------------- /week3/1-Files-Paths-Streams/README.md: -------------------------------------------------------------------------------- 1 | ### 1. Prepare utility methods for reading and writing to files 2 | 3 | Create a class `FileUtils`. Make it a [Singleton](http://en.wikipedia.org/wiki/Singleton_pattern). 4 | Implement two methods - `String readFrom(File file)` and `String readFrom(Path path)`. 5 | They should read **all the contents** from the file to a String, using the default (OS-default) charset. 6 | As this method is an **API**, you should NOT catch the exceptions in the method's body, remember? 7 | For this task, do not worry about different encoding. 8 | Do the same for a 'write' method. 9 | 10 | ### 2. Implement a 'Properties' file parser. 11 | [.properties files](http://en.wikipedia.org/wiki/.properties) are commonly used in java as a resources and configuration. They just represent a key=value pairs, where each pair is a new line. The `#` sign denotes a comment. 12 | 13 | Make a **utility** method `Map parseProperties` that reads a .properties file and returns its content as a Map. 14 | 15 | The `#`-sign, when seen as a **first character in a line**, denotes that **the line is a comment and should not be parsed**. 16 | 17 | ``` 18 | # this=comment 19 | a1=b1 20 | a2 =b2 21 | a3 = b3 22 | a4 = b4 23 | a5=b6=b7=b8 24 | a6=b9 #comment 25 | a7==b10 26 | ``` 27 | All of the above entries (`a1` to `a7`) are valid key-value pairs. 28 | The value for `a5` is `b6=b7=b8` 29 | The value for `a6` is `b9 #comment` 30 | The value for `a7` is `=b10` 31 | 32 | Hints and suggestions: 33 | - Use JUnit @Before, @BeforeClass, @After, @AfterClass http://stackoverflow.com/questions/20295578/difference-between-before-and-beforeclass 34 | - Make a helper method, that does all the parsing logic (generates the Map from List). 35 | - Do **not** split the lines on your own like `fileContents.split("\n")`. This is not a cross-platform solution. 36 | - First test your helper method, which creates the Map from a given List. 37 | - After assuring yourself your helper method works great, test the `parseProperties` method. 38 | - Create (write) your .properties file (for testing) programmatically, in `setUp`. Do not depend on external resources for testing if you can avoid it! 39 | - Do not polute the filesystem because you are writing tests. Clean up (delete the file in `tearDown`) after your each test run. Your file is relevant ONLY for the tests, and it should not outlive them. 40 | 41 | ### 3. Implement the wc command 42 | 43 | Create a **utility** method `WordCountResult wordCount(Path path)` with an overload `WordCountResult wordCount(File file)`. 44 | This method, when given a file, returns the number of words, lines and characters in that file. 45 | Java can't return multiple values. You can return an instance of `WordCountResult` which is a class that contains three integers - word count, lines count, characters count. 46 | 47 | Follow the testing approach described in the previous task. 48 | 49 | ### 4. Fix these subtitles 50 | Have you ever wanted to watch a movie, and all the cyrillic characters be like ������? 51 | 52 | Have you ever received emails like "Greetings, dear �������"? 53 | 54 | These things happen because of different encoding and decoding schemes used. 55 | 56 | As we all know, even text files and strings are retained as binary in memory. 57 | So if we have the string 'Dumbledore', we need to store an array of bytes to represent it. 58 | 59 | The way we choose what bytes represent 'Dumbledore' in memory is called an **encoding scheme**. (a.k.a. encoding) 60 | "windows-1251" is a type of encoding scheme. 61 | "ISO-8859-1" is another type of encoding scheme. 62 | 63 | The way we choose to convert it from a byte array to a char array is called a **decoding scheme**. 64 | 65 | **Unicode** is an industry standard of encodings. There is no good reason against an Unicode encoding scheme. 66 | UTF-8 is a good encoding scheme from the Unicode standard. (There are others, which differ slightly.) 67 | 68 | So, here you are given a text file with a Windows-1251 encoding. Your task is to convert it to UTF-8. You can test this in your browser, just open the text file and choose to view it with UTF-8 encoding. (You might have to rename it to .html though) 69 | 70 | The subtitle you need to fix are here: http://subsunacs.net/get.php?id=41854 71 | It is okay not to use TDD for this one. 72 | 73 | In summary: 74 | - Create a utility method `fixEncoding(Path path)` 75 | - Backup the subtitles file so you don't have to download it again if you fail to write it. 76 | - The text in the file given is encoded using a **windows-1251** scheme. 77 | - Conver it to UTF-8. 78 | 79 | ### 5. Reduce-file-path in 1 line 80 | *This is a really quick one.* 81 | Solve the [reduce-file-path problem (number 27)] (https://github.com/HackBulgaria/Programming101/blob/master/week0/simple_problems2.md) with no more than 1 line of Java code. 82 | Check out [the normalize method] (http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html#normalize%28%29) 83 | 84 | 85 | ### 6. Find all broken links in a given folder 86 | A broken link is a link that points to something that is simply not there. 87 | Make a **utility** method that is given a folder (as a Path), and searches recursively for bad links. 88 | If it finds a bad link, it should simply print it out. 89 | 90 | How to detect a bad link? Use `Files.isSymbolicLink(path)` in order to check if a file is a link, and `Files.readSymbolicLink(path)` in order to follow it and receive its target's path. 91 | 92 | 93 | ### 7. Implement a simple text file compression 94 | 95 | Create a **utility** method `compress(Path filePath)` 96 | that reads the text from `filePath` and writes it back in a compressed way, adding the `.compr` extension (or one of your choosing). 97 | 98 | Let's have the file 99 | `buffalo buffalo buffalo rides a buffalo buffalo buffalo.` 100 | There are a lot of repeating words here (duuh). 101 | 102 | Parse all the words from a file, add them to an index, and assign them numbers. 103 | Replace all the words in the file with their respective indices, prepending them with '~' or another letter of your choosing. 104 | E.g. our sentence becomes 105 | 106 | ~0 ~0 ~0 ~1 ~2 ~0 ~0 ~0. 107 | 108 | Implement a decompressing scheme (another **utility** method) 109 | 110 | Check out the file compression you've just made : ) 111 | 112 | 113 | ### BONUS: Find all duplicated files 114 | 115 | ##### Summary: 116 | Two files are **duplicates** if all the **bytes** from file1 are the same as the **bytes** from file2. 117 | Find and print out all touples of duplicate files. 118 | 119 | ##### Detailed 120 | 121 | We are going to make a command line java tool, that receives a folder location and finds and prints outs all groups of duplicating files, ancestors of the given folder. 122 | It is called like this: 123 | ```java 124 | java -jar duplicates-finder.jar /home/georgi/Dev 125 | 126 | //Ouput below: 127 | //Group A 128 | /home/georgi/Dev/eclipse/settings.xml 129 | /home/georgi/Dev/ADT/settings.xml //duplicate 130 | /home/georgi/Dev/eclipse/plugins/default/settings.xml //duplicate 131 | 132 | //Group B 133 | /home/georgi/Dev/eclipse/update-site.xml 134 | /home/georgi/Dev/ADT/update-site.xml //duplicate 135 | /home/georgi/Dev/tmp/copies/site_backup.xml //duplicate 136 | 137 | //Group C 138 | /home/georgi/Dev/eclipse/readme.txt 139 | /home/georgi/Dev/workspace/Project1/data/readme.txt //duplicate 140 | 141 | 3 groups of duplications found. 142 | A total of 5 duplicate files can be deleted, freeing up /*the sum of the lengths of those 5 files*/ disk space 143 | ... 144 | ``` 145 | 146 | All the files from Group A are equivalent (every file from Group A has the same contents). 147 | Same for group B and group C. As you can see, the **name** of the file does not matter. 148 | File A can be a duplicate of file B regardless of them having different names. 149 | 150 | 151 | Hints: 152 | - When visiting files, be careful with links. You should check if the file currently being visited is a link by using `Files.isSymbolicLink(Path)`. If the file happens to be a symbolic link, find and use **it's target**, by using `Files.readSymbolicLink(pathOfSymbolicLink);`. 153 | - When following symbolic links in the way described above, be careful, because symbolic links may lead to files that **do not exist** (broken links). Your program should not stop working merely because it saw a broken link! 154 | - Ignore files with size over 512KB. If we want our tool to work for large files, the task get's a little bit more interesting and non-trivial :) 155 | - Be very careful when dealing with **OS-Special files (devices files)**. You should ignore them, as the OS call might block/hang when you try to read or write into of them. Use `Files.isRegular(path)` to check whether a file is a normal file, or it's a special file and we should probably not play with it. 156 | - Create a folder `testData` in your project. Create several folders and files with which you can test your problem. If you are too lazy for that, just download and unzip [this test data] (https://github.com/HackBulgaria/Core-Java-1/blob/master/7-Files1/testData.zip) in your project. 157 | [More spoilers and possible approaches] (https://gist.github.com/GeorgiPachov/039d2c339358dbfcc650) 158 | 159 | 160 | ### BONUS: MP3 organizer 161 | 162 | Traverse a given directory recusrivelly and extract the ID3 tags from all mp3 files. 163 | Use this information to give the mp3 files appropriate names in order to fix the titles. For instance Unknown Artist - Unknown Song should be renamed to Amaranthe - The Nexus (if you have good taste of course). 164 | As a plus organize the files based on artist and album. For every artist create a directory, containing a directory for each of his albums. Move the songs into the respective albums. 165 | 166 | Usage: `mp3organizer.jar "songs"` 167 | 168 | Helpful links: 169 | http://javamusictag.sourceforge.net/ 170 | -------------------------------------------------------------------------------- /week0/2-TypesArraysStrings/Project1/test/com/hackbulgaria/corejava/tests/Problems2Tests.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava.tests; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | import static org.junit.Assert.assertFalse; 5 | import static org.junit.Assert.assertTrue; 6 | import static org.junit.Assert.fail; 7 | 8 | import java.util.Arrays; 9 | 10 | import org.junit.Before; 11 | import org.junit.Test; 12 | 13 | import com.hackbulgaria.corejava.Problems2; 14 | import com.hackbulgaria.corejava.Problems2Factory; 15 | 16 | public class Problems2Tests { 17 | 18 | private static final String NOT_IMPLEMENTED = "NOT IMPLEMENTED"; 19 | private final Problems2 problems2 = Problems2Factory.createProblems2Instance(); 20 | 21 | private void notImplemented() { 22 | fail(NOT_IMPLEMENTED); 23 | } 24 | 25 | @Test 26 | public void testIsPrime() { 27 | assertTrue(problems2.isPrime(5)); 28 | assertTrue(problems2.isPrime(7)); 29 | assertTrue(problems2.isPrime(41)); 30 | assertTrue(problems2.isPrime(3)); 31 | assertTrue(!problems2.isPrime(39)); 32 | } 33 | 34 | @Test 35 | public void testIsOdd() { 36 | assertTrue(problems2.isOdd(3)); 37 | assertTrue(problems2.isOdd(5)); 38 | assertTrue(problems2.isOdd(7)); 39 | assertTrue(problems2.isOdd(-1)); 40 | assertTrue(problems2.isOdd(-3)); 41 | assertTrue(!problems2.isOdd(0)); 42 | } 43 | 44 | @Test 45 | public void testMin() { 46 | int min = problems2.min(1, 3, 4, 5, 6, -1, 23, -125, 125125, -63262, 2151, -1212); 47 | assertTrue(min == -63262); 48 | 49 | min = problems2.min(-1, 0, 1, 1, -1, -9, 0, 5); 50 | assertTrue(min == -9); 51 | } 52 | 53 | @Test 54 | public void testKthMin() { 55 | int testArr[] = new int[] { 1, 2151, 125, 125, 1125, 16, 754, 132, 613, -51521, 51251, 675, 125366 }; 56 | Arrays.sort(testArr); 57 | 58 | assertTrue(testArr[0] == problems2.kthMin(1, testArr)); 59 | assertTrue(testArr[1] == problems2.kthMin(2, testArr)); 60 | assertTrue(testArr[2] == problems2.kthMin(3, testArr)); 61 | } 62 | 63 | @Test 64 | public void testGetAverage() { 65 | int testArr[] = new int[] { 1, 2151, 125, 125, 1125, 16, 754, 132, 613, -51521, 51251, 675, 125366 }; 66 | 67 | float avg = 0; 68 | for (int i = 0; i < testArr.length; i++) { 69 | avg += testArr[i]; 70 | } 71 | avg /= testArr.length; 72 | 73 | assertEquals(avg, problems2.getAverage(testArr), 0.01f); 74 | } 75 | 76 | @Test 77 | public void testGetSmallestMultiple() { 78 | assertEquals(2520, problems2.getSmallestMultiple(10)); 79 | assertEquals(232792560, problems2.getSmallestMultiple(20)); 80 | 81 | } 82 | 83 | @Test 84 | public void testGetLargestPalindrome() { 85 | assertEquals(99, problems2.getLargestPalindrome(100)); 86 | assertEquals(99_999, problems2.getLargestPalindrome(10_0000)); 87 | assertEquals(123_321, problems2.getLargestPalindrome(123_456)); 88 | } 89 | 90 | @Test 91 | public void testHistorgram() { 92 | final short[][] image = new short[10][10]; 93 | assertEquals(100, problems2.histogram(image)[0]); 94 | 95 | for (short i = 0; i < image.length; i++) { 96 | for (short j = 0; j < image[0].length; j++) { 97 | image[i][j] = (short) (i * image[0].length + j); 98 | } 99 | } 100 | 101 | assertEquals(1, problems2.histogram(image)[13]); 102 | 103 | for (short i = 0; i < image.length; i++) { 104 | for (short j = 0; j < image[0].length; j++) { 105 | image[i][j] = (short) (i * j + j); 106 | } 107 | } 108 | } 109 | 110 | @Test 111 | public void testDoubleFac() { 112 | assertEquals(720, problems2.doubleFac(3)); 113 | assertEquals(2, problems2.doubleFac(2)); 114 | } 115 | 116 | @Test 117 | public void testKthFac() { 118 | assertEquals(3628800, problems2.kthFac(1, 10)); 119 | assertEquals(3628800 / 10, problems2.kthFac(1, 9)); 120 | testDoubleFac(); 121 | } 122 | 123 | @Test 124 | public void testGetOddOccurrence() { 125 | int[] numbers = new int[] { 1, 1, 3, 3, 6, 5, 4, 6, 5, 9, 1, 1, 3, 15, 4, 5, 9, 3, 15 }; 126 | assertEquals(5, problems2.getOddOccurrence(numbers)); 127 | } 128 | 129 | @Test 130 | public void testPow() { 131 | assertEquals(8, problems2.pow(2, 3)); 132 | assertEquals(-1, problems2.pow(-1, 9)); 133 | assertEquals(1, problems2.pow(99, 0)); 134 | 135 | assertEquals(-32, problems2.pow(-2, 5)); 136 | assertEquals(729, problems2.pow(3, 6)); 137 | } 138 | 139 | @Test 140 | public void testMaximalScalarSum() { 141 | int[] a = new int[] { 1, 2, 3, 4, 5, 6 }; 142 | int[] b = new int[] { 0, 0, 0, 0, 0, 0 }; 143 | 144 | assertEquals(0, problems2.maximalScalarSum(a, b)); 145 | b = new int[] { 1, 1, 1, 1, 1, 1 }; 146 | 147 | assertEquals(21, problems2.maximalScalarSum(a, b)); 148 | 149 | b = new int[] { 5, 4, 8, 9, -1, 2 }; 150 | assertEquals(129, problems2.maximalScalarSum(a, b)); 151 | 152 | } 153 | 154 | @Test 155 | public void testMaxSpan() { 156 | assertEquals(4, problems2.maxSpan(new int[] { 1, 2, 1, 1, 3 })); 157 | assertEquals(6, problems2.maxSpan(new int[] { 1, 4, 2, 1, 4, 1, 4 })); 158 | assertEquals(6, problems2.maxSpan(new int[] { 1, 4, 2, 1, 4, 4, 4 })); 159 | } 160 | 161 | @Test 162 | public void testCanBalance() { 163 | assertTrue(problems2.canBalance(new int[] { 1, 1, 1, 2, 1 })); 164 | assertFalse(problems2.canBalance(new int[] { 2, 1, 1, 2, 1 })); 165 | assertTrue(problems2.canBalance(new int[] { 10, 10 })); 166 | } 167 | 168 | @Test 169 | public void testRescale() { 170 | final int[][] original = new int[100][100]; 171 | int counter = 0; 172 | for (int y = 0; y < original.length; y++) { 173 | for (int x = 0; x < original[0].length; x++) { 174 | original[y][x] = counter++; 175 | } 176 | } 177 | 178 | final int newWidth = 10; 179 | final int newHeight = 10; 180 | 181 | final int[][] newImage = problems2.rescale(original, newWidth, newHeight); 182 | assertEquals(newImage[0][0], original[0][0]); 183 | assertEquals(newImage[9][9], original[90][90]); 184 | assertEquals(newImage[0][9], original[0][90]); 185 | assertEquals(newImage[9][0], original[90][0]); 186 | } 187 | 188 | @Test 189 | public void testStringReverse(){ 190 | assertEquals("ytrewq", problems2.reverseMe("qwerty")); 191 | assertEquals("How about", problems2.reverseMe("tuoba woH")); 192 | assertEquals(" ", " "); 193 | assertEquals("This is bad", problems2.reverseMe(problems2.reverseMe("This is bad"))); 194 | } 195 | 196 | @Test 197 | public void testReverseWords(){ 198 | assertEquals("tahW si siht", problems2.reverseEveryWord("What is this")); 199 | assertEquals("yrevE drow si desrever", problems2.reverseEveryWord("Every word is reversed")); 200 | } 201 | 202 | @Test 203 | public void testIsPalindrome(){ 204 | assertEquals(true, problems2.isPalindrome("radar")); 205 | assertEquals(false, problems2.isPalindrome("Nixin")); 206 | assertEquals(false, problems2.isPalindrome("Nikon")); 207 | assertEquals(true, problems2.isPalindrome("Nobody ydoboN")); 208 | assertEquals(false, problems2.isPalindrome("Nobody ydobom")); 209 | } 210 | 211 | @Test 212 | public void testIsPalindromeNumber(){ 213 | assertEquals(true, problems2.isPalindrome(191)); 214 | assertEquals(false, problems2.isPalindrome(1992)); 215 | assertEquals(true, problems2.isPalindrome(0x00)); 216 | } 217 | 218 | @Test 219 | public void testCopyCharacter(){ 220 | assertEquals("aaa", problems2.copyEveryChar("a", 3)); 221 | assertEquals("aabbaadd", problems2.copyEveryChar("abad", 2)); 222 | assertEquals("Wwhhaatt tthhee hheellll", problems2.copyEveryChar("What the hell", 2)); 223 | } 224 | 225 | @Test 226 | public void testPalindromStarLength(){ 227 | assertEquals(2, problems2.getPalindromeLength("taz*zad")); 228 | assertEquals(0, problems2.getPalindromeLength("tad*zad")); 229 | assertEquals(3, problems2.getPalindromeLength("tad*dat")); 230 | } 231 | 232 | @Test 233 | public void testNonOverlappingOccurrences(){ 234 | assertEquals(0, problems2.countOcurrences("demetrius", "")); 235 | assertEquals(2, problems2.countOcurrences("ab", "abandon all hope, abandon this place!")); 236 | assertEquals(2, problems2.countOcurrences("de", "deutschland uber alles, detonate all the allez")); 237 | } 238 | 239 | @Test 240 | public void testCopyEveryCharacter(){ 241 | assertEquals("ttwwrr", problems2.copyEveryChar("twr", 2)); 242 | assertEquals("ttt www rrr", problems2.copyEveryChar("t w r", 3)); 243 | } 244 | 245 | @Test 246 | public void testDecodeUrl(){ 247 | assertEquals("http://meyerweb.com/eric/tools/dencoder/", problems2.decodeURL("http%3A%2F%2Fmeyerweb.com%2Feric%2Ftools%2Fdencoder%2F")); 248 | assertEquals("http://javarevisited.blogspot.com/2012/10/10-java-string-interview-question-answers-top.html", problems2.decodeURL("http%3A%2F%2Fjavarevisited.blogspot.com%2F2012%2F10%2F10-java-string-interview-question-answers-top.html")); 249 | } 250 | 251 | 252 | @Test 253 | public void testSumOfIntegers(){ 254 | assertEquals(999, problems2.sumOfNumbers("999problemsButJavaAint0")); 255 | assertEquals(0, problems2.sumOfNumbers("000 three five -1 1")); 256 | assertEquals(2, problems2.sumOfNumbers("samir1WhatAreYou2Doing3You-4")); 257 | } 258 | 259 | @Test 260 | public void testAnagrams(){ 261 | assertEquals(true, problems2.areAnagrams("A", "A")); 262 | assertEquals(true, problems2.areAnagrams("BRADE", "BEARD")); 263 | assertEquals(true, problems2.areAnagrams("TOP CODER", "COTE PROD")); 264 | assertEquals(false, problems2.areAnagrams("TOP CODER", "COTO PRODE")); 265 | 266 | // Грешен Unit test! 267 | // assertEquals(true, problems2.areAnagrams("том месвролуко риддъл", "тук съм и лорд волдеморт")); 268 | } 269 | 270 | @Test 271 | public void testHasAnagramOf(){ 272 | assertEquals(true, problems2.hasAnagramOf("abc", "cbadfghhijh")); 273 | assertEquals(true, problems2.hasAnagramOf("abcdef", "fedbcadh")); 274 | assertEquals(true, problems2.hasAnagramOf("dirac", "libcarid")); 275 | assertEquals(false, problems2.hasAnagramOf("abc", "cbda")); 276 | } 277 | } -------------------------------------------------------------------------------- /week2/1-CollectionsAndGenerics1/README.md: -------------------------------------------------------------------------------- 1 | All of these should go in a project named 'Collections1' 2 | ###0.Check if an expression of brackets is correct### 3 | Such expression is a string like `"()()())))((())("` - it has multiple brackets, your job is to check whether the expression is correct. 4 | Such expression is correct if: 5 | - it starts with a `'('` 6 | - it ends with a `')'` 7 | - the number of opening brackets equals exactly the number of closing brackets 8 | - at no point in the string the number of closing brackets is higher than the number of opening brackets. E.g. `())(()` is not a valid one, because at index 2 there is a second closing bracket with only one opening bracket. 9 | 10 | ###1.Reverse a generic collection### 11 | Declare a method, expecting a Collection and reverse it in your method. Return the same collection given, do not return a new collection!. 12 | Either use: 13 | `static void reverse (Collection collection)` 14 | or make it a concrete type: 15 | `static void reverse(Collection collection)` 16 | 17 | *Do not try to use* Collections.reverse. It works only for a List, and not for collections : ) 18 | 19 | 20 | ###2.Implement an on/off collection### 21 | Implement a Collection, in which, if you add an element twice, the element gets removed from your collection. 22 | 23 | *Hint and edge case spoiler:* How would you handle null objects? :) 24 | *Fun fact:*: As logical idea behind a collection is an abstraction of a... well, bunch of elements, allowing null actually makes no sense. 25 | Note that the java implementations are broken on several places, allowing nulls to creep into the collections, making all kinds of havoc later on. Don't blindly follow the java implementations, do better. 26 | 27 | 28 | ###3.Make a bounded queue### 29 | A bounded queue is queue with a 'limit' of maximum elements. 30 | Your `BoundedQueue` class of course should implement the `Queue` interface. 31 | Example usage of your `BoundedQueue` class: 32 | ``` 33 | BoundedQueue boundedQueue = new BoundedQueue<>(3); 34 | boundedQueue.offer(1); 35 | boundedQueue.offer(2); 36 | boundedQueue.offer(3); 37 | boundedQueue.offer(4); 38 | boundedQueue.offer(5); 39 | System.out.println(boundedQueue.toString()); //3,4,5 40 | ``` 41 | 42 | ###4.Rotate the elements of a collection### 43 | Make a void *utility* method that rotates the contents of a collection. 44 | 45 | You are given a collection containing `[one, two, three, four, five, six, seven]` 46 | "Rotating" it once means the collection becoming `[seven, one, two, three, four, five, six]` 47 | 48 | ```java 49 | void rotate(Collection collection, int rotateStep ) 50 | ``` 51 | 52 | `rotateStep` can be negative - meaning you are rotating to the left, and not to the right. 53 | 54 | 55 | ###5.Given a list contaning some duplicate values, find the first unique element### 56 | Make a *utility* method, which returns the first unique element in a given argument of type `Collection`. 57 | Example: 58 | 59 | ```java 60 | Collection ints = Arrays.asList(1,2,3,4,5,5,4,3,1); 61 | System.out.println(yourMethod(ints)) //2; 62 | ``` 63 | 64 | 65 | ###6.Given several sets, find the duplicating elements### 66 | Write a *utility* method, that takes several sets, and returns a set that contains the duplicating elements of all the other sets. 67 | 68 | ``` 69 | A = {1,2,3,4,5} 70 | B = {4,5,6} 71 | C = {5,6,7,8} 72 | ``` 73 | 74 | `yourMethd(A,B,C) => D{5}` 75 | 76 | ###7.Given a list of Students, sort them by grade### 77 | Lets say you have a `List`, where a Student is a class, containing two fields: `name` and `grade`. 78 | 79 | Sort them by their grades first. Their grades actually are integers => 2,3,4,5,6. If two students happen to have the same grades, sort those two by their names. 80 | 81 | ###8.Give me the median, quick!### 82 | Make an interface `Statistics`, which has these operations: 83 | 84 | ``` 85 | -getMean(); 86 | -getMedian(); 87 | -getMode(); 88 | -getRange(); 89 | ``` 90 | 91 | If you don't know what Mean,Median, Mode and Range are, see http://www.purplemath.com/modules/meanmode.htm 92 | 93 | Make an implementation of this interface, with an additional operation `add(int number)` (Work with integers only). 94 | I would also like to able to look through all the integers I've given you, with a `for(Integer i : isntanceOfYourClass) {... }`. 95 | 96 | So, as a client of your code, I will be adding some integers(just like in a list), and would want you to give me the mean, median, mode and range. 97 | 98 | *Bonus/Challenge* 99 | Every method from `Statistics` interface should complete in O(1) time. 100 | This is a little bit on the algorithm side, and you might need some interesting data structures : ) 101 | Come back to this when you are done with all the tasks. 102 | 103 | 104 | *Hints* 105 | Solve this one *iteratively* with TDD. 106 | 107 | 108 | ###9.Implement a class ToDoList### 109 | Imagine you have a world of stuff to do. 110 | Homeworks, courseworks, exams, even preparing for HackBulgaria! 111 | Unfortunately you do not have much time - you need to eat, you need to sleep, you need to have a good time. 112 | 113 | Now, you need to sort your priorities right! Make a class `ToDoList`, which supports the following operations: 114 | `void add(Task t)` 115 | `void markFinished(Task t)` 116 | `void markCancelled(Task t)` 117 | `Task getTop()` 118 | `boolean canFinish()` 119 | `int getRemainigTime()` //calculates the time remaining after you've done all of your tasks. 120 | 121 | ... where `Task` is a class which represents something you have to do. What data/methods should it have? What is common for all the tasks you need to get done? 122 | A `Task` should at the very least have a priority and a time required in order to finish. 123 | You should take an integer in your constructor - the ammount of hours available for each task. 124 | 125 | Example usage of your class: 126 | 127 | ```java 128 | ToDoList todo = new ToDoList(11); //11 hours remaining! 129 | todo.addTask(new StudyForAlgebraTask(10)); //maximum priority! 130 | todo.addTask(new LearnGeometryTask()); //default priority, smaller than 10 131 | todo.addTask(new GoOutTask(1.5f)); //default priority, smaller than 10 132 | todo.addTask(new SleepTask()); //straight 8 hours, of course! 133 | 134 | if (todo.canFinish()){ 135 | System.out.println("Woohoo!"); 136 | } else { 137 | System.out.println("I am ...screwed :("); 138 | } 139 | 140 | System.out.println(todo.top()) //StudyForAlgebraTask 141 | System.out.println(todo.getTimeNeeded()) //sum of the time needed for every task added in todo list 142 | ``` 143 | 144 | *Hints* 145 | See Comparable and Comparator classes in Java. Check out the PriorityQueue class. 146 | http://javarevisited.blogspot.com/2011/06/comparator-and-comparable-in-java.html 147 | 148 | ###10.Make a utility method that converts a hashMap into a very human-readable string### 149 | Make a *utility* method that takes a `HashMap` 150 | and *returns a String*, representing the HashMap. 151 | 152 | I want you to make a utility method that does this, *do not* override `toString()` in hashMap. 153 | 154 | Example: 155 | 156 | ```java 157 | String result = YourUtilsClass.yourFirstUtilMethod(map); 158 | System.out.println(result) // { key1:value1, key2:value2, key3:value3 } 159 | ``` 160 | 161 | ###11.Count occurences of words in text### 162 | Make a *utility* method that takes a `String text` and returns a map, which on every word in `text` maps the number of times this word has been used. 163 | 164 | See Example: 165 | 166 | ```java 167 | Map result = YourUtilsClass.yourSecondUtilMethod("Ninjas are all over the place! We are all going to die!"); 168 | System.out.println(YourUtilsClass.yourFirstUtilMethod(result)); 169 | ``` 170 | 171 | Outputs: 172 | 173 | ``` 174 | // { Ninjas:1, are:2, all:2, over:1, the:1, place!:1, We:1, going:1, to:1, die!:1 } 175 | ``` 176 | 177 | Retain the ordering of the elements! 178 | 179 | ##Epic bonus!## 180 | ###Cryptoanalysis fun### 181 | There is an old technique for encrypting messages - shuffling the letters. For instance, if we take the string `Godzilla`, one crypted version of it 182 | is `Mrezotti`. 183 | The cipher here is 184 | ``` 185 | G=m 186 | o=r 187 | d=e 188 | i=o 189 | l=t 190 | z=z 191 | ``` 192 | 193 | Your task here is to decrypth the following text: 194 | ``` 195 | Ajb vnf guj luqv akjvojufq . Sk qkkj egvfs Rkhfwu Lumemu'q akhhfjvq kj vnf ohifjbojc essoxew kg Dofck Ckqve , nfsf'q Ffsjejbk Tkssfq vk qnkr vnf ohifvukuq zkujc dkz nkr ov'q bkjf Iv'q vnf qehf fxfsz quhhfs . Nk-kjf neq fxfs coxfj hf ejzvnojc kj e iwevf . Tnfz hebf hf akhifvf gks hz iweaf vnf xfsz hkhfjv I ckv ojvk vnf gosqv vfeh; vnev'q rnev vnfz veucnv hf ejb ov'ww df vnev rez ujvow I wfexf . Tnf nocnfs puewovz iwezfsq vnev akhf - ejb Dofck Ckqve oq puewovz - vnf csfevfs vnf akhifvovokj roww df ejb vnf dfvvfs ov'ww df gks vnf vfeh .Ajb gfes jkv ( ks , ewvfsjevoxfwz , bkj'v cfv vkk ftaovfb) , Tkssfq neq jk iwejq vk vuam veow ejb suj ejb wfexf noq iezanfamq dfnojb . I bkj'v nexf ejz iwejq vk hkxf erez socnv jkr . Ig rf woqvfjfb vk eww vnf suhkusq rf'b nexf 50 iwezfsq . Nkr'q jkv vnf socnv vohf vk df vnojmojc edkuv Cnfwqfe . I'h qusf vnf awud oq rksmojc vk ohiskxf vnf vfeh , duv eww vnev hevvfsq socnv jkr oq vnf Wkswb Cui .Om , vnev dov edkuv vnf 50 iwezfsq hebf hf anuamwf . Noaf kjf , Ffsjejbk .Nkr , oj ej obfew rkswb , rf rkuwb ifsneiq cfv vnfqf rksbq gskh Lumemu , rnkh rf'b womf vk dfakhf wfcfjbesz ev Cnfwqfe . Buv rf bkj'v woxf oj ej obfew rkswb , ejb ojqvfeb rf cfv vnfqf rksbq gskh Tkssfq , rnkh rf'b womf vk dfakhf e wkjc-gksckvvfj hfhksz ev Cnfwqfe . Aweq .Tnev dfojc qeob , qojaf ov'q deqoaewwz ej ohikqqodwf vk veqm vk sob kusqfwxfq kg vnf £100h gwki , ev wfeqv nf'q ckv vnf socnv evvovubf . Hussez? 196 | ``` 197 | 198 | Once more, your task is not to make a program that *deciphers every possible text on the planet*, you just have to decipher *this text*. And by decipher, I mean extract the meaning of it - let's not care about missed dots, commas, word casing and such stuff. 199 | 200 | ####Instructions and hints#### 201 | 202 | A usually good counter-attacking technique is to simply make a histogram of the usage of letters in the *given* text and comapre it to the histogram of letters *in the language*. 203 | For example, in the english language, the letter 'e' is the most frequently used, in a total of 13% of all letters. So there is a good chance the most commonly used letter in the given text is 'e'. 204 | 205 | You can see some frequencies and letter distribution facts here: 206 | http://en.wikipedia.org/wiki/Letter_frequency 207 | http://www.cryptograms.org/letter-frequencies.php 208 | 209 | 210 | Some hints: 211 | - Ignore one-letter words. They are likely dots or hyphens or commas, you will add them later. 212 | - Trim spaces on words after you parse them. Make sure you are not analysing empty spaces. 213 | - Watch out for letter casing! Make sure you analyze uppercase 'T' the same as downcase 't'. 214 | - Make a method `String applyCipher(Map cipher)`. You will likely find a good use for it. Of course, it is not mandatory. 215 | - As this problem requires some visual examination, do *not try* to solve in TDD at first. In fact, in general, apply *TDD* only when you have something to test for. 216 | - If frequency attack turns out to be not good enough, check [the list of 5000 most used words in English](https://docs.google.com/spreadsheets/d/1LuHWIlshSqwfr3AKwvqIoXAGZrNmsPUopwfhc3DhtS4/edit#gid=0). There is a good chance some of those will be from the first words you unveil! 217 | 218 | 219 | --------------------------------------------------------------------------------