Friday, March 29, 2013

How to Convert from Decimal to Binary



  • How to Convert from Decimal to Binary


The decimal (base ten) numeral system has ten possible values (0,1,2,3,4,5,6,7,8, or 9) for each place-value. In contrast, the binary (base two) numeral system has two possible values, often represented as 0 or 1, for each place-value.

http://www.wikihow.com/Convert-from-Decimal-to-Binary



  • Converting Decimal Fractions to Binary


In fact, there is a simple, step-by-step method for computing the binary expansion on the right-hand side of the point. We will illustrate the method by converting the decimal value .625 to a binary representation..

Step 1: Begin with the decimal fraction and multiply by 2. The whole number part of the result is the first binary digit to the right of the point.

Because .625 x 2 = 1.25, the first binary digit to the right of the point is a 1.
So far, we have .625 = .1??? . . . (base 2) .

Step 2: Next we disregard the whole number part of the previous result (the 1 in this case) and multiply by 2 once again. The whole number part of this new result is the second binary digit to the right of the point. We will continue this process until we get a zero as our decimal part or until we recognize an infinite repeating pattern.

Because .25 x 2 = 0.50, the second binary digit to the right of the point is a 0.
So far, we have .625 = .10?? . . . (base 2) .

Step 3: Disregarding the whole number part of the previous result (this result was .50 so there actually is no whole number part to disregard in this case), we multiply by 2 once again. The whole number part of the result is now the next binary digit to the right of the point.

Because .50 x 2 = 1.00, the third binary digit to the right of the point is a 1.
So now we have .625 = .101?? . . . (base 2) .

Step 4: In fact, we do not need a Step 4. We are finished in Step 3, because we had 0 as the fractional part of our result there.

Hence the representation of .625 = .101 (base 2) .

You should double-check our result by expanding the binary representation.






  • Infinite Binary Fractions


the binary representation of the decimal fraction 1/10 is, in fact, infinite.Step 1: Begin with the decimal fraction and multiply by 2. The whole number part of the result is the first binary digit to the right of the point.

Because .1 x 2 = 0.2, the first binary digit to the right of the point is a 0.
So far, we have .1 (decimal) = .0??? . . . (base 2) .

Step 2: Next we disregard the whole number part of the previous result (0 in this case) and multiply by 2 once again. The whole number part of this new result is the second binary digit to the right of the point. We will continue this process until we get a zero as our decimal part or until we recognize an infinite repeating pattern.

Because .2 x 2 = 0.4, the second binary digit to the right of the point is also a 0.
So far, we have .1 (decimal) = .00?? . . . (base 2) .

Step 3: Disregarding the whole number part of the previous result (again a 0), we multiply by 2 once again. The whole number part of the result is now the next binary digit to the right of the point.

Because .4 x 2 = 0.8, the third binary digit to the right of the point is also a 0.
So now we have .1 (decimal) = .000?? . . . (base 2) .

Step 4: We multiply by 2 once again, disregarding the whole number part of the previous result (again a 0 in this case).

Because .8 x 2 = 1.6, the fourth binary digit to the right of the point is a 1.
So now we have .1 (decimal) = .0001?? . . . (base 2) .

Step 5: We multiply by 2 once again, disregarding the whole number part of the previous result (a 1 in this case).

Because .6 x 2 = 1.2, the fifth binary digit to the right of the point is a 1.
So now we have .1 (decimal) = .00011?? . . . (base 2) .

Step 6: We multiply by 2 once again, disregarding the whole number part of the previous result. Let's make an important observation here. Notice that this next step to be performed (multiply 2. x 2) is exactly the same action we had in step 2. We are then bound to repeat steps 2-5, then return to Step 2 again indefinitely. In other words, we will never get a 0 as the decimal fraction part of our result. Instead we will just cycle through steps 2-5 forever. This means we will obtain the sequence of digits generated in steps 2-5, namely 0011, over and over. Hence, the final binary representation will be.

.1 (decimal) = .00011001100110011 . . . (base 2) .
The repeating pattern is more obvious if we highlight it in color as below:

.1 (decimal) = .00011001100110011 . . . (base 2) .

http://cs.furman.edu/digitaldomain/more/ch6/dec_frac_to_bin.htm





  • We can construct binary fractions using a binary "point", in the same was as we do with decimal:


101.101
||| |||
||| ||2-3 (1/8)
||| |2-2  (1/4)
||| 2-1   (1/2)
||20     (1)
|21       (2)
        22        (4)
And so the above number represents 4 + 1 + 1/2 + 1/8 = 5 5/8 (5.625)

http://turing.cs.camosun.bc.ca/COMP166/resources/floatingpoint.html




  • Binary Numbering


0.101

= 0 X 20 + 1 X 2-1 + 0 X 2-2 + 1 X 2-3

= 0 + 1/2 + 0 + 1/8

= 4/8 + 1/8

= 5/8


http://cs.furman.edu/digitaldomain/more/binary/bin1.html




  • 1. Which of the following is the binary representation of 4 5/8?


A. 100.11

ANSWER: D


https://docs.google.com/viewer?a=v&q=cache:00oarkgsJgkJ:site.iugaza.edu.ps/lalsaedi/files/2010/02/Chapter_One.doc+&hl=tr&pid=bl&srcid=ADGEESjzXurOtyhphMb3gIqn3eIZoYb-rzzeM8VZfuwgjEkeUT3qz6Owdai6A5spFoV9glErHyRAj6EarlH-34TTNh2pLRWHfuR1FFwSmZMgIaTCnS1Frc-dZb873BWlEwdPq7zcNzVB&sig=AHIEtbRxYL1hEMxqJSLu9JaEE3mZTjp23w




  • Example: Convert decimal 44 to binary.


DIVIDE
44 / 2 = 22 remainder = 0
22 / 2 = 11 remainder = 0
11 / 2 =  5 remainder = 1
 5 / 2 =  2 remainder = 1
 2 / 2 =  1 remainder = 0
 1 / 2 =  0 remainder = 1


