Jumat, 31 Oktober 2014

Custom Camouflage: Octopus-Inspired Technology Will Help You Blend In...Or Not

I'M SO FANCYYY...
In some social settings, have you ever just wanted to blend into the walls and disappear? Maybe this will soon be possible thanks to new changeable camouflage technology being developed at the University of Illinois. 

As the BBC reports, a thin grid of 1-mm cells is controlled by a temperature-sensitive colored dye that is able to adapt to its environment. Derived from observations of creatures like octopi and cuttlefish, who are able to easily change colors to disguise themselves in the ocean to avoid predators and attract prey, the technology based itself in part on the idea of the animals' layered skin. In the grid, the bottom layer uses photosensors to reflect the desired pattern to actuators in the middle layer, which then control the colored pigment in the top level to change color at precisely 47 degrees Celsius. Similarly, an octopus would have these actuators embedded in its muscle flesh to control their color-changing outer skin.

Though the work is being accomplished in America (led by senior author Professor John Roberts), the word of this project has jumped the pond and gathered attention. Professor Anne Neville, the Royal Academy of Engineering Chair in Emerging Technologies at the University of Leeds, called Professor Roberts' work "very innovative and very interesting," as well as noting it was operating at a "very high standard."

The technology is not fully developed yet, and some hindrances still exist. The dye is currently only working in black and white, but will eventually take on other hues as the technology develops. Another issue is a power source for the camo, which is currently fueled externally, but could likely benefit from an element of solar cells.

The project is based off of information gleaned from "a collaboration between experts in biology, materials, computing and electrical engineering," according to Professor Roberts, but has wide potential for architectural, military, and even fashion applications. One day, you could use the hues to make your shirt any color you wanted, or really stand out in a room by reflecting its most stark colors, like a real-life Paint eyedropper feature for fashion.

Or, for those who still treasure their privacy in the face of ever-encroaching surveillance, you could just practice vanishing...


Homeland Security has no idea who this guy is.















Source:http://blog.agupieware.com/2014/08/custom-camouflage-octopus-inspired.html

If You Smell Something, Yell Something: Mass-Produceable "Electronic Nose" To Monitor For Gas Attacks

While relatively rare in the world of terror attacks, deadly gas remains a threat as an insidious, easily-deployed weapon of mass destruction. However, a new sensor can help curtail gas-based attacks and save lifes.

According to factor-tech.com, an "electronic nose" is in development at the Universitat Politècnica de València in Spain, to be used on public transport in an effort to identify deadly gases. Fifteen sensors in the device would alert an attached data acquisition system and computer (via sensitive metal oxide semiconductor sensors) to help discern the nature of a toxic airborne attack, such as sarin gas.

Cristian Olguín, a researcher on the project, explains, “The use of the electronic nose technology aims to create a device that detects these warfare gases in an efficient, quick, simple and cheap way.” The affordability and precision of the device would make it a popular option for monitoring the air in and around trains, planes, and many other hubs of public connection all over the world. The device is also small enough to be portable, which could have valuable applications for both military operators and civilians living in embattled areas.

Methodology of monitoring the volume of unpleasant-smelling commuters is unfortunately still limited to first-person analysis.

Our lives can go on like normal now!  Thanks, electronic nose!











Source:http://blog.agupieware.com/2014/08/if-you-smell-something-yell-something.html

Be Future-Fashion Forward With 3-D Printed Dresses

Science has determined that soon we'll be able to 3-D print out whole new organs for our bodies. But what are our freshly-invigorated forms going to wear? 3-D printing now has an answer for that too.

As shown by burlesque performer, "muse and model" Dita Von Teese in New York City, 3-D printing proved that isn't just in fashion, it's creating fashion. Her $100,000 3-D printed mesh dress, inspired by the ever-escalating Fibonacci sequence, conforms precisely to her form thanks to virtual technology imbuing the dress with next-generation design elements.

“It’s that continuous variation — managing the complexity of the subtle adjustments in form to respond to curvature of the body, how things tighten or narrow, where we need more flexibility or less flexibility of the mesh, all that was able to be tuned to a really high level,” says Francis Bitonti, who along with fellow designer Michael Schmidt created the dress using various 3-D imaging software programs.

According to wired.com, the process was elaborate. First, a 3-D model of the dress was built by Bitonti from an original sketch by Schmidt, using the Maya design program to custom tailor it to Von Teese's figure. Using Rhino, a software program that works to intricately detail surfaces, he fleshed out the 2,633 "rings" that interlock to form the garment. The dress was then sintered on an EOS P350 laser printer by Shapeways and manually assembled from the 17 different sections of material.

The dress, while expensive, could set the stage for a whole new category of couture. Shapeways designer Evangelist Duann Scott enthused, “Traditionally, all garments are either a weave or a stitch...with 3-D printing, we can…introduce something completely different. So we can grow designs rather than just using something that’s centuries-old technology. It’s a whole way to move forward in fashion and clothing and textiles.”

The 3-D technology of the future holds many promises...it can stop sweatshop labor yet quickly create necessary items when none are available...could its refinement and tailored-tech finally be able to solve the problem of finding that perfect pair of jeans, too?


Von Teese's fabulous fabricated frock.



Source:http://blog.agupieware.com/2014/08/be-future-fashion-forward-with-3-d.html

Mass Surveillance In Massachusetts: Boston Police Spy And Lie


In yet another installation of a police force overprotecting and serving themselves, it has recently come to light that every single attendee of the Boston Calling music festival in 2013 was under surveillance, the records of which were accessible through the darknet.  According to techdirt.com, the Boston Police Department then lied about their involvement in the entire operation.

While the event was clearly being documented by the media, various videographers, and amateur snapshooters alike, no one was availed of the information that they were being categorized and profiled during the festival.  Reporter Tim Cushing described it as such:

