Just run this:
$ git merge-base awesome master d931216adebf441dc7431f1a073baed8b4a1b20aAnd you'll get the SHA1 of the most recent common commit.
$ git merge-base awesome master d931216adebf441dc7431f1a073baed8b4a1b20aAnd you'll get the SHA1 of the most recent common commit.
git checkout -
to switch to the previous branch.# suppose we're at the branch 'master' now $ git checkout - Switched to branch 'awesome' # now let's go back to master $ git checkout - Switched to branch 'master'Yeah, that's pretty similar to a good old
cd -
.
git config --global alias.st status git config --global alias.co checkout git config --global alias.ci commitAnd you're done:
$ git ci --allow-empty -m "nice, we can commit with 'git ci' now"
amazing_function
and you want to measure its speed.time
, and looping n
times. Use:$ ipython In [1]: %timeit amazing_function('some', 'arguments') 100000 loops, best of 3: 13.4 µs per loop
say hello
say
command, ahem, says things.
It can even read your private SSH key out loud (warning: this is not very secure, someone can eavesdrop you private key):
cat ~/.ssh/id_rsa | sayOr your home directory:
ls | sayEven the cliboard content:
pbpaste | say
import ( "errors" "fmt" ) err := errors.New(fmt.Sprintf("my %s error", "awesome"))About 4000 golang projects do
errors.New(fmt.Sprintf(...
Don't do it, there is a better way:import ( "fmt" ) err := fmt.Errorf("my %s error", "awesome")You're welcome.
from setuptools import setup setup( name='yourapp', author='Your name', version='0.0.1', description='Your app', packages=['yourapp'], )When developing an application you often want to install it into system/virtualenv site-packages directory. At the same time you don't want to run
python setup.py install
after every time you make a change. There is a simple solution.cd
into directory containing setup.py and run pip install --editable .
pip install --editable <period>
. Trailing period is important.import java.time.DayOfWeek; import java.time.LocalDate; import static java.time.temporal.TemporalAdjusters.firstDayOfNextMonth; import static java.time.temporal.TemporalAdjusters.nextOrSame; LocalDate firstSundayOfNextMonth = LocalDate .now() .with(firstDayOfNextMonth()) .with(nextOrSame(DayOfWeek.SUNDAY));LocalDate.with method is remarkable.
import java.time.LocalDate; import java.time.format.DateTimeFormatter; LocalDate tomorrow = LocalDate.now().plusDays(1); tomorrow.format(DateTimeFormatter.ISO_DATE); // "2014-03-06"It's absolutely gorgeous.
DateTimeFormatter
class:
import java.time.format.DateTimeFormatter; tomorrow.format(DateTimeFormatter.ISO_DATE); // "2014-03-06" tomorrow.format(DateTimeFormatter.ISO_WEEK_DATE); // "2014-W10-5" tomorrow.format(DateTimeFormatter.ISO_ORDINAL_DATE); // "2014-066"
LocalDate
class has a signature of
factory method and this method has a signature (int, int, int)
or (int, java.time.Month, int)
:
import java.time.LocalDate; import java.time.Month; LocalDate date = LocalDate.of(2014, 3, 18); LocalDate sameDate = LocalDate.of(2014, Month.MARCH, 18);All right.
import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; LocalDateTime now = LocalDateTime.now(); LocalDateTime afterNow = now.plusHours(5).plusMinutes(61); long minutes = ChronoUnit.MINUTES.between(now, afterNow); // 361 long hours = ChronoUnit.HOURS.between(now, afterNow); // 6 long centuries = ChronoUnit.CENTURIES.between(now, afterNow); // 0We're really excited about the
ChronoUnit
class. It's the most advanced way to calculate the amount of time between two temporal objects.java.util.Date
is incredibly simple. Here I just call toInstant
, then atZone, and finally toLocalDate.
import java.time.LocalDate; import java.time.ZoneId; import java.util.Date; Date oldDate = new Date(114, 2, 18); // deprecated since 1.1 LocalDate brandNewDate = oldDate.toInstant() .atZone(ZoneId.systemDefault()) .toLocalDate(); // 2014-03-18 Date oldDateFromBrandNewDate = Date.from(brandNewDate .atStartOfDay() .atZone(ZoneId.systemDefault()) .toInstant()); // 2014-03-18So that's a brief update on date and time API.
public interface Language { default boolean hasLambdas() { return false; } }With typical legendary Java ease of use you just add the
default
modifier, provide an implementation and it works.public interface Language { static int getNumberOfLanguagesThatRunOnThreeBillionDevices { return 1; } }To give the finishing touch to the interfaces we've added stunning
@FunctionalInterface
annotation.@FunctionalInterface public interface Language { default boolean hasLambdas() { return false; } static int getNumberOfLanguagesThatRunOnThreeBillionDevices { return 1; } // abstract method boolean runsOnThreeBillionDevices(); }We don't want to make Java 8 too restrictive and
@FunctionalInterface
annotation is not required to make the interface functional. Having exactly one abstract method in the interface is enough.@FunctionalInterface
annotation, then our brand new compiler won't compile a functional interface with two or more abstract methods. It works like magic.
// Compilation error: Language is not a functional interface. // Multiple non-overriding abstract methods found // in the interface Language @FunctionalInterface interface Language { boolean runsOnThreeBillionDevices(); boolean isAmazing(); }It's amazing. Let's use the brand new default methods to fix this error:
@FunctionalInterface public interface Language { boolean runsOnThreeBillionDevices(); default boolean isAmazing() { return runsOnThreeBillionDevices(); } }But why would we redesign interfaces that way? And what does it have to do with lambdas?
Language java = () -> true; System.out.println(java.runsOnThreeBillionDevices()); // trueWhen you instantiate a functional interface with lambda then this lambda "substitutes" that single abstract method. Type signatures of lambda and abstract method should match.
Runnable
was never so much fun:
(new Thread(() -> System.out.println("Awesome"))).start();Writing custom comparators is incredibly simple:
import java.util.Comparator; Comparator<String> lengthComparator = (x, y) -> Integer.compare(x.length(), y.length());It's even simpler with the Comparator's brand new helper methods and method references:
import java.util.Comparator; Comparator<String> lengthComparator = Comparator.comparing(String::length);Java 8 lambdas come in several different shapes. Our favorite at Oracle is type-inferenced short version. You just write an argument list, an arrow (
->
), and provide and implementation. It's pretty awesome:
Comparator<String> lengthComparator = (x, y) -> Integer.compare(x.length(), y.length());If you want to you can add a type signature:
Comparator<String> lengthComparator = (String x, String y) -> Integer.compare(x.length(), y.length());Or explicit return statement:
Comparator<String> lengthComparator = (String x, String y) -> { return Integer.compare(x.length(), y.length()); };Method references can be used instead of lambdas with stunning effect.
// static method reference // same as (int x, int y) -> Integer.compare(x, y) Comparator<Integer> integerComparator = Integer::compare; // non-static method reference // same as (Integer integer) -> integer.byteValue() Comparator<Integer> intAsByteComparator = Comparator.comparing(Integer::byteValue); // instance method reference // same as (String suffix) -> javaString.endsWith(suffix) String javaString = "Java 8"; Comparator<String> mysteriousComparator = Comparator.comparing(javaString::endsWith); // constructor reference, same as (String s) -> new Integer(s) Comparator<String> stringAsIntegerComparator = Comparator.comparing(Integer::new);Next, ultrauseful
java.util.stream
package. It plays so nice with lambdas.import java.util.stream.Stream;Creating a stream is remarkably simple:
Stream<String> languages = Stream.of("C", "Java 8", "C++", "Haskell", "C");Let's filter out high-level languages:
languages.filter(lang -> lang.startsWith("C")); // stream of C, C++, CMethod references feel incredible with the streams:
languages.map(String::length); // stream of 1, 6, 3, 7, 1
Stream.map
applies specified function to the elements of the stream and returns a new stream.languages.filter(lang -> lang.startsWith("C")).map(String::length);But you can't call two methods on the same stream. This won't work:
languages.filter(lang -> lang.startsWith("C")); languages.map(String::length); // throws IllegalStateExceptionWe didn't stop with the
map
method. We've added mapToInt
, mapToLong
, and mapToDouble
methods so you can enjoy working with your favorite primitive types:
languages.mapToInt(String::length) // primitive stream of 1, 6, 3, 7, 1. We call it IntStream
Stream.distinct
method is fantastic when you don't want duplicate elements:
languages.filter(lang -> lang.startsWith("C")).distinct(); // stream of C and C++We've reinvented the sorting. It's so simple:
languages.sorted(); // C, C, C++, Haskell, Java 8Brand new Comparator methods take sorting to a different level:
languages.sorted(Comparator.reverseOrder()); // Java, Haskell, C++, C, CLimiting and skipping your streams is incredibly fun:
languages.limit(3); // C, Java 8, C++ languages.skip(2); // C++, Haskell, CNext, gorgeous forEach method:
languages.forEach(System.out::println); // println every elementBy the way we've added the forEach method to our classic Iterable interface. It's fantastic.
String[] langs = languages.toArray(String[]::new); // convert to a string arrayCounting elements is so easy:
languages.count(); // 5These methods are so intuitive and natural I won't even explain what they're doing:
languages.anyMatch(s -> s.equals("Java 8")); // true languages.allMatch(s -> s.equals("Java 8")); // false languages.noneMatch(s -> s.equals("Java 8")); // falseParallel processing of streams works like magic. You just call the parallel method and continue working with the stream like nothing happened:
languages.parallel().forEach(System.out::println); // makes processing parallelConcat method is great for concatenating streams:
Stream.concat(Stream.of("Java", "Java 8"), Stream.of("C", "C++")); // Stream of Java, Java 8, C, C++Finding the maximum element is gorgeous:
languages.max(Comparator.naturalOrder()); // Optional[Java 8]Getting the first element is at least five years ahead of what's in any other language:
languages.findFirst(); // Optional[C]Now, these last two methods return an Optional<String>. What is Optional? Optional is an amazing container which may or may not contain a non-null value.
import java.util.Optional; Optional<String> os = Optional.of("Java 8");Creating an empty Optional is so easy with the empty method:
Optional<String> empty = Optional.empty();You get a value from an Optional with the get method:
os.get(); // "Java 8"To check if an Optional contains a value, you use the isPresent method:
os.isPresent(); // true empty.isPresent(); // falseOptional.filter method is fantastic. If the filter predicate returns true for Optional value then it returns the Optional itself. If the filter predicate returns false then it returns an empty Optional.
os.filter(s -> s.startsWith("J")); // Optional[Java 8] os.filter(s -> s.equals("C++"))); // Optional.emptyFilter method works for an empty Optional as well. It simply returns an empty Optional.
empty.filter(s -> s.startsWith("J")); // Optional.emptyOptional.map method is so cool. It applies a function to an Optional value and returns a new Optional.
os.map(s -> s + " is the best Java we've ever made"); // Optional[Java 8 is the best Java we've ever made]As you can guess it works for an empty Optional as well:
empty.map(s -> s + " is the best Java we've ever made"); // Optional.emptyOptional.orElse method returns an Optional value or the default value if Optional is empty.
os.orElse("C++"); // Java 8 empty.orElse("Java 8"); // Java 8But we didn't stop with the Optional<T>. We've added the OptionalInt, OptionalLong, and OptionalDouble classes so Java 8 has now 3 Optional types more than Haskell.
import java.nio.file.Files; import java.nio.file.Paths; Stream<String> lines = Files.lines(Paths.get("Java.java"));We've also added lines method to the BufferedReader class:
import java.io.BufferedReader; import java.nio.file.Files; import java.nio.file.Paths; BufferedReader reader = Files.newBufferedReader( Paths.get("Java.java")); Stream<String> lines = reader.lines();By the way Files.newBufferedReader is new in Java 8. There is also of course Files.newBufferedWriter.
import java.util.ArrayList; import java.util.Collection; import java.util.stream.Stream; Collection<String> languagesCollection = new ArrayList<>(); languagesCollection.add("Java 8"); languagesCollection.add("C++"); Stream<String> languagesStream = languagesCollection.stream();It's the best way to convert a collection to a stream.
import java.utils.Arrays; int[] intNumbers = new int[] { 8, 9, 10}; Arrays.stream(intNumbers); // stream of integersThe stream method is overloaded so it works with all your favorite types. Unless your favorite type is byte.
import java.utils.Arrays; double[] doubleNumbers = new double[] { 2.71, 3.14, 69.69}; String[] strings = new String[] { "Java 6", "Java 7", "Java 8"}; Arrays.stream(doubleNumbers).average(); // OptionalDouble[25.18] Arrays.stream(strings).filter(s -> s.endsWith("8")).findFirst() // Optional[Java 8]While we're at Arrays. Java 8 is 100% ready for the multicore revolution with the fantastic Arrays.parallelSort method:
import java.utils.Arrays; double[] doubleNumbersToSort = new double[] { 69.69, 2.71, 3.14, }; Arrays.parallelSort(doubleNumbersToSort); // in-place sort: 2.71, 3.14, 69.69Removing nulls from Collection is so simple with our brand new removeIf and Objects.isNull methods:
import java.util.Objects;
languagesCollection.removeIf(Objects::isNull); // modifies collection in-placePure stream solution is also amazing:
languagesStream.filter(Objects::nonNull); // returns a new stream with non null objects.It's incredible.
import java.util.ArrayList; import java.util.Comparator; ArrayList<String> languagesList = new ArrayList<>(); languagesList.add("Java 8"); languagesList.add("C++"); languagesList.add(null); languagesList.sort( Comparator.nullsFirst(Comparator.naturalOrder())); // null, C++, Java 8You can handle nulls in the list by using Comparator.nullsFirst method. No exception is thrown. It's amazing. Comparator also has the nullsLast method.
import java.util.Random; (new Random()).ints().limit(100); // stream of 100 random integers (new Random()).ints(); // infinite stream of random integersNow that's all great and amazing but I hear you asking what about the argument types? What is the argument type of the Stream.filter method? What is the argument type of the Stream.map method?
<R> Stream<R> map(Function<? super T, ? extends R> mapper); Stream<T> filter(Predicate<? super T> predicate);The team has added Function and Predicate types. Function and Predicate are of course functional interfaces and you can instantiate them with lambdas. That's why streams are so fun in Java 8. But the team didn't stop there. They've added some fantastic methods to the Function and Predicate interfaces.
import java.util.function.Function; Function<String, String> toUpper = String::toUpperCase; Function<String, String> concatAndToUpper = toUpper .compose(s -> s + " is the best Java we've ever made"); concatAndToUpper.apply("Java 8"); // JAVA 8 IS THE BEST JAVA WE'VE EVER MADEAnd then there's amazing andThen method that constructs a new function with a slight twist:
Function<String, String> toUpperAndConcat = toUpper .andThen(s -> s + " is the best Java we've ever made"); toUpperAndConcat.apply("Java 8"); // JAVA 8 is the best Java we've ever madeStatic method Function.identity can be helpful at lazy Sunday mornings when you don't want to do anything:
import java.util.function.Function; Function<String, String> returnTheArgument = Function.identity(); returnTheArgument.apply("Java 8"); // Java 8And that was the Function class. But there's so much more.
import java.util.function.Predicate; Predicate<String> isAmazing = s -> s.equals("Java 8"); isAmazing.test("Java 8"); // true isAmazing.test("Haskell"); // falsePredicate interface has some incredible default methods. Predicate.or is fantastic for chaining or conditions:
Predicate<String> isGreatOrAmazing = isAmazing .or(s -> s.equals("Java 7")); isGreatOrAmazing.test("Java 7"); // trueIt also has the similar and method. Predicate.negate is beautiful:
Predicate<String> isNotAmazing = isAmazing.negate(); isNotAmazing.test("Java 7"); // true isNotAmazing.test("Java 8"); // falseMy favorite Predicate method is the static method isEqual. It returns a new Predicate that checks for equality to a specified object. It plays so nice with the brand new stream API:
import java.util.stream.Stream; import static java.util.function.Predicate.isEqual; Stream.of("C", "Java 8", "C++").filter(isEqual("Java 8")); // Stream of Java 8Predicates are so useful that we've added the asPredicate method to the java.util.regex.Pattern class.
import java.util.regex.Pattern; import java.util.stream.Stream; Pattern isJava = Pattern.compile("^Java \\d+$"); Stream.of("Java 8", "C", "C++", "Java 7") .filter(isJava.asPredicate()); // Stream of Java 8, Java 7And that was the new Predicate and Function interfaces. But the team didn't stop there.
import java.utils.StringJoiner; StringJoiner sj = new StringJoiner(", "); sj.add("Java 8").add("C++").add("Haskell"); sj.toString(); // Java 8, C++, HaskellAnd we also have this great constructor StringJoiner(String delimiter, String prefix, String suffix):
import java.utils.StringJoiner; StringJoiner sj = new StringJoiner(", ", "The most advanced languages are: ", "."); sj.add("Java 8").add("C++").add("Haskell"); sj.toString(); // "The most advanced languages are: Java 8, C++, Haskell."We've also got great Base64 class.
import java.util.Base64; byte[] encodedMessage = Base64 .getEncoder() .encode("Java 8 is the best Java we've ever made".getBytes()); new String(Base64.getDecoder().decode(encodedMessage)); // "Java 8 is the best Java we've ever made"It's just gorgeous.
int maxValuePlusOne = Integer.MAX_VALUE + 1; // silent overflow, -2147483648 Math.addExact(Integer.MAX_VALUE, 1); // throws ArithmeticExceptionWe've also added subtractExact, multiplyExact, incrementExact, decrementExact, and negateExact methods to the Math class. If your favorite integer type is long - every of the exact methods is overloaded on long.
// Java 7 way byte theBiggestByteWeHaveEverMade = (byte)255; int byteAsInt = theBiggestByteWeHaveEverMade & 0xFF;This is the old way. And it's fine. But it's so much nicer with the brand new Byte.toUnsignedInt method:
int byteAsIntBrandNewWay = Byte.toUnsignedInt(theBiggestByteWeHaveEverMade);We've also provided Byte.toUnsignedLong method if your bytes are so big that they don't fit into an int.
import java.math.BigInteger; BigInteger big = BigInteger.valueOf(Integer.MAX_VALUE) .add(BigInteger.ONE); int bigAsInt = big.intValueExact(); // throws ArithmeticExceptionBut we didn't stop there. We went on to add the byteValueExact, shortValueExact, and longValueExact methods so you can work with all your favorite primitive types. Even if your favorite primitive type is byte.
long bigAsLong = big.longValueExact(); // that's okNext, string joining. The team worked really hard at it and we have two join methods in the String class. The first one takes a delimiter and any number of strings.
String joinedString = String.join(", ", "Java 8", "Java 7", "C++", "Haskell"); // "Java 8, Java 7, C++, Haskell"Let me show you the second join method. It takes a delimiter and an Iterable.
import java.util.Arrays; import java.util.List; List<String> someStrings = Arrays.asList("Java 8", "Java 7", "C++", "Haskell"); String joinedStringIterableWay = String.join(", ", someStrings); // "Java 8, Java 7, C++, Haskell"Next, I'd like to show you a brand new class and that is java.util.stream.Collectors.
import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; Stream<String> languages = Stream.of("C", "Java 8", "C++", "Haskell", "C");Let's convert this stream to a list. It's so easy with the Collectors.toList method.
List<String> asList = languages.collect(Collectors.toList());List is of course an Iterable so our brand new forEach method is fantastic here:
asList.forEach(System.out::println);Collectors.toSet is the most advanced way to convert a stream to a set.
Set<String> asSet = languages.collect(Collectors.toSet());And one of the really cool things about Collectors is the joining method. Joining a stream of strings has never been that easy. No more Apache Commons, no more Guava, it's just Java 8 since today.
String joined = languages.collect(Collectors.joining(", ")); // String "C, Java 8, C++, Haskell, C"Here I skip the delimiter argument and it just works:
String joinedWithoutDelimiter = languages .collect(Collectors.joining()); // String "CJava 8C++HaskellC"What Collectors.groupingBy does is simply astounding:
Map<Character, List<String>> groupedByFirstChar = languages.collect(Collectors.groupingBy(s -> s.charAt(0))); // {'C': ["C", "C++", "C"], 'J': ["Java 8"], 'H': ["Haskell"]}Let's print this map using the brand new Map.forEach method:
groupedByFirstChar.forEach(c, langs) -> System.out.printf("%s=%s\n", c, String.join(", ", langs)));Fantastic.
Map<Boolean, List<String>> paritioned = languages.collect(Collectors.partitioningBy(s -> s.startsWith("J"))); // {true: ["Java 8"], false: ["C", "C++", "Haskell", "C"]}[ Applause ]
This [code] works because max(None, i) is i for any integer i.I was all like: wow, Python gonna let this punk get away with that? What's the matter? What's the world coming to?
nigel@codumentary:~$ python Python 3.2.3 (default, Nov 22 1963, 18:30:12) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> help Type help() for interactive help, or help(object) for help about object. >>> max(None, 12) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unorderable types: int() > NoneType()That's what the world is coming to: TypeError.
pnorvig@google:/usr/local/secret-project/popups$ python Python 2.7.3 (default, Apr 20 2012, 22:39:59) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> # it works >>> max(None, 12) 12 >>> # there is more >>> class FarmAnimal(object): pass >>> max(lambda x: x + 12, FarmAnimal) <class '__main__.FarmAnimal'>Yes, you can compare class to lambda function in Python2. Python3 throws an exception.
Objects of different types, except different numeric types and different string types, never compare equal; such objects are ordered consistently but arbitrarily (so that sorting a heterogeneous array yields a consistent result)
CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.Let's check it:
>>> type(FarmAnimal).__name__ 'type'Type name of FarmAnimal is 'type', type name of
>>> type(lambda x: x + 12).__name__ 'function'
lambda x: x + 12
is 'function'. That's why FarmAnimal is greater than lambda x: x + 12 (string 'type' is greater than string 'function').>>> max(None, 12)Is it because string 'int' is greater than string 'NoneType'?
12
static int
default_3way_compare(PyObject *v, PyObject *w) { ... ... /* None is smaller than anything */ if (v == Py_None) return -1; if (w == Py_None) return 1; /* different type: compare type names; numbers are smaller */ if (PyNumber_Check(v)) vname = ""; else vname = v->ob_type->tp_name; if (PyNumber_Check(w)) wname = ""; else wname = w->ob_type->tp_name; c = strcmp(vname, wname); if (c < 0) return -1; if (c > 0) return 1; /* Same type name, or (more likely) incomparable numeric types */ return ((Py_uintptr_t)(v->ob_type) < ( Py_uintptr_t)(w->ob_type)) ? -1 : 1; }
Is it because string 'int' is greater than string 'NoneType'?
/* None is smaller than anything */ if (v == Py_None) return -1; if (w == Py_None) return 1;Anything is greater than None in CPython2. None is Python's absolute zero. Here's the proof:
>>> cow = FarmAnimal() >>> type(cow).__name__
'FarmAnimal' >>> 'FarmAnimal' > 'NoneType'
False >>> # Comparing to None ignores type names >>> max(None, cow) <__main__.FarmAnimal object at 0xdeadbeef>