REVERSE THE ORDER OF REMAINDERS
The bits, in the order they were generated is 001101 Reversing the order of bits we get 101100. Properly padded with leading zeroes to fill out one byte, we get 01011000

http://www.inetdaemon.com/tutorials/basic_concepts/number_systems/binary/conversion.shtml




  • Example.  Convert the decimal number 29410 into its binary number equivalent.


Number 294 Dividing each number by "2" gives a result plus a remainder. The binary result is obtained by placing the remainders in order with the least significant bit (LSB) being at the top and the most significant bit (MSB) being at the bottom.
divide by 2
result 147 remainder 0  (LSB)
divide by 2
result 73 remainder 1
divide by 2
result 36 remainder 1
divide by 2
result 18 remainder 0
divide by 2
result 9 remainder 0
divide by 2
result 4 remainder 1
divide by 2
result 2 remainder 0
divide by 2
result 1 remainder 0
divide by 2
result 0 remainder 1  (MSB)

Then, the decimal to binary conversion gives the decimal number 29410 equivalent of 1001001102 in binary, reading from right to left.

http://www.electronics-tutorials.ws/binary/bin_2.html

The shift operators


The shift operators allow programmers to adjust an integer by shifting all of its bits to the left or the right.

The following diagram shows the affect of shifting a value to the left by one digit
  00001111  =  15
SHIFT LEFT
  00011110  =  30


Compound Assignment Operators
The shift operators have equivalents for compound assignment
These are used by adding an equals sign to the operator and using the number of bits to shift by as the operand.


int value = 240;             // 11110000

value >>= 2;      // Result = 60
value <<= 1;      // Result = 120


http://www.blackwasp.co.uk/CSharpShiftOperators.aspx

Wednesday, March 27, 2013

Data vs. Information



  • Data vs. Information


Data:
raw facts
no context
just numbers and text

Information:
data with context
processed data
value-added to data
summarized
organized
analyzed
http://www.google.com.tr/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&cad=rja&ved=0CDgQFjAB&url=http%3A%2F%2Fwww.cs.siena.edu%2F~ebreimer%2Fcourses%2Fcsis-114-s08%2Flectures%2FData%2520vs.%2520Information%2520(4).ppt&ei=qGZTUYbxCYjIswaYv4GgBg&usg=AFQjCNG67c6gZwgrpj3FEVUYSbNru5jdKQ&bvm=bv.44342787,d.Yms




  • Data:


Meaning
Data is raw, unorganized facts that need to be processed. Data can be something simple and seemingly random and useless until it is organized.
Example
Each student's test score is one piece of data

Information:

Meaning
When data is processed, organized, structured or presented in a given context so as to make it useful, it is called Information.
Example
The class' average score or the school's average score is the information that can be concluded from the given data

http://www.diffen.com/difference/Data_vs_Information

Binary-coded decimal(BCD)

  • Binary-coded decimal

In computing and electronic systems, binary-coded decimal (BCD) is a class of binary encodings of decimal numbers where each decimal digit is represented by a fixed number of bits, usually four or eight, although other sizes (such as six bits) have been used historically

As an example, encoding the decimal number 91 using uncompressed BCD results in the following binary pattern of two bytes:
Decimal:          9          1
Binary :  0000 1001  0000 0001

In packed BCD, the same number would fit into a single byte:
Decimal:     9    1
Binary :  1001 0001
https://en.wikipedia.org/wiki/Binary-coded_decimal




  • BCD to deciman conversion


Short for Binary Coded Decimal, BCD is also known as packet decimal and is numbers 0 through 9 converted to four-digit binary. Below is a list of the decimal numbers 0 through 9 and the binary conversion.

Using this conversion, the number 25, for example, would have a BCD number of 0010 0101 or 00100101. However, in binary, 25 is represented as 11001.

http://www.computerhope.com/jargon/b/bcd.htm

graph vs tree



  • Introduction

Realize that all trees are graphs. A tree is a special case of a graph, one whose nodes are all reachable from some starting node and one that has no cycles.
Graph (c) does not have any cycles, as one less edge than it does number of nodes, and all nodes are reachable. Therefore, it is a tree.
http://msdn.microsoft.com/en-us/library/ms379574(v=vs.80).aspx



  • A tree is a connected graph with no cycles

https://docs.google.com/viewer?a=v&q=cache:2B00UUiFWB0J:www.cs.cmu.edu/afs/cs.cmu.edu/academic/class/15251-f09/Site/Materials/Lectures/Lecture18/lecture18.pdf+&hl=en&pid=bl&srcid=ADGEESh21IGgvVbbit2jwxSTnGhgmrTQ7ygsouGco178oA5Zj-HGbftJXWYOo6zmIzJVrz1KflxLwogoo8SkPw6iQOVKvx0fJ6-yOdeZwucLjGfNtXr2MLtxnOwRQKyxN0QFE-R3pEMo&sig=AHIEtbTjJflUVZU-sehW22YfIRzxWuFFUg

A Tree is just a restricted form of a Graph.
Trees have direction (parent / child relationships) and don't contain cycles.
They fit with in the category of Directed Acyclic Graphs (or a DAG)
http://stackoverflow.com/questions/7423401/whats-the-difference-between-the-data-structure-tree-and-graph

Tree is a hierarchical model.
Graph is a network model.
http://freefeast.info/difference-between/difference-between-trees-and-graphs-trees-vs-graphs/

Infix to Postfix Conversion

  • Infix to Postfix Conversion : 


Infix String : a+b*c-d
Postfix String : abc*+d-
http://scriptasylum.com/tutorials/infix_postfix/algorithms/infix-postfix/index.htm



  • Infix to Postfix Notation

http://www.youtube.com/watch?v=rA0x7b4YiMI


  • Infix to Postfix Notation

http://www.youtube.com/watch?v=1X_li3efgDI&feature=related



  • Insert-sort with Romanian folk dance

https://www.youtube.com/watch?v=ROalU379l3U


  • Algorithms #2 - Insertion Sort

https://www.youtube.com/watch?v=Fr0SmtN0IJM

Tuesday, March 26, 2013