"What Boston Calling attendees (and promoters, for that matter) didn't know, however, was that they were all unwitting test subjects for a sophisticated new event monitoring platform. Namely, the city's software and equipment gave authorities a live and detailed birdseye view of concertgoers, pedestrians, and vehicles in the vicinity of City Hall on May 25 and 26 of 2013 (as well as during the two days of a subsequent Boston Calling in September). We're not talking about old school black and white surveillance cameras. More like technology that analyzes every passerby for height, clothing, and skin color."

Boston's Dig website found some even more unsettling information:

"Shockingly, these sensitive documents have been left exposed online for more than a year. Among them are memos written by employees of IBM, the outside contractor involved, presenting plans to use "Face Capture" on "every person" at the 2013 concert. Another defines a party of interest "as anyone who walks through the door."

Over 50 hours of footage was available for easy access. When confronted, the Boston police department denied any involvement, until they were called out by journalist Kenneth Lipp (who found the files.) Boston police were clearly seen in monitoring stations, being trained by IBM employees.

Fortunately, this forced out the truth, with mayoral press secretary Kate Walsh explaining to Dig in an email that a "pilot program" had indeed been tested, and of course, it was for our own good. The city was merely "looking at challenges such as permitting, basic services, crowd and traffic management, public safety, and citizen engagement through social media and other channels. These were technology demonstrations utilizing pre-existing hardware (cameras) and data storage systems."

Yes, that's right. They've had the ability to do this for a while. And nobody in the crowd - or even the promoters - knew.

Lipp continued to probe, uncovering a host of other sensitive information that the BPD had left out in nearly plain sight. Driver's license information, addresses, and other valuable informative material was easily accessed, which could have led to a bigger problem than anything the cops were looking out for with their spy system.

Despite events like the Boston Marathon bombings prompting authorities to seek more intel on members of large crowds, the fact that this system went live without any public knowledge or oversight, and was then lied about, doesn't make the average civilian feel any safer.  When civilians are treated like suspects for no reason, cops are acting like villains for no reason.  And what kind of society is served by villains?

Soon they'll start judging and profiling you by your music tastes, too.




Source:http://blog.agupieware.com/2014/08/mass-surveillance-in-massachusetts.html

Kamis, 30 Oktober 2014

Space Station Sunday: Supermoon!


The astronomical phenomena known as a "supermoon" occurred earlier this week, giving humans both on Earth and in space the chance to gaze on the biggest and brightest view of the moon seen in 20 years.  The supermoon occurs when the moon is at its perigee, a.k.a. the point closest in its orbit to the earth (the scientific name for the supermoon is "perigee moon.")  That put our nearest astronomical neighbor a mere 221,765 miles away from us, making it appear 30% brighter and 14% larger, according to a report published on www.independent.co.uk.

The supermoon was prominent indeed to our intrepid heroes on the ISS, and was captured in all of its super, moony glory by several astronauts.  Oleg Artemyev, a Russian cosmonaut aboard the ISS, snapped a series of images of what he called the "moonset", including the dramatic shot below.


German ISS astronaut Alexander Gerst also captured the event, posting an image of the supermoon behind the spacecraft to his Twitter feed.

Meanwhile NASA posted this patriotic take on the phenomena.

It's even red, white, and blue!  Of course, because Americans reached the moon first.


Moon enthusiasts (lunatics?) can check out even more cool supermoon pictures from weather.com.

The supermoon was so bright that even while it was waning, it outshone another major astronomical event last week:  the Perseid meteor shower.  But don't worry, astronaut Gerst had a good enough view to capture a subtle but still cool bit of that too, explaining "Here's what a shooting star looks like from the side!"

  You get to make extra wishes on shooting stars seen from space.




Source:http://blog.agupieware.com/2014/08/space-station-sunday-supermoon.html

Windowless Planes To Provide Amazing High-Res Views?

If you like flying so much that you can't bear to be away from the window seat, there may be an exciting new technological breakthrough you'll enjoy. A new design for a windowless airplane that recreates scenery in high definition inside the airplane cabin could revolutionize how you see the skies.

Technicon, a Parisian design company, has drawn accolades for their new IXION Windowless Plane Concept. Using exterior-mounted cameras, a 360-view of what's going on outside your aircraft could be displayed in glorious high-def for your in-flight entertainment.

According to mashable.com, design director Gareth Davies explained, “The ethos of the project is simple, to challenge current thinking, and propose something a little different, but not just a fantasy. It has to be credible and relevant, yet provoke discussion.”

Amorphous solar panels on a windowless fuselage would help to power the displays. The imagery itself could be anything - your flight over Kansas could magically become a leisurely lift over the Hawaiian islands, or even space-based scenes. Parallax balance technology could allow for separate viewing screens, if you absolutely HAD to watch some boring business presentation during your amazing all-seeing excursion.

While this is still a concept in development for the private planes of the future, it's nice to know that even something as awesome as flying can still get even better.

Wonder Woman has the right idea.


Source:http://blog.agupieware.com/2014/08/windowless-planes-to-provide-amazing.html

Believe The Hyperlapse: New App To Smooth Out GoPro Videos For Maximum Cool Viewing

For adventurous videographers everywhere, the GoPro is a thing of beauty.  The compact, tough little cameras operate in a variety of crazy environments - even underwater or hurtling through the air - and the high-def videos serve as souvenirs like no other of your excellent exploits.  Unfortunately, your gnarly ski vids end up looking a little TOO gnarly thanks to the shaking inherent to all of your extreme activity.  Thankfully, Microsoft is working on a software solution to this issue.

According to wired.com, a new app is in development to help smooth out your shots and gives your home movie a "hyperlapse" real movie feel.  This works by an algorithm analyzing your original trajectory, then restitching and blending the frames together to create a more fluid appearance.  "Hyperlapse" refers to the smoothed-out version of time lapse videos - a.k.a. the sped-up versions of your adventures that make the action move more swiftly, and now, not at the expense of watchability.  The technology is currently in development for a new app for Windows.

Learn more and check out some spectacular stabilized footage at research.microsoft.com/hyperlapse.






So even if you're attacked by sharks during a dive, you'll still look chill.



Source:http://blog.agupieware.com/2014/08/believe-hyperlapse-new-app-to-smooth.html

"Shut Up, Devil!" App To Help Save Your Soul


In this crazy and cruel modern world, it doesn't seem like one can get very far without hearing the voice of the devil (or however you may perceive the forces of evil) taunting and tempting you.  Now, a new app promises to offer a means of fighting back by using the force of the Lord (the Christian one.  Other lords' advice may vary.)

As reported by charismamag.com, the free "Shut Up, Devil!" app is there for you when the powers of darkness threaten their worst.  Users can choose from a variety of troubling topics, or indicate their exact feelings by typing them in.  Shut Up, Devil! then provides a Bible verse appropriate to remedying the situation, as well as a retort to set loose on Lucifer.

"The lies the devil launches at you will no longer influence you," app creator Kyle Winkler states.  To drive the message home, Shut Up, Devil! also includes reminder alarms that can be programmed to send you to your "favorited" in-app scripture cards whenever you feel you may need support during the day...be it when you're waking up feeling a little evil or slamming down drinks at last call.

Tell the Prince of Darkness to get behind thee and show him who's really boss, all with just the power of your smartphone!

Hell no, I'm not making out on the Ferris Wheel with you!  


Source:http://blog.agupieware.com/2014/08/shut-up-devil-app-to-help-save-your-soul.html

Rabu, 29 Oktober 2014

"Luddite Hipsters" Rejoice: Tom Hanks Has Created A Typewriter IPad App


Are you one of those retronauts who longs for the days of clacking keys and difficult deletes?  Are you even old enough to remember what a typewriter acted like?  Either way, Tom Hanks is bringing back the dubious heyday of typewriting, all via your suspiciously-slender and technologically-inclined iPad.

As theverge.com reports, Mr. Hanks has released a new app called "Hanx Writes" that replicates a frustration-free feel of the analog word processors.  Hanks, who is a devotee of typewriters (like some sort of sad spinoff of record collecting), has had his app reenact the moving pages and chattering keystrokes for the ultimate in what he calls "Luddite hipster" appeal.

The "crisp typeface" Hanks lauds is actually your standard typewriter font, with the added bonus of a "delete" button (although this can be turned off and replaced with the classic "XXXX" elimination...seriously.)

The app is free and was co-developed by the Hitcents agency.  So if you need an excuse to take up even more time working on your screenplay, now Forrest Gump is on your side.

Momma always said, "Life is like a box of a bunch of cumbersome letter and symbol keys that make a lot of noise and are hard to find ink for."


Source:http://blog.agupieware.com/2014/08/luddite-hipsters-rejoice-tom-hanks-has.html

Bubble Sort Algorithm in Java with Example



Bubble Sort is the first sorting algorithm I learned during my college day, and after so many years it's the one I remember by heart. It's kind of weird that one of the most popular sorting algorithm is also one of the worst performing sorting algorithm. Bubble sort's average case performance is in O(n^2), which means as the size array grows, the time it take to sort that array increases quadratic. Due to this reason, bubble sort is not used in production code, instead quick sort and merge sort are preferred over it. In fact, Java's own Arrays.sort() method, which is the easiest way to sort an array in Java also uses two pivot quicksort to sort primitive array and stable mergesort algorithm to sort object arrays. The reason or slow performance of this algorithm is excessive comparison and swapping, since it compare each element of array to another and swaps if it is on right side. Due to quadratic performance, bubble sort is best suited for small, almost sorted list e.g. {1, 2, 4, 3, 5} , where it just need to do one swapping. Ironically, best case performance of bubble sort, which is O(n) beats quicksort's best case performance of O(NlogN). Someone may argue that why teaching an algorithm which that poor performance, why not teach insertion or selection sort which is as easy as bubble sort, and performs better. IMHO, easiness of algorithm depends upon programmer as much as on algorithm itself. Many programmer will find insertion sort easier than bubble sort but again there will be a lot many who will find bubble sort easier to remember, including myself. This is true, despite many of them have used insertion sort unknowingly in real life, e.g. sorting playing cards in hand. Another reason for learning this sorting algorithm is for comparative analysis, how you improve algorithms, how you come up with different algorithms for same problems. In short, despite of all its shortcomings, bubble sort is still the most popular algorithm. In this tutorial, we will learn how bubble sort works, complexity and performance of bubble sort algorithm,  implementation and source code in Java and a step by step example of bubble sort.








How Bubble Sort Algorithm works


If you are the one who focus on names, then you might have got an idea how bubble sort works. Just like a bubble comes up from water, in bubble sort smallest or largest number, depending upon whether you are sorting array on ascending or descending order, bubbles up towards start or end of the array. We need at least N pass to sort the array completely and at the end of each pass one elements are sorted in its proper position. You can take first element from array, and start comparing it with other element, swapping where it's lesser than the number you are comparing. You can start this comparison from start or from end, as we have compared elements from end in our bubble sort example. It is said that a picture is worth more than a thousand word and it's particularly true in case of understanding sorting algorithm. Let' see an step by step example to sort array using bubble sort, as I said after each pass largest number is sorted.




Bubble Sort Example in Java



In this array, we start from index 0, which is 5 and starts comparing elements from start to end. So first element we compare 5 is 1, and since 5 is greater than 1 we swap them ( because ascending order sorted array will have larger number towards end). Next we compare 5 to 6, here  no swapping because 6 is greater than 5 and it's on higher index than 5. Now we compare 6 to 2, again we need swapping to move 6 towards end. At the end of this pass 6 reaches (bubbles up) at the top of the array. In next iteration 5 will be sorted on its position and after n iteration all elements will be sorted. Since we compare each element with another, we need two for loops and that result in complexity of O(n^2).