Binary search algorithm

  • Binary search algorithm

In computer science, a binary search or half-interval search algorithm finds the position of a specified value (the input "key") within a sorted array.
In each step, the algorithm compares the input key value with the key value of the middle element of the array

If the keys match, then a matching element has been found so its index, or position, is returned. Otherwise, if the sought key is less than the middle element's key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the input key is greater, on the sub-array to the right

http://en.wikipedia.org/wiki/Binary_search_algorithm


  • Binary search algorithm


It means, that in worst case, algorithm makes 20 steps to find a value in sorted array of a million elements or to say, that it doesn't present it the array.


Algorithm

Algorithm is quite simple. It can be done either recursively or iteratively:

get the middle element;
if the middle element equals to the searched value, the algorithm stops;
otherwise, two cases are possible:
searched value is less, than the middle element. In this case, go to the step 1 for the part of the array, before middle element.
searched value is greater, than the middle element. In this case, go to the step 1 for the part of the array, after middle element.
   
   
Java

/**
 * searches for a value in sorted array
 *
 * @param array
 *            array to search in
 * @param value
 *            searched value
 * @param left
 *            index of left boundary
 * @param right
 *            index of right boundary
 * @return position of searched value, if it presents in the array or -1, if
 *         it is absent
 */
int binarySearch(int[] array, int value, int left, int right) {
      if (left > right)
            return -1;
      int middle = (left + right) / 2;
      if (array[middle] == value)
            return middle;
      else if (array[middle] > value)
            return binarySearch(array, value, left, middle - 1);
      else
            return binarySearch(array, value, middle + 1, right);        
}


http://www.algolist.net/Algorithms/Binary_search




  • İkili Arama Algoritması (Binary Search Algorithm)

http://www.bilgisayarkavramlari.com/2009/12/21/ikili-arama-algoritmasi-binary-search-algorithm/



  • İkili arama algoritması

http://tr.wikipedia.org/wiki/%C4%B0kili_arama_algoritmas%C4%B1



  • Binary Search - Example, Explanations, Algorithm & Code Part 2/2

http://www.youtube.com/watch?v=ZvJA-bdIvN8


Sunday, March 24, 2013

Reflection

  • Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine.

http://docs.oracle.com/javase/tutorial/reflect/index.html




  • Reflection allows the examination/modification of classes/objects at runtime. Personally I have only used it to implement a factory pattern. This is where there are a number of classes/subclasses that could be used to create objects at runtime. Based on some variable I can create the correct object by loading the class I want.


Class<?> c = Class.forName(someclass);
superTypeOfClass = c.newInstance();

I believe the instanceOf (isInstance() maybe) is also part of the Reflection API allowing you to discover the run time type of an object. Hope this helps.


Another example is Spring core framework's depedency injection. It is done through Reflection API.


Reflection API helps to manipulate classes and its properties at run time. You can create instance for class and can execute all methods (including private).
For example, To test private methods in JUnit.
http://www.linkedin.com/groups/What-is-Reflection-API-Can-70526.S.225700742?view=&srchtype=discussedNews&gid=70526&item=225700742&type=member&trk=eml-anet_dig-b_pd-ttl-cn&ut=0j-X2_38EiZRE1

Cocoa Touch



  • Cocoa Touch

Cocoa Touch is a UI framework for building software programs to run on the iPhone, iPod Touch, and iPad from Apple Inc.
https://en.wikipedia.org/wiki/Cocoa_Touch

Saturday, March 23, 2013

Java ORMs for MongoDB



  • MJORM (mongo-java-orm) - A MongoDB Java ORM

This project aims to provide a robust query api and ORM for MongoDB and the Java programming language
https://code.google.com/p/mongo-java-orm/


  • Spring Data - MongoDB

Spring Data for MongoDB is part of the umbrella Spring Data project which aims to provide a familiar and consistent Spring-based programming model for for new datastores while retaining store-specific features and capabilities
http://www.springsource.org/spring-data/mongodb


  • Morphia

Morphia is a lightweight type-safe library for mapping Java objects to/from MongoDB:
https://code.google.com/p/morphia/


  • jongo

http://jongo.org/


  • Hibernate OGM

Hibernate OGM is an attempt to store data in a NoSQL data grid using the Hibernate ORM engine rather than rewriting a JPA engine from scratch.
https://github.com/hibernate/hibernate-ogm

dependency injection

  • Google Guice
Google Guice is an open source software framework for the Java platform released by Google under the Apache License. It provides support for dependency injection using annotations to configure Java objects
Dependency injection is a design pattern whose core principle is to separate behavior from dependency resolution.
http://en.wikipedia.org/wiki/Google_Guice



Put simply, Guice alleviates the need for factories and the use of new in your Java code
Think of Guice's @Inject as the new new
https://code.google.com/p/google-guice/


  • Dependency Injection in Spring
Dependency injection (DI) is a design pattern in object-oriented computer programming whose purpose is to reduce the coupling between software components.
http://www.mkyong.com/spring/spring-dependency-injection-di/
http://en.wikipedia.org/wiki/Dependency_injection
http://www.youtube.com/watch?v=PGfs2CxDGM4



  • You can mix both, Constructor-based and Setter-based DI but it is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies.

ode is cleaner with the DI principle and decoupling is more effective when objects are provided with their dependencies. The object does not look up its dependencies, and does not know the location or class of the dependencies rather everything is taken care by the Spring Framework.

http://www.tutorialspoint.com/spring/spring_dependency_injection.html



  • Dependency Injection Types

Constructor Injection
The constructor arguments are injected during instance instantiation.
Setter Injection
This is the most favored method of dependency injection in Spring. Dependencies are “set” in the objects through setter methods defined in a Spring configuration file
Interface Injection
This is not implemented in Spring currently, but by Avalon. It’s a different type of DI that involves mapping items to inject to specific interfaces.
Spring uses the concept of a BeanFactory as its assembler, and it is the BeanFactory that manages the JavaBeans you have configured to run within it.
In Spring, the initialization of a bean by the framework is exactly equivalent to using the new keyword to instantiate an object in Java code
Once the framework has instantiated the object, it manages the scope of the bean, based on its configuration.