FlowChart of Bubble Sort Algorithm


Another cool way to understand an algorithm is to draw it's flowchart. It will walk through each iteration in loop and how decisions are made during algorithm execution. Here is flowchart of our bubble sort algorithm, which complements our implementation of this sorting algorithm.




flowchart of bubble sort algorithm

Here we have integer array {9, 7, 3, 6, 2} and start with four variable i, j, temp and array length which is stored in variable n. We have two for loop, outer loop runs from 1 to n-1. Our inner loop runs from n-1 to i. Many programmer make mistake here, if you start outer loop with second element than make sure to use j>=i condition on inner loop, or if you start with first element e.g. i=0, make sure you use j>i to avoid ArrayIndexOutOfBound exception. Now we compare each element and swap them to move smaller element towards front of array. As I said depending upon your navigation direction either largest element will be sorted at highest index in first pass or smallest element will be placed in lowest index. In this case, after first pass, smallest number will be sorted. This loop runs until j>=i after than it finishes and i becomes i + 1. This whole process repeats until outer loop is finished and that time your array is sorted. In flowchart, a diamond box is used for decision making, which is equivalent of if-else statement in code. You can see here decision box is inside inner loop, which means we do N comparison in each iteration, totals to NxN comparisons.








Complexity and Performance of Bubble Sort Algorithm


As I said before compared to other sorting algorithm like quicksort, merge sort or shell sort, bubble sort performs poorly. These algorithm has average case complexity of O(NLogN), while average case complexity of bubble sort O(n^2). Ironically in best case bubble sort do better than quicksort with O(n) performance.  Bubble sort is three times slower than quicksort or mergesort even for n = 100 but it's easier to implement and remember. here is the summary of bubble sort performance and complexity :



Bubble sort Worst case performance       O(n^2)

Bubble sort Best case performance         O(n)

Bubble sort Average case performance    O(n^2)



You can further explore insertion sort and selection sort, which also does sorting in similar time complexity. By the you can not only sort the array using bubble sort but ArrayList or any other collection class as well. Though you should really use Arrays.sort() or Collections.sort() for those purpose.






Bubble Sort Implementation in Java


here is the Java program to implement bubble sort algorithm using Java programming language. Don't surprise with import of java.util.Array, we have not used it's sort method here, instead it is used to print arrays in readable format. I have created a swap function to swap numbers and improve readability of code, if you don't like you can in-line the code in the swap method inside if statement of inner loop. Though I have used main method for testing, as it demonstrate better, I would suggest you to write some unit test case for your bubble sort implementation. If you don't know how to do that, you can see this JUnit tutorial.



import java.util.Arrays;

/**
* Java program to implement bubble sort algorithm and sort integer array using
* that method.
*
* @author Javin Paul
*/

public class BubbleSort{

public static void main(String args[]) {
bubbleSort(new int[] { 20, 12, 45, 19, 91, 55 });
bubbleSort(new int[] { -1, 0, 1 });
bubbleSort(new int[] { -3, -9, -2, -1 });

}

/*
* This method sort the integer array using bubble sort algorithm
*/

public static void bubbleSort(int[] numbers) {
System.out.printf("Unsorted array in Java :%s %n", Arrays.toString(numbers));

for (int i = 0; i < numbers.length; i++) {
for (int j = numbers.length -1; j > i; j--) {
if (numbers[j] < numbers[j - 1]) {
swap(numbers, j, j-1);
}
}
}

System.out.printf("Sorted Array using Bubble sort algorithm :%s %n",
Arrays.toString(numbers));
}

/*
* Utility method to swap two numbers in array
*/

public static void swap(int[] array, int from, int to){
int temp = array[from];
array[from] = array[to];
array[to] = temp;
}

}


Output
Unsorted array in Java : [20, 12, 45, 19, 91, 55]
Sorted Array using Bubble sort algorithm : [12, 19, 20, 45, 55, 91]
Unsorted array in Java : [-1, 0, 1]
Sorted Array using Bubble sort algorithm : [-1, 0, 1]
Unsorted array in Java : [-3, -9, -2, -1]
Sorted Array using Bubble sort algorithm : [-9, -3, -2, -1]






How to improve Bubble Sort Algorithm


In interview one of the popular follow-up question is how do you improve a particular algorithm, and Bubble Sort is no different than that. If you wrote bubble sort like the one we have shown here, interviewer will definitely going to ask about how do you improve your bubble sort method. In order to improve any algorithm, you must understand how each step of that algorithm works, then only you will be able to spot any deficiency in code. If you follow the tutorial, you will find that array is sorted by moving elements to their correct position. In worst case situation if array is reverse sorted then we need to move every element, this will require n-1 passes, n-1 comparison in each pass and n-1 exchanges, but how about best case if array is already sorted, our existing bubble sort method is still going to take n-1 pass, same number of comparison but no exchange. If you observe carefully, you will find that after one pass through the array, the largest element will moved to the end of the array, but many other elements also moved toward their correct positions, as bubbles move toward the water’s surface. By leveraging this property, you can deduce that during a pass, if no pair of consecutive entries is out of order, then the array is sorted. Our current algorithm is not taking advantage of this property. If we track exchanges then we can decide whether additional iteration over array is needed or not. Here is an improved version of Bubble Sort algorithm, which will only take 1 iteration and n-1 comparison in best case, when array is already sorted. This will also improve Bubble sort's average case performance, as compared to our existing method which will always take N - 1 passes.



    /*
* An improved version of Bubble Sort algorithm, which will only do
* 1 pass and n-1 comparison if array is already sorted.
*/

public static void bubbleSortImproved(int[] number) {
boolean swapped = true;
int last = number.length - 2;

// only continue if swapping of number has occurred
while (swapped) {
swapped = false;

for (int i = 0; i <= last; i++) {
if (number[i] > number[i + 1]) {

// pair is out of order, swap them
swap(number, i, i + 1);

swapped = true; // swapping occurred
}
}

// after each pass largest element moved to end of array
last--;
}

}






Now let's test this method for two input, one in which array is sorted (best case) and other on which only one pair is out of order. If we pass int array {10, 20, 30, 40, 50, 60} to this method,  initially will go inside while loop and make swapped=false. Then it will go inside for loop. when i =0 it will compare number[i] to number[i+1] i.e. 10 to 20 and check if 10 > 20, since it's not it will not go inside if block and no swapping will be occurred. When i=1, it will compare 20 > 30 again no swapping, next when i =2 30> 40 which is false so no exchange again, next i =3 so 40> 50, which is again false, so no swapping. Now last pair comparison i=4, it will compare 50 > 60 again this is false, so control will not go inside if block and no exchange will be made. Because of that swapped will remain false and control will not go inside while loop again. So you know that your array is sorted just after one pass.



Now consider another example, where just one pair is out of order, let's say String array names = {"Ada", "C++", "Lisp", "Java", "Scala"}, here only one pair is out of order e.g. "Lisp" should come after "Java". Let's see how our improved bubble sort algorithm work here. In first pass, comparison will continue without exchange until we compare "Lisp" to "Java", here "Lisp".compareTo("Java") > 0 will become true and swapping will occur, which means Java will go to the Lisp place, and Lisp will take Java's place. this will make boolean variable swapped=true, Now in last comparison on this pass, we compare "Lisp" to "Scala" and again no exchange. Now we will reduce last index by 1 because Scala is sorted at last position and will not participate  further. But now swapped variable is true, so control will again go inside while loop, and for loop but this time no exchanged will be made so it will not take another pass. Our array is now sorted in just two pass compared to N-1 pass of earlier implementation. This bubble sort implementation is much better and even perform better than Selection sort algorithm in average case because, now sorting is not proportional to total number of elements but only with number of pairs which are out-of-order.



By the way to sort String array using Bubble Sort, you need to overload BubbleSortImproved() method to accept String[] and also need to use compareTo() method to compare two String object lexicographically. Here is Java program to sort String array using Bubble Sort :



import java.util.Arrays;

class BubbleSortImproved {

public static void main(String args[]) {

String[] test = {"Ada", "C++", "Lisp", "Java", "Scala"};
System.out.println("Before Sorting : " + Arrays.toString(test));
bubbleSortImproved(test);
System.out.println("After Sorting : " + Arrays.toString(test));
}

/*
* An improved implementation of Bubble Sort algorithm, which will only do
* 1 pass and n-1 comparison if array is already sorted.
*/

public static void bubbleSortImproved(String[] names) {
boolean swapped = true;
int last = names.length - 2;

// only continue if swapping of number has occurred
while (swapped) {
swapped = false;

for (int i = 0; i <= last; i++) {
if (names[i].compareTo(names[i + 1]) > 0) {

// pair is out of order, swap them
swap(names, i, i + 1);

swapped = true; // swapping occurred
}
}

// after each pass largest element moved to end of array
last--;
}

}

public static void swap(String[] names, int fromIdx, int toIdx) {
String temp = names[fromIdx]; // exchange
names[fromIdx] = names[toIdx];
names[toIdx] = temp;
}

}

Output:
Before Sorting : [Ada, C++, Lisp, Java, Scala]
After Sorting : [Ada, C++, Java, Lisp, Scala]




Which one is better Selection Sort vs Bubble Sort?


Though both Selection Sort and Bubble sort has complexity of O(n^2) in worst case. On average, we expect the bubble sort to perform better than Selection sort, because bubble sort will finish sorting sooner than the selection sort due to more data movements for the same number of comparisons, because we compare elements in pair on Bubble Sort. If we use our improved implementation Bubble Sort then a boolean test to not enter on while loop when array gets sorted will also help. As I said, The worst case of the bubble sort happens when the original array is in descending order, while in best case, if the original array is already sorted, the bubble sort will perform only one pass whereas the selection sort will perform N - 1 passes. Given this, I think on average Bubble sort is better than Selection sort.





That's all about Bubble Sort in Java. We have learned how bubble sort algorithm works and how do you implement it in Java. As I said, it is one of the simplest sorting algorithm and very easy to remember, but also it doesn't have any practical use apart from academics and in data structure and algorithm training classes. It's worst case performance is quadratic which means it not suitable for large array or list. If you have to use bubble sort, it's best suited for small, already sorted array in which case it has to very few swapping and it's performance is in O(n). If you love algorithms, you can see this problem of finding cycle on linked list























Source:http://javarevisited.blogspot.com/2014/08/bubble-sort-algorithm-in-java-with.html

Your Security, Your Secretary, and Your Sacajawea: New &quot;Smart&quot; Motorcycle Helmet Protects, Takes Calls, Provides GPS


Do you enjoy motorcycling but long for the creature comforts (like hearing audible music, making phone calls, and monitoring rear-view cameras) afforded by some cars?  According to bgr.com, the new Skully AR-1 "smart" motorcycle helmet will bring you the best of both worlds.

Skully, which was created thanks to a crowdsourcing initiative, has been heralded as "the helmet for the digital age," by Popular Science.  It was one of this year's top 10 inventions, according to CNN.  And if you don't believe the media hype, believe the masses:  the $250,000 development goal was met two and a half times over...in one day.

Each Skully features an E-tint visor that acts as a heads up display, offering GPS maps and a 180-degree rearview camera (for watching our for rival biker gangs, obviously.)   An in-helmet Bluetooth connection allows for music and phone calls to be dealt with hands-free.  A 9-hour battery ensures you can go on long treks with your tech still intact.

This most badass of bike helmets comes in Matte Black (*insert Darth Vader noises*) or Gloss White, and currently retails for $1,399.  The first models ship in May 2015, so you still have some time to learn how to ride a motorcycle (unfortunately Skully is not quite smart enough to teach you...yet.)