Because the IoC container is managing the beans, JNDI lookups that are typical in Java EE containers are no longer required, leaving your code container-agnostic and easier to unit test both inside and outside of the framework. And while you are coding to interfaces as part of good OO practice, Spring allows you to manage what implementations are used by leveraging dependency injection, resulting in cleaner, decoupled components.

All we need to do is inform Spring through an XML configuration file that the recorder bean is implemented by the LocalVoteRecorder class.
<bean id="recorder"      class="com.springindepth.LocalVoteRecorder" />

Then we simply map the recorder bean to the VotingBooth bean by setter injection in that beans definition.
<bean id="votingBooth"
      class="com.springindepth.VotingBooth">
    <property name="voteRecorder" ref="recorder"/>
</bean>

The IoC container manages java objects – from instantiation to destruction – through its BeanFactory.

http://www.springbyexample.org/examples/core-concepts-bean-management-through-ioc.html



  • Basic Bean Creation

A Spring bean in the IoC container can typically be any POJO (plain old java object).
Creating a Spring bean is as simple as coding your POJO and adding a bean configuration element to the Spring XML configuration file or annotating the POJO

             
public class DefaultMessage {

    private String message = "Spring is fun.";

    /**
    * Gets message.
    */
    public String getMessage() {
        return message;
    }

    /**
    * Sets message.
    */
    public void setMessage(String message) {
        this.message = message;
    }

}


  The bean element below indicates a bean of type Message – defined by the class attribute – with an id of 'message'.
  The instance of this bean will be registered in the container with this id.
  <bean id="message"    class="org.springbyexample.di.xml.DefaultMessage" />

  When the container instantiates the message bean, it is equivalent to initializing an object in your code with 'new DefaultMessage()'.


http://www.springbyexample.org/examples/intro-to-ioc.html



  • Basic Constructor Injection

we have our POJO and a basic configuration for the message bean, we can introduce our first dependency injection examples
Through the Spring beans XML file you can configure your bean to initialize with an argument for the constructor, and then assign the arguments.
Spring essentially “injects” the argument into your beans
This is referred to as constructor injection.

The following example passes in the String message using a constructor. The class is the same as the one in Basic Bean Creation except the default message on the message variable has been cleared and is now set to null. A single parameter constructor has been added to set a message.

public class ConstructorMessage {

    private String message = null;

    /**
    * Constructor
    */
    public ConstructorMessage(String message) {
        this.message = message;
    }

    /**
    * Gets message.
    */
    public String getMessage() {
        return message;
    }

    /**
    * Sets message.
    */
    public void setMessage(String message) {
        this.message = message;
    }

}


The configuration for this bean is exactly the same as in the previous example, but now we have a new element, the constructor-arg. The constructor-arg element injects a message into the bean using the constructor-arg element's value attribute.

<bean id="message"  class="org.springbyexample.di.xml.ConstructorMessage">
        <constructor-arg value="Spring is fun." />
    </bean>



http://www.springbyexample.org/examples/intro-to-ioc-basic-constructor-injection.html


  • Basic Setter Injection

The Spring IoC container also supports setter injection, which is the preferred method of dependency injection in Spring.

In most cases Spring will lowercase the first letter after “set” in the method name and use the rest of the method name as-is for deducing the property name. So for example if there is a setMessage() method in your class, the property name you would use when setting that property on a bean in the XML config is 'message'. If there is a setFirstName() method in your class, the property name you would use when setting the value is 'firstName'. 
In cases where the letters after “set” are all uppercase, Spring will leave the property name as uppercase. So if you have setXML() on a class, the property name would be 'XML'

public class SetterMessage {

    private String message = null;

    /**
    * Gets message.
    */
    public String getMessage() {
        return message;
    }

    /**
    * Sets message.
    */
    public void setMessage(String message) {
        this.message = message;
    }

}
  
  
  The property element is used to define the setter injection: 
  
  <bean id="message" class="org.springbyexample.di.xml.SetterMessage">
        <property name="message" value="Spring is fun." />
    </bean>

http://www.springbyexample.org/examples/intro-to-ioc-basic-setter-injection.html


  • Reference Injection
Values can also be injected by reference 
one bean definition can be injected into another.
To do this, you use the constructor-arg or property's ref attribute instead of the value attribute

  the first bean definition is a java.lang.String with the id springMessage
  
  <bean id="springMessage" class="java.lang.String">
        <constructor-arg value="Spring is fun." />
  </bean>
  
  
  It is injected into the second bean definition by reference using the property element's ref attribute.
  
  <bean id="message"  class="org.springbyexample.di.xml.SetterMessage">
        <property name="message" ref="springMessage" />
  </bean>
  
  http://www.springbyexample.org/examples/intro-to-ioc-reference-injection.html


  •   Spring Constructor-based Dependency Injection
  
  Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.
  
  
package com.tutorialspoint;

public class SpellChecker {
  public SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
  }

  public void checkSpelling() {
      System.out.println("Inside checkSpelling." );
  }
  
}

<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="com.tutorialspoint.SpellChecker"></bean>



package com.tutorialspoint;

public class TextEditor {
  private SpellChecker spellChecker;

  public TextEditor(SpellChecker spellChecker) {
      System.out.println("Inside TextEditor constructor." );
      this.spellChecker = spellChecker;
  }
  public void spellCheck() {
      spellChecker.checkSpelling();
  }
}


<!-- Definition for textEditor bean -->
  <bean id="textEditor" class="com.tutorialspoint.TextEditor">
      <constructor-arg ref="spellChecker"/>
  </bean>
  
  
  To resolve this ambiguity, the order in which the constructor arguments are defined in a bean definition is the order in which those arguments are supplied to the appropriate constructor_based_dependency_injection
  
package x.y;

public class Foo {
  public Foo(int year, String name) {
      // ...
  }
}
  

  <beans>
  <bean id="foo" class="x.y.Foo">
      <constructor-arg ref="bar"/>
      <constructor-arg ref="baz"/>
  </bean>

  <bean id="bar" class="x.y.Bar"/>
  <bean id="baz" class="x.y.Baz"/>