Look, it's as close to an X-Wing pilot helmet as you're going to get for right now, okay?




Source:http://blog.agupieware.com/2014/08/security-secretary-and-sacajawea-new.html

Hi From The Sky: New Satellite To Spy On You, Down To 10-Inch Parameters


That feeling that someone is watching you has never been more apt.  In addition to the countless cameras on the streets, in vehicles, in stores, on phones, and wherever else instant-documentation is for some reason now necessary, there is now also a seriously strong satellite checking you out.

As reported by engadget.com, the "high-resolution, public imaging satellite"  WorldView-3 is set to launch tomorrow, providing imaging data down to a frankly creepy 10-inch range.  Parent company DigitalGlobe intends to sell this information to its customers like Microsoft and Google for better street imaging, but grandparent company Lockheed Martin is a well-known U.S. government ally.  Take that as you will, as they take your pictures.

The technology is supposedly also set to aid farmers, mineral-deposit seekers, environmental protectors and others, so apparently we're just going to have to pretend this is all altruistic, as if we had a choice.  And maybe it's really not all bad...at least for exhibitionists, your nude sunbathing just got a little more exciting.

It can also see spectra that your eyes cannot.  But it's still probably just watching you.




Source:http://blog.agupieware.com/2014/08/hi-from-sky-new-satellites-to-spy-on.html

Selasa, 28 Oktober 2014

Python: What to do after you&#39;ve finished Code Academy?

One of the most common beginner questions I see in Python programming forums is from people asking what to do once they’ve completed Code Academy’s Python training course. The possibilities are virtually limitless and may seem overwhelming at first, especially if you have little prior programming experience. It’s a bit like finding yourself in a foreign country where you know enough of the local language to just get by, but not enough to really find your way around. I certainly don’t claim to have the map, but in this post I’ll try to point out a few landmarks that might help some folks get their bearings. 

The Code Academy course covers the basics of Python syntax and data structures, and provides a quick introduction to more advanced topics like the use of list comprehensions, bitwise operators, classes, file input/output etc. Along the way, the student also completes a handful of small projects to demonstrate how this newly acquired knowledge can be put to use, for example, a pig latin translator, a Battleship game simulator and so on.

But the big question is: what next?! There is no straightforward answer to this question, as it depends on a number of highly individual variables such as your level of prior programming knowledge and experience, your interests, your goals and motivations for learning programming in general and Python in particular, not to mention the amount of time you are able to devote to study and practice, to name just a few. For the sake of simplicity, what follows is targeted to a beginner who has recently completed an introductory Python crash course such as Cody Academy’s Python Track, or Learn Python the Hard Way, has little or no prior programming experience, and can devote a modest amount of time to study and practice on a regular basis. 

As a natural language instructor, I can almost always tell when a student has not done any homework or practice over a long weekend: they are already starting to get rusty! Probably the single most important thing to do after an introductory course like Code Academy’s is to reinforce the lessons learned, and to do it on a consistent basis. This will help to shore up all that newly acquired knowledge and provide a sturdier basis to extend it and expand on it. This could be anything from reading a textbook to watching a series of lectures, or following along with another tutorial, exploring other areas of the Python universe, tinkering with your own little programming projects, or some combination of these, or even all of the above. 

You’ll likely also find that these activities are themselves mutually reinforcing: while working on your own projects, you’ll realize when you’ve hit a wall and need to consult some documentation or a textbook, or seek out a new library or framework to help achieve your goal; reading through a textbook you’ll be exposed to new ideas that you can experiment with in the interpreter or in your own little projects; working through a tutorial, you might find a piece of code that interests you and which you start to tweak on your own to see how it works and to experiment with extending it or expanding on it in some way, shape or form.  

If Code Academy was your first exposure to programming in general, it might be a good idea to consider working through a general introductory textbook (or even an introductory course!) on computer science. This will provide you with a basis in the fundamentals of the discipline as a whole, things that are more or less the same across all programming languages. 

So far as introductory textbooks go, many people, myself included, highly recommend Think Python: How to Think Like a Computer Scientist, which is freely available online.   This book is required reading for a number of well known introductory computer science courses such as MIT’s Introduction to Computer Science and Programming, and was written for the express purpose of introducing students to the field. It is highly readable, provides a review of basic syntax and covers intermediate as well as more advanced topics, along with a series of chapters on object-oriented programming and design. 

Along similar lines, if you have the time to devote to it, I highly recommend MIT’s Introduction to Computer Science class. All the lectures, recitation sections and course materials are freely available online in their entirety, and the course uses Python as its pedagogical language of choice. For more information on this course, see our previous post Teach Yourself Python in Less Than Four Months, which provides a learning plan that uses the MIT course as its guide.  

Okay, but what if you are not the type who likes to curl up with a good textbook, and don’t have the time to slog through a college level introduction to computer science course, but want to delve more deeply into Python itself? What then? In this case, you might consider working through another general introductory tutorial on Python programming, this will help consolidate the knowledge you’ve already gained and also likely expose you to more beginner and intermediate level aspects of the language and the programming process. There are tons of such resources available online. Here are a few that I've found quite helpful:
"Bah," some may say, "I'm bored of mechanically typing out tutorial code! I want to experiment, but I'm not sure where to begin!" Not to worry, there's tons of stuff out there, you just have to know where to look. For those who want to jump right in to real problem solving, your first stop should be the Programming Mega Project List. This is a list of around 100 practical programming projects that can be solved in any programming language. The difficulty level of the various projects ranges from beginner to advanced and the list broken down into basic categories such as math, algorithms, networking, text, web, and so on. Find one that interests you, tackle it and repeat.

Other people may find it rather uninteresting to solve problems for the sake of problem solving, and would rather explore Python itself. The standard library is your friend! One of the great things about programming is that it can make your life a whole lot easier. If you stick with programming, one thing you will learn rather quickly is that programmers are lazy and proud of it. If I had a dime for every time I’ve come across a talk or article on programming which proclaimed that programmers are lazy, I’d probably have like $10 by now.  I guarantee there is some absurd, repetitive task that you have to complete on a regular basis that can be automated with a relatively simple Python script. For these everyday routines, there is also very likely a standard library module that can aid you in your endeavor. Relevant xkcd:


Maybe you work in an office and have a tedious spreadsheet task you have to complete on a regular basis. Automate it with the csv module. Perhaps you’re in a band and hate writing up set lists, write a random set list generator with the random module. Maybe you like sports or finance, and are constantly looking up scores or quotes. Write a command line app to grab them from your favorite online source using urllib without having to open a browser.  If you’re a news junky, you could consider writing your own RSS headline aggregator with urllib and one of the XML modules. The possibilities are literally limitless. 

Last but not least, as a beginner Python programmer, you will most definitely want to begin checking out the many great frameworks that have been built around the language.  "A software framework is a universal, reusable software platform to develop software applications, products and solutions," says Wikipedia. At the most basic level, a software framework is a library or set of libraries that provide generic functionality for routine tasks to aid in the development of applications and programming projects. In the Python universe there are tons of frameworks to explore, such as web frameworks for the development of web applications, GUI frameworks for development of graphical user interfaces for desktop applications, and so on. Some of my favorites:
Well, that concludes our tour of some noteworthy landmarks in the Python programming space. As always, feel free to provide your own favorite resources or suggestions in the comments.

Source:http://blog.agupieware.com/2014/08/python-what-to-do-after-youve-finished.html

How to find all Pairs in Array of Integers whose Sum is equal to a given Number



Practising coding problems are very important to do well in any programming interview. You should at your best on data-structures like array, linked list, and string to clear any programming interview, and believe me you can not do this in one day or one week. It's rather long process of learning through coding, and that's where these small coding problems helps. Today, we are going to look at another interesting programming question from array; write a program to find all pairs of integers whose sum is equal to a given number. For example if input integer array is {2, 6, 3, 9, 11} and given sum is 9, output should be {6,3}. Sounds simple? may be, but this exactly question has appeared in technical interview at Amazon, Microsoft, Facebook and couple of other fortune five tech companies in past. Many of you might already heard about this question and some of you may already know the solution of this problem as well, but it's not enough to know just the answer. In a programming interview, many things matter apart from correct solution. For example, first thing Interviewer look is whether candidate can ask right questions or not. So before jumping straight to coding, spare a second or two to think about problem and clear any doubt you may have. For example, you can ask following questions based upon problem statement given above :






  • Does array contains only positive or negative numbers?

  • What if same pair repeats twice, should we print it every time?

  • Is reverse of pair is acceptable e.g. can we print both (4,1) and (1,4) if given sum is 5.

  • Do we need to print only distinct pair? does (3, 3) is a valid pair for given sum of 6?

  • How big the array is?


Many programmers afraid to ask questions instead they like to assume about it, but during coding interview IMHO it's always better to ask questions. First it shows that you have not mugged the answer and second it demonstrate that you have ability to think through a problem, which is a very important quality of any professional programmer. Now let's go back to question, for simplicity we can assume that we just need to print a pair of integers once or twice depending upon their occurrence, but pair has to be distinct, (2,2) or (3, 3) is not valid pair.






3 Solution to Find Pair Of Integers in Array whose Sum is Given Number


The first solution which comes in my mind is our friend brute-force, naive but genuine. You take one number from array and then loop through array and output pairs which is equal to given sum. You do this for all numbers in first array, as shown in following Java program :



import java.util.Arrays;

/**
* Java Program to find pairs on integer array whose sum is equal to k
*
* @author WINDOWS 8
*/

public class ProblemInArray{

public static void main(String args[]) {
int[] numbers = { 2, 4, 3, 5, 7, 8, 9 };
int[] numbersWithDuplicates = { 2, 4, 3, 5, 6, -2, 4, 7, 8, 9 };
prettyPrint(numbers, 7);
prettyPrint(numbersWithDuplicates, 7);
}

/**
* Prints all pair of integer values from given array whose sum is is equal to given number.
* complexity of this solution is O(n^2)
*/

public static void printPairs(int[] array, int sum) {

for (int i = 0; i < array.length; i++) {
int first = array[i];
for (int j = i + 1; j < array.length; j++) {
int second = array[j];

if ((first + second) == sum) {
System.out.printf("(%d, %d) %n", first, second);
}
}

}
}
/**
* Utility method to print input and output for better explanation.
*/

public static void prettyPrint(int[] givenArray, int givenSum){
System.out.println("Given array : " + Arrays.toString(givenArray));
System.out.println("Given sum : " + givenSum);
System.out.println("Integer numbers, whose sum is equal to value : " + givenSum);
printPairs(givenArray, givenSum);
}

}

Output:
Given sum : 7
Integer numbers, whose sum is equal to value : 7
(2, 5)
(4, 3)
Given array : [2, 4, 3, 5, 6, -2, 4, 7, 8, 9]
Given sum : 7
Integer numbers, whose sum is equal to value : 7
(2, 5)
(4, 3)
(3, 4)
(-2, 9)



This solution is correct but it's time complexity is very hight, O(n^2), which means Interviewer will surely ask you to improve your answer and come up with solution whose complexity is either O(1), O(n) or O(nLog(n)). So let's dig deeper to improve this answer. In order to find two numbers in an array whose sum equals a given value, we probably don't need compare each number with other. What we can do here is to store all numbers in a hashtable and just check if it contains second value in a pair. For example, if given sum is 4 and one number in pair is 3, then other must be 1 or -7. Do you remember the first question we asked, if array only contains positive numbers then we don't need to check for negative values in Map. How is this solution better than previous one? It would require less comparisons. Only N to iterate through array and insert values in a Set because add() and contains() both O(1) operation in hash table. So total complexity of solution would be O(N). Here is a Java program which find the pair of values in the array whose sum is equal to k using Hashtable or Set. In this program we have also written a utility method to generate random numbers in a given range in Java. You can use this method for testing with random inputs. By the way, random numbers are only good for demonstration, don't use them in your unit test. One more good thing you can learn from printPairsUsingSet() method is pre validation, checking if inputs are valid to proceed further.