</beans> 
  
  
  one more case where we pass different types to the constructor_based_dependency_injection
  
  package x.y;

    public class Foo {
      public Foo(int year, String name) {
      // ...
      }
    }

    
    <bean id="exampleBean" class="examples.ExampleBean">
      <constructor-arg type="int" value="2001"/>
      <constructor-arg type="java.lang.String" value="Zara"/>
  </bean>
  
  
  the best way to pass constructor arguments, use the index attribute to specify explicitly the index of constructor arguments
  
  <bean id="exampleBean" class="examples.ExampleBean">
      <constructor-arg index="0" value="2001"/>
      <constructor-arg index="1" value="Zara"/>
  </bean>
  
  in case you are passing a reference to an object, you need to use ref attribute of <constructor-arg> tag and if you are passing a value directly then you should use value attribute
  
  
http://www.tutorialspoint.com/spring/constructor_based_dependency_injection.htm

Spring can instance objects in two ways: 

    Singleton: Instantiate only one object
    Prototype: Instantiate a new object everytime

        <bean id="ticketVendingMachine"
        class="com.studytrails.tutorials.springsingletonandprototype.TicketVendingMachine"
        scope="singleton" />

    <bean id="ticket"
        class="com.studytrails.tutorials.springsingletonandprototype.Ticket"
        scope="prototype" />
        
        
    http://www.studytrails.com/frameworks/spring/spring-singleton-and-prototype.jsp


  •     Spring Dependency Injection: Setter Injection
    
    
    the ATM class and Printer class can collaborate with each other to print the balance information for a bank account
    
    dependency where the reference of one class is held by another class
    
    The ATM class holds a reference to Printer class below. 
    
    private Printer printer;
    
    ATM class depends on Printer class
    
    public class ATM { 
    private Printer printer;
    
    
    The dependencies need to be 'resolved' before the desired functionality can be achieved
    By 'resolved' we mean that an instance of Printer class needs to be created and associated with the 'printer' member in ATM class
    When dependency resolution is not performed by the class itself but is left to be done by an external agent (e.g. Spring Framework) it is called dependency injection
    Spring will create an instance of the Printer class and associate the instance with the 'printer' member in ATM class
    as the 'printer' member in ATM class is private, the ATM class needs to expose its dependency to Spring for it to inject the Printer instance into the ATM class.
    
    If the ATM class exposes its dependency on Printer class as a setter method so that Spring can inject the Printer object then this is called as Setter injection
    
    public void setPrinter(Printer printer)
    
    ATM class takes in Printer class as a setter methods
    
    public class ATM {

    private Printer printer;

    public Printer getPrinter() {
        return printer;
    }
    public void setPrinter(Printer printer) {
        this.printer = printer;
    }
    
    
       
    
    http://www.studytrails.com/frameworks/spring/spring-setter-injection.jsp


  •  Spring Dependency Injection: Constructor Injection
    
    Spring will create an instance of the Printer class and associate the instance with the 'printer' member in ATM class. 
    as the 'printer' member in ATM class is private, the ATM class needs to expose its dependency to Spring for it to inject the Printer instance into the ATM class
    
    If the ATM class exposes its dependency on Printer class as a constructor so that Spring can inject it then this is called as Constructor injection
    
    public ATM(Printer printer) 
    
    ATM class takes in Printer class as a constructor argument 
    
    public class ATM {

    private Printer printer;
    
    public ATM(Printer printer) {
        this.printer = printer;
    }
    ...
    
    
    <bean id="printer" class="com.studytrails.tutorials.springcontructorinjection.Printer">
    </bean>
    
    <bean id="atm" class="com.studytrails.tutorials.springcontructorinjection.ATM">
            <constructor-arg ref="printer"/>
    </bean>    
        
    
    
    http://www.studytrails.com/frameworks/spring/spring-constructor-injection.jsp


  • IOC can be achieved by either of the following:
1. DI (Dependency Injection)
2. Service Locator


3 types of DI
1.1 Constructor Injection
1.2 Setter Injection
1.3 Interface Injection

http://programmers.stackexchange.com/questions/131451/difference-between-dependency-injection-di-inversion-of-control-ioc


  • Inversion of Control vs Dependency Injection [closed]
inversion of control is the principle where the control flow of a program is inverted: instead the programmer controls the flow of a program, the external sources (framework, services, other components) take control of it. It likes we plug something into something else

IoC is a generic term meaning rather than having the application call the methods in a framework, the framework calls implementations provided by the application.
DI is a form of IoC, where implementations are passed into an object through constructors/setters/service look-ups, which the object will 'depend' on in order to behave correctly.

IoC without using DI, for example would be the Template pattern because the implementation can only be changed through sub-classing.

DI Frameworks are designed to make use of DI and can define interfaces (or Annotations in Java) to make it easy to pass in implementations.

IoC Containers are DI frameworks that can work outside of the programming language. In some you can configure which implementations to use in metadata files (e.g. XML) which are less invasive. With some you can do IoC that would normally be impossible like inject implementation at pointcuts.

Inversion of Control (IoC) means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source (for example, an xml configuration file).

Dependency Injection (DI) means that this is done without the object intervention, usually by a framework component that passes constructor parameters and set properties.


http://stackoverflow.com/questions/6550700/inversion-of-control-vs-dependency-injection

Calypso


Calypso
Calypso Technology offers financial institutions and corporate treasuries an integrated trading, risk and processing platform for derivatives and treasury product which provides the most solid foundation for future business growth.
http://www.calypso.com/

Disruptor Pattern



  • LMAX Disruptor

High Performance Inter-Thread Messaging Library
The Disruptor is a general-purpose mechanism for solving a difficult problem in concurrent programming.
It works in a different way to more conventional approaches, so you use it a little differently than you might be used to.
For example, applying the pattern to your system is not as simple as replacing all your queues with the magic ring buffer.
http://lmax-exchange.github.com/disruptor/

Friday, March 22, 2013

Quartz



  • Quartz

Quartz is a full-featured, open source job scheduling service that can be integrated with, or used along side virtually any Java application - from the smallest stand-alone application to the largest e-commerce system.
Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs
http://quartz-scheduler.org/

JRebel


JRebel, formerly known as JavaRebel, is a plug-in for the Java Virtual Machine (JVM) that enables instant reloading of changes made to a Java class file.
JRebel is an alternative solution to updating classes which does not require a debugging session to be started
Instead it monitors the file system for changes and updates the classes in-memory.
This means that only classes compiled to ".class" files will be updated and changes to classes in JAR files will be ignored.
JRebel imposes a performance overhead on the application and should not be used in production or performance tests. It is meant to be a development tool only.

Starting from version 1.4, the Java Virtual Machine includes a hot swapping feature that allows developers to update the code on-the-fly during debugging
However hot swapping was limited to updating method bodies only, and trying to add methods and fields to classes would not succeed.

https://en.wikipedia.org/wiki/JRebel

Messaging


  • RabbitMQ?

Robust messaging for applications
Easy to use
Runs on all major operating systems
Supports a huge number of developer platforms
Open source and commercially supported
http://www.rabbitmq.com/



  • zeromq

The socket library that acts as a concurrency framework.
Faster than TCP, for clustered products and supercomputing.
Carries messages across inproc, IPC, TCP, and multicast.
http://www.zeromq.org/



  • Apache ActiveMQ

Apache ActiveMQ ™ is the most popular and powerful open source messaging and Integration Patterns server.
http://activemq.apache.org/

Thursday, March 21, 2013

lambda expression



  • Anonymous function

In computer programming, an anonymous function (also function constant, function literal, or lambda function) is a function (or a subroutine) defined, and possibly called, without being bound to an identifier.
Anonymous functions are convenient to pass as an argument to a higher-order function and are ubiquitous in languages with first-class functions such as Haskell.
Anonymous functions are a form of nested function, in that they allow access to the variable in the scope of the containing function (non-local variables).
Unlike named nested functions, they cannot be recursive without the assistance of a fixpoint operator (also known as an anonymous fixpoint or anonymous recursion).
http://en.wikipedia.org/wiki/Anonymous_function



  • Lambda calculus 

Lambda calculus  is a formal system in mathematical logic and computer science for expressing computation by way of variable binding and substitution
http://en.wikipedia.org/wiki/Lambda_calculus



  • What is a lambda expression?

Lambda is an operator used to denote anonymous functions
For more information on Lambda expressions in Java 8 check out the JSR-335
My First Java 8 Lambda
It’s getting late, I have downloaded the Java 8 JDK preview, written three pages of fluff on Lambda expressions but have yet to write one. So here goes, you can download Java 8 from Oracle at http://jdk8.java.net/lambda/.
http://diarmuidmoloney.wordpress.com/2011/12/10/my-first-java-8-lambda-expression/



  • Java 8 - Closures, Lambda Expressions Demystified 

http://frankhinkel.blogspot.com/2012/11/java-8-closures-lambda-expressions.html

Node.js


Node.js
Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.
http://nodejs.org/


Node.js
Node.js is a server-side software system designed for writing scalable Internet applications, notably web servers.
Programs are written on the server side in JavaScript, using event-driven, asynchronous I/O to minimize overhead and maximize scalability
http://en.wikipedia.org/wiki/Nodejs

Wednesday, March 20, 2013

Security information and event management (SIEM)

  • Security information and event management

Security Information and Event Management (SIEM) solutions are a combination of the formerly disparate product categories of SIM (security information management) and SEM (security event manager).
SIEM technology provides real-time analysis of security alerts generated by network hardware and applications.
SIEM solutions come as software, appliances or managed services, and are also used to log security data and generate reports for compliance purposes
http://en.wikipedia.org/wiki/Security_information_and_event_management


  • Security event manager


A security event manager (SEM) is a computerized tool used on enterprise data networks to centralize the storage and interpretation of logs, or events, generated by other software running on the network


Many systems and applications which run on a computer network generate events which are kept in event logs. These logs are essentially lists of activities that occurred, with records of new events being appended to the end of the logs as they occur. Protocols, such as Syslog and SNMP, can be used to transport these events, as they occur, to logging software that is not on the same host on which the events are generated


http://en.wikipedia.org/wiki/Security_event_manager



  • Security information management

Security information management (SIM) is the industry-specific term in computer security referring to the collection of data (typically log files; e.g. eventlogs) into a central repository for trend analysis

Most famous editors and solutions in the SIM/SEM Marketplace


    Alcatel-Lucent OA Safeguard
    Araknos Akab2
    BlackStratus Netforensics
    Cisco Cisco Security Manager
    Correlog Correlog Solution Suite
    CS Prelude/Vigilo
    EMC2 RSA Security
    HP ArcSight
    LogLogic Enterprise Virtual Appliance (formerly Exaprotect)
    LogRhythm SIEM 2.0 Security Intelligence
    NetIQ Security Manager
    NitroSecurity McAfee Enterprise Security Manager
    Novell Sentinel
    Q1 Labs Qradar (an IBM Company)
    SenSage Advanced SIEM and Log Management
    Splunk Splunk
    Symantec Security Information Manager
    TrustWave Intellitactics Security Manager for SIEM

http://en.wikipedia.org/wiki/Security_information_management
  • OSSIM, the Open Source SIEM

OSSIM is the most widely used SIEM offering, thanks in no small part to the open source community that has promoted its use. OSSIM provides all of the capabilities that a security professional needs from a SIEM offering, event collection, normalization, correlation, and incident response - but it also does far more. Not simply satisfied with integrating data from existing security tools, OSSIM is built on the Unified Security Management platform which provides a common framework for the deployment, configuration, and management of your security tools
http://communities.alienvault.com/


  • OSSIM

Open Source Security Information Management (OSSIM) provides a Security Information and Event Management (SIEM) solution. It is a one-stop solution and integrated the open source software’s NTOP, Mrtg, Snort, OpenVAS, and Nmap. OSSIM is a cost-effective solution in the area of monitoring network health and security of network/hosts compared to other propriety products.

OSSIM, AlienVault’s Open Source Security Information and Event Management (SIEM) product, provides you with a feature-rich open source SIEM complete with event collection, normalization, and correlation.
https://www.alienvault.com/products/ossim



  • Security Information and Event Management (SIEM) solutions


Security Information and Event Management (SIEM) solutions are a combination of the formerly disparate product categories of SIM (security information management) and SEM (security event manager)

SIEM technology provides real-time analysis of security alerts generated by network hardware and applications

http://en.wikipedia.org/wiki/Security_information_and_event_management



  • Eyes on Glass: End to End Monitoring

Organizations’ IT Infrastructure will function best when a continuous set of “eyes” are closely analyzing its health and availability; and proactively identifying the issues that keep the business up and running.
What plays a pivotal role in defining an overall IT monitoring strategy is ensuring a healthy data center along with end user experience coverage.
https://www.zensar.com/blogs/2015/12/eyes-on-glass-end-to-end-monitoring/


  • Next Generation SOC

The Techniques, Tactics and Procedures – The Cyber Kill Chain
real-time “eyes on glass” monitoring
http://www.itip.ph/uploads/events_files/IBM_SOC.pAp%E0%9C%90%9C%8C%81P%EC%3C%BFi%B3Y9%06a%D2%94%01%FF*Z%E3T%89R425%5B,%0C%C3%B2,%07%BD%8Ae%19%86%B1X%CC&%93%8C)%1F%CE%D7%9C%18%14%8B%EA%F4z%03F%A5i%23%CE%04%AD%25%B3%D04EQ%06%05S%5Bs)%8AH%91)B%D5cW%25


  • WHAT IS A MSSP (MANAGED SECURITY SERVICES PROVIDER?


A managed security service provider (MSSP) is an IT service provider that provides an organization with information security, cybersecurity monitoring and management, which may include policy development, security operation center, compliance services, incident response service, Virtual CISO, risk management program, vulnerability testing, penetration testing, security training and awareness, virus and spam blocking, intrusion detection, firewalls and virtual private network (VPN) management

MSSP technology offerings may include deploying, configuring, and/or managing the following technologies:

Intrusion prevention systems (IPS)
Web content filtering
Anti-virus (AV),
Anti-spam
Firewalls (UTMs, NGFWs, etc.)
VPN
Vulnerability scanning
Patch management
Data loss prevention (DLP)
Threat intelligence
Identity access management (IAM)
Privileged access management (PAM)

MSSP services may include:

Risk assessments and gap analysis
Policy development and risk management
Solution scoping
Solution/tool research and requisition
Solution implementation
Management of security systems
Configuration management
Security updates
Reporting, auditing, and compliance
Training and education

“Traditionally, MSSPs have been overwhelmingly focused on the perimeter,” assesses Keve. And, while MSSP offerings are evolving, even today, few MSSP’s tackle IAM.
Another differentiation between MSPs versus MSSPs is NOCs versus SOCs. MSPs frequently establish their own network operation center (NOC) from which they monitor and administrate over customer operations, MSSPs on the other hand typically establish a security operations center (SOC), which is responsible for protecting the infrastructure (networks, applications, databases, servers, etc.).


https://cybersecop.com/news/2018/10/4/what-is-an-mssp-managed-security-services-provider


  • Managed Security Services (MSS) and Eyes on Glass in the Real World

“Eyes on Glass” is a common saying when it comes to reviewing SIEM logs and managed services but is often misunderstood.
Technically “eyes on glass” requires a high degree of skill and capabilities to interact directly with unique client technologies, something not commonly included with managed services.

SIEM vs. MSSP
A Security Information and Event Management (SIEM) solution is designed to collect log data and provide real-time analysis towards alerting of events that require security management (e.g. virus infection or brute force attack attempt). A Managed Security Service Provider (MSSP) provides security monitoring and management which may include review, research, and response to alerts and data collected from a SIEM.
The MSSP does not actually have access to the “eyes on glass” endpoint product at this point, just the alert or log data that is sent to them from the client endpoint product and SIEM.
Scale and Efficiency
True “eyes on glass” is not a scalable service
It is far more efficient to configure logs to submit as much data as possible than have an employee or service provider perform “eyes on glass” investigations on one or more devices or software services used within an organization.

“Eyes on Glass” is sometimes required to dive deeper into a threat as one researches and responds to an incident. For daily operations the most cost-effective monitoring solution is to properly configure and tune detailed alerts sent to a SIEM and MSSP solution enabling research and response.
https://www.optiv.com/blog/managed-security-services-mss-and-eyes-glass-real-world



  • What is Managed Detection and Response? Definition, Benefits, How to Choose a Vendor, and More

Managed detection and response is a service that arose from the need for organizations, who lack the resources, to be more cognizant of risks and improve their ability to detect and respond to threats.

MDR is more focused on threat detection, rather than compliance.
The services are delivered using the provider's own set of tools and technologies,
Managed detection and response relies heavily on security event management and advanced analytics.

Managed Detection and Response vs. Managed Security Services
    Coverage. Managed security services can work with different types of event logs and contexts. The customer decides which of their security data is sent to the MSSP. With managed detection and response services, they only work with event logs that their own tools provide.
    Compliance reporting. If you need compliance reporting, go for a managed security service, as managed detection and response services rarely do compliance reports.
    The human touch. One of the upsides of managed detection and response offerings is that you get more human interaction with analysts. Managed security services rely on portals and e-mail rather than direct communication.
    Incident response. With managed detection and response, you only need a separate retainer if you want on-site incident response. Remote incident response is usually included in what you pay for the basic service. This is not true for many managed security services, where you need separate retainers for both onsite and remote incident response.

https://digitalguardian.com/blog/what-managed-detection-and-response-definition-benefits-how-choose-vendor-and-more
  • Managed Detection and Response

managed service detects and responds to threats with complete root-cause and kill chain visibility to deliver more effective security.
https://www.ibm.com/security/services/managed-detection-response



  • Managed Detection and Response

Managed detection and response (MDR) is an outsourced service that provides organizations with threat hunting services and responds to threats once they are discovered. It also involves a human element: Security providers provide their MDR customers access to their pool of security researchers and engineers, who are responsible for monitoring networks, analyzing incidents, and responding to security cases.

What challenges can MDR address?
While training and setting up dedicated security teams that can do full-time threat hunting may be feasible for larger organizations that can afford it, most companies will find it a difficult proposition given their resource limitations.

MDR integrates EDR tools in its security implementation, making them an integral part of the detection, analysis, and response roles.
Many of these alerts cannot be readily identified as malicious, and have to be checked on an individual basis. In addition, security teams need to correlate these threats, since correlation can reveal whether seemingly insignificant indicators all add up as part of a larger attack. This can overwhelm smaller security teams, and take away precious time and resources from their other tasks.

MDR aims to address this problem not only by detecting threats but also by analyzing all the factors and indicators involved in an alert.
One of the most important skills that security professionals need is the ability to contextualize and analyze indicators of compromise in order to better position the company against future attacks. Security technologies may have the ability to block threats, but digging deeper into the hows, whys, and whats of incidents requires a human touch.

MDR is designed to solve the problem of an organization’s cybersecurity skills gap. It tackles the issue of more advanced threats that an in-house IT team cannot completely address, ideally at a cost that is less than what the company will need to spend to build its own specialized security team. MDR can also offer the organization access to tools that it may not normally have access to

How do MDR providers compare with MSSPs?
In contrast with MDR providers, which can detect lateral movement within a network, MSSPs typically work with perimeter-based technology as well as rule-based detections to identify threats. Also, the kinds of threats that MSSPs deal with are known threats, such as vulnerability exploits, reoccurring malware, and high-volume attacks.
MSSPs have security professionals who perform log management, monitoring, and analysis, but often not at a very in-depth level.
In essence, MSSPs are able to manage an organization’s security but typically only at the perimeter level, and their analysis does not involve extensive forensics, threat research, and analytics.

In terms of service, MSSPs usually communicate via email or phone, with security professionals as a secondary access, while MDR providers carry out 24/7 continuous monitoring, which may not be offered by some MSSPs.
However, MSSPs still provide value to organizations. For example, managing firewalls and other day-to-day security needs of an organization’s network is a task that is more apt for an MSSP than an MDR provider, which offers a more specialized service.
Accordingly, MSSPs and MDR providers can work in conjunction with each other — with MDR providers focusing on the proactive detection and behavioral analysis of more advanced threats and giving remediation recommendations for organizations once the threats are discovered.

How does Trend Micro’s MDR work?
Trend Micro’s MDR provides a wide array of security services, including alert monitoring, alert prioritization, investigation, and threat hunting. It uses artificial intelligence models and applies them to endpoint, network, and server data in order to correlate and prioritize advanced threats. By investigating prioritized alerts, Trend Micro threat researchers can then work with organizations to provide a detailed remediation plan.

https://www.trendmicro.com/vinfo/us/security/definition/managed-detection-and-response


  • What is Real User Monitoring? How It Works, Examples, Best Practices, and More

Real User Monitoring is a type of performance monitoring that captures and analyzes each transaction by users of a website or application. It’s also known as real user measurement, real user metrics, end-user experience monitoring, or simply RUM.
It’s used to gauge user experience, including key metrics like load time and transaction paths, and it’s an important component of application performance management (APM).

Real User Monitoring vs. Synthetic Monitoring
Real User Monitoring is a form of passive web monitoring.We say “passive” because it relies on services that constantly observe the system in the background, tracking availability, functionality, and responsiveness

By contrast, Synthetic Monitoring is active web monitoring. In synthetic monitoring, behavioral scripts are deployed in a browser to simulate the path an end-user takes through a website. In addition, this active monitoring permits webmasters to test the application before launch. That makes it an essential tool for sites with a high volume of traffic. Unlike synthetic monitoring, RUM never rests.

Examples of RUM
Constant monitoring of a blog in the background to see when and where page load times increase
An end-user portal like a bank software system may use it to spot intermittent issues, like login failures that only occur under specific, rare conditions.
An app developer may use it to highlight failures in different platforms that don’t show up during pre-deployment testing.

Benefits of RUM
    Measure service level targets easily. It offers real-world measurement of key targets by tracking actual visits and delivering top-level data on actual use cases.
    Easily identify problems and better prioritize issues. It can replay user sessions and track transaction paths to surface hidden problems.
    Determine hitches at the network and page level. Problems at the lower levels of a website can hide like needles in a haystack. It can spotlight these problems even when they’re intermittent in nature or based on rare conditions.

Best Practices for RUM
Assess the Current Speed of the Website. F
Improve Mobile Testing Strategy.
Relate Performance to the Business.
https://stackify.com/what-is-real-user-monitoring/

  • SIEM Analyzes security alerts in real-time

SIEMs do three things:

One: Collect, normalize, and store log events and alerts from the organization’s network and
security devices, servers, databases, applications, and endpoints in a secure, central location
Investigators had determined that logging in to every system to
check for relevant log events was increasingly impossible. Also, if your logs were not secure,
you had no guarantee that an attacker hadn’t just deleted the entries to hide their activities

Two: Run advanced analytics on the data, both in real-time and across historical data, to
Identify potential security incidents that should be investigated by a human
The potential
incidents are prioritized by risk, severity, and impact.
these security analytics have
grown from employing Simple cross-correlation rules to monitoring for User-behavioral
anomalies, watching for known Indicators of Compromise IoC, and applying sophisticated
Machine learning models

Three: Prove that all of the security controls under the purview of the SIEM are in place and
effective

SIEM has evolved from an information platform, to a threat
intelligence center, to a fully integrated and automated center for security and network
operations. 


https://training.fortinet.com/pluginfile.php/1625608/mod_scorm/content/1/story_content/external_files/NSE%202%20SIEM%20Script_EN.pdf