import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
* Java Program to find two elements in an array that sum to k.
*
* @author WINDOWS 8
*/

public class ArraySumUsingSet {

public static void main(String args[]) {
prettyPrint(getRandomArray(9), 11);
prettyPrint(getRandomArray(10), 12);
}

/**
* Given an array of integers finds two elements in the array whose sum is equal to n.
* @param numbers
* @param n
*/

public static void printPairsUsingSet(int[] numbers, int n){
if(numbers.length < 2){
return;
}
Set set = new HashSet(numbers.length);

for(int value : numbers){
int target = n - value;

// if target number is not in set then add
if(!set.contains(target)){
set.add(value);
}else {
System.out.printf("(%d, %d) %n", value, target);
}
}
}

/*
* Utility method to find two elements in an array that sum to k.
*/

public static void prettyPrint(int[] random, int k){
System.out.println("Random Integer array : " + Arrays.toString(random));
System.out.println("Sum : " + k);
System.out.println("pair of numbers from an array whose sum equals " + k);
printPairsUsingSet(random, k);
}

/**
* Utility method to return random array of Integers in a range of 0 to 15
*/

public static int[] getRandomArray(int length){
int[] randoms = new int[length];
for(int i=0; i<length; i++){
randoms[i] = (int) (Math.random()*15);
}
return randoms;
}

}

Output:
Random Integer array : [0, 14, 0, 4, 7, 8, 3, 5, 7]
Sum : 11
pair of numbers from an array whose sum equals 11
(7, 4)
(3, 8)
(7, 4)
Random Integer array : [10, 9, 5, 9, 0, 10, 2, 10, 1, 9]
Sum : 12
pair of numbers from an array whose sum equals 12
(2, 10)




How to find two integers in Java array whose sum equal to given number

One more thing, here we are using HashSet but since HashSet in Java internally uses HashMap, it would not make any difference if use either of those data structure.By the this solution has few constraints, first it would need additional space of order O(n) to store numbers in Hashtable or Set, so you need additional space which could be problem if array is very large (remember the question we asked before writing solution). For a large array, you need a solution which doesn't require additional space, also known as in-place solution. If interviewer will ask you how do you find if two values in an array sum to a given value without any additional space, first solution will also not work because it's complexity is too high and it would too long to sort a large array. A solution with complexity e.g. O(n), O(logN) or O(NLongN) should work though. A more efficient in-place solution would be to sort the array and use two pointers to scan through array from both direction i.e. beginning and end. If sum of both the values are equal to given number then we output the pair and advance them. If the sum of two numbers is less than k then we increase the left pointer, else if the sum is greater than k we decrement the right pointer, until both pointers meet at some part of the array. The complexity of this solution would be O(NlogN) due to sorting. Remember to use a in-place sorting algorithm like quicksort to sort the array as we don't have additional space. Thankfully, Arrays.sort() method uses a two pivot quicksort algorithm to sort array of primitives.



import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
* Java Program to find all pairs on integer array whose sum is equal to k
*
* @author WINDOWS 7
*/

public class PrintArrayPairs {

public static void main(String args[]) {
prettyPrint( new int[]{ 12, 14, 17, 15, 19, 20, -11}, 9);
prettyPrint( new int[]{ 2, 4, 7, 5, 9, 10, -1}, 9);
}

/**
* Given a number finds two numbers from an array so that the sum is equal to that number k.
* @param numbers
* @param k
*/

public static void printPairsUsingTwoPointers(int[] numbers, int k){
if(numbers.length < 2){
return;
}
Arrays.sort(numbers);

int left = 0; int right = numbers.length -1;
while(left < right){
int sum = numbers[left] + numbers[right];
if(sum == k){
System.out.printf("(%d, %d) %n", numbers[left], numbers[right]);
left = left + 1;
right = right -1;

}else if(sum < k){
left = left +1;

}else if (sum > k) {
right = right -1;
}
}

}

/*
* Utility method to print two elements in an array that sum to k.
*/

public static void prettyPrint(int[] random, int k){
System.out.println("input int array : " + Arrays.toString(random));
System.out.println("All pairs in an array of integers whose sum is equal to a given value " + k);
printPairsUsingTwoPointers(random, k);
}

}

Output :
input int array : [12, 14, 17, 15, 19, 20, -11]
All pairs in an array of integers whose sum is equal to a given value 9
(-11, 20)
input int array : [2, 4, 7, 5, 9, 10, -1]
All pairs in an array of integers whose sum is equal to a given value 9
(-1, 10)
(2, 7)
(4, 5)





That' all on this array based interview question to find all pairs in an array of integers whose sum is equal to a given integer. We have seen three ways to solve this problem starting from simplest brute-force solution to acceptable O(N) with additional space and O(NLogN) in-place. If anyone like to do some more practice, I would suggest to write JUnit test cases for this problem, given set of constraints that only unique pair needs to be printed even if array contains duplicated and find bugs on these solution. Alternatively, you can also try to solve it's cousin question, given an array of integers check whether there are 3 numbers that sum up to 0 or given number. Remember more fun is in journey than reaching the destination :)



Exercises : 

1) Write JUnit tests for this problem and check if each of this solution passes those tests.

2) Come up with a better solution in terms of time and space complexity?

3) Find boundary conditions on which these solution breaks.























Source:http://javarevisited.blogspot.com/2014/08/how-to-find-all-pairs-in-array-of-integers-whose-sum-equal-given-number-java.html