text:
package org.python.types;

public class Type extends org.python.types.Object implements org.python.Callable {
    public enum Origin {
        PLACEHOLDER,  // Dummy entry to resolve circular dependencies
        BUILTIN,      // A type provided as part of Python itself.
        PYTHON,       // A type defined in Python code
        JAVA,         // A type defined in Java
        EXTENSION     // A type defined in Python, extending a Java base class
    }

    public java.lang.String PYTHON_TYPE_NAME;
    private static java.util.Map<java.lang.Class, org.python.types.Type> known_types = new java.util.HashMap<java.lang.Class, org.python.types.Type>();
    public java.lang.reflect.Constructor constructor;
    public java.lang.Class klass;

    private static org.python.Object[] emptyArgs;
    private static java.util.Map<java.lang.String, org.python.Object> emptyKwargs;

    private static org.python.Object[] getEmptyArgs() {
        if (emptyArgs == null) {
            emptyArgs = new org.python.Object[0];
        }
        return emptyArgs;
    }

    private static java.util.Map<java.lang.String, org.python.Object> getEmptyKwargs() {
        if (emptyKwargs == null) {
            emptyKwargs = new java.util.HashMap<java.lang.String, org.python.Object>();
        }
        return emptyKwargs;
    }

    /**
     * Factory method to obtain Python classes from their Java counterparts
     */
    public static org.python.types.Type pythonType(java.lang.Class java_class) {
        // Look up the class in the known types table.
        org.python.types.Type python_type = known_types.get(java_class);
        if (python_type == null) {
            // If type isn't known, create and store a placeholder
            // so that recursive lookups have a termination condition.
            PlaceholderType placeholder = new PlaceholderType(java_class);
            known_types.put(java_class, placeholder);

            // Declare the type, and install it the known types list
            // (Replacing any placeholders)
            python_type = declarePythonType(java_class, null, null, null);

            // Since we have a freshly created type, resolve
            // any placeholders that referenced this type.
            // These will have been created as a consequence of
            // calling the constructor for this type.
            placeholder.resolve(python_type);

            // After object type is resolved, clean up subclasses that
            // reference the placeholder.
            if (java_class == org.python.types.Object.class) {
                java.util.List<org.python.Object> bases = new java.util.ArrayList<org.python.Object>();
                bases.add(python_type);
                for (org.python.types.Type type : known_types.values()) {
                    if (type.__dict__.get("__base__") == placeholder) {
                        type.__dict__.put("__base__", python_type);
                        type.__dict__.put("__bases__", new org.python.types.Tuple(bases));
                    }
                }
            }
        }
        // System.out.println("GOT TYPE " + java_class + " " + python_type.origin);
        return python_type;
    }

    public static org.python.types.Type pythonType(java.lang.String java_class_name) {
        try {
            return pythonType(java.lang.Thread.currentThread().getContextClassLoader().loadClass(java_class_name.replace("/", ".")));
        } catch (ClassNotFoundException e) {
            throw new org.python.exceptions.RuntimeError("Unknown Class " + java_class_name);
        }
    }

    public static org.python.types.Type pythonType(java.lang.Class java_class, java.lang.Class base_java_class) {
        org.python.types.Type python_type = pythonType(java_class);

        if (base_java_class != null) {
            org.python.types.Type base_python_type = known_types.get(base_java_class);
            java.util.List<org.python.Object> bases = new java.util.ArrayList<org.python.Object>();
            bases.add(base_python_type);
            python_type.__dict__.put("__base__", base_python_type);
            python_type.__dict__.put("__bases__", new org.python.types.Tuple(bases));
        }

        return python_type;
    }

    public static org.python.types.Type declarePythonType(
            org.python.Object name,
            org.python.Object bases,
            org.python.Object dict
    ) {
        java.util.Map<org.python.Object, org.python.Object> from_dict = ((org.python.types.Dict) dict).value;
        java.util.Map<java.lang.String, org.python.Object> to_dict = new java.util.HashMap<java.lang.String, org.python.Object>();
        for (org.python.Object k : from_dict.keySet()) {
            to_dict.put(k.toString(), from_dict.get(k));
        }

        return org.python.types.Type.declarePythonType(
                org.python.types.Object.class,
                ((org.python.types.Str) name).value,
                ((org.python.types.Tuple) bases).value,
                to_dict
        );
    }

    public static org.python.types.Type declarePythonType(
            java.lang.Class java_class,
            java.lang.String name,
            java.util.List<org.python.Object> bases,
            java.util.Map<java.lang.String, org.python.Object> dict
    ) {
        org.python.types.Type python_type;
        // System.out.println("DECLARE " + java_class + " as " + name + " with bases " + bases + " and dict " + dict);

        // Construct the new type, and store it in the types table.
        // Any type implementing org.python.Object is a Python type;
        // otherwise, wrap it as a native Java type.
        if (org.python.Object.class.isAssignableFrom(java_class)) {
            if (java_class.getName().startsWith("org.python.types")
                    || java_class.getName().startsWith("org.python.stdlib")) {
                // System.out.println("    BUILTIN");
                python_type = new org.python.types.Type(Origin.BUILTIN, java_class);
                org.Python.loadModule(java_class, python_type.__dict__);
            } else {
                // System.out.println("    PYTHON");
                python_type = new org.python.types.Type(Origin.PYTHON, java_class);
            }
        } else {
            try {
                // System.out.println("    EXTENSION");
                java_class.getDeclaredField("__VOC__");
                python_type = new org.python.java.Type(Origin.EXTENSION, java_class);
            } catch (NoSuchFieldException e) {
                // System.out.println("    JAVA");
                python_type = new org.python.java.Type(Origin.JAVA, java_class);
            }
        }

        // Set the name of the class.
        if (name != null) {
            python_type.PYTHON_TYPE_NAME = name;
        }

        // Set __base__ and __bases__ for the type
        if (java_class == org.python.types.Object.class) {
            python_type.__dict__.put("__base__", org.python.types.NoneType.NONE);
            python_type.__dict__.put("__bases__", new org.python.types.Tuple());
        } else if (bases != null && bases.size() > 0) {
            python_type.__dict__.put("__base__", bases.get(0));
            python_type.__dict__.put("__bases__", new org.python.types.Tuple(bases));
        } else {
            org.python.types.Type base_python_type = known_types.get(org.python.types.Object.class);
            java.util.List<org.python.Object> default_bases = new java.util.ArrayList<org.python.Object>();
            default_bases.add(base_python_type);
            python_type.__dict__.put("__base__", base_python_type);
            python_type.__dict__.put("__bases__", new org.python.types.Tuple(default_bases));
        }

        // Update the dictionary of the type.
        if (dict != null) {
            python_type.__dict__.putAll(dict);
        }

        // Register the type.
        org.python.types.Type placeholder = known_types.put(java_class, python_type);

        if (placeholder != null && placeholder.__dict__ != null) {
            python_type.__dict__.putAll(placeholder.__dict__);
        }

        // System.out.println("FINISHED DECLARING " + java_class + " as " + name + "; " + python_type.__dict__);
        return python_type;
    }

    /**
     * Convert a Java instance into the a Python-wrapped type.
     *
     * This means converting:
     *    * `null` into a None
     *    * Returning any object that already implements org.python.Object as itself.
     *    * Returning the existing VOC wrapper if one exists
     *    * Wrapping any other object in a newly created org.python.java.Object wrapper.
     */
    public static org.python.Object toPython(java.lang.Object value) {
        if (value == null) {
            return org.python.types.NoneType.NONE;
        } else {
            if (value.getClass() == java.lang.Boolean.TYPE
                    || value.getClass() == java.lang.Boolean.class) {
                return org.python.types.Bool.getBool((java.lang.Boolean) value);
            } else if (value.getClass() == java.lang.Byte.TYPE
                    || value.getClass() == java.lang.Byte.class) {
                return org.python.types.Int.getInt((java.lang.Byte) value);
            } else if (value.getClass() == java.lang.Character.TYPE
                    || value.getClass() == java.lang.Character.class) {
                return new org.python.types.Str((java.lang.Character) value);
            } else if (value.getClass() == java.lang.Short.TYPE
                    || value.getClass() == java.lang.Short.class) {
                return org.python.types.Int.getInt((java.lang.Short) value);
            } else if (value.getClass() == java.lang.Integer.TYPE
                    || value.getClass() == java.lang.Integer.class) {
                return org.python.types.Int.getInt((java.lang.Integer) value);
            } else if (value.getClass() == java.lang.Long.TYPE
                    || value.getClass() == java.lang.Long.class) {
                return org.python.types.Int.getInt((java.lang.Long) value);
            } else if (value.getClass() == java.lang.Float.TYPE
                    || value.getClass() == java.lang.Float.class) {
                return new org.python.types.Float((java.lang.Float) value);
            } else if (value.getClass() == java.lang.Double.TYPE
                    || value.getClass() == java.lang.Double.class) {
                return new org.python.types.Float((java.lang.Double) value);
            } else if (value.getClass() == java.lang.String.class) {
                return new org.python.types.Str((java.lang.String) value);
            } else if (org.python.Object.class.isAssignableFrom(value.getClass())) {
                return (org.python.Object) value;
            } else {
                try {
                    // Check to see if a __VOC__ field exists on the object.
                    // If it does, that field will contain the wrapper object.
                    // However, if this is the first time the object has been
                    // referenced (e.g., during construction), we may need to
                    // create the wrapper.
                    java.lang.reflect.Field field = value.getClass().getField("__VOC__");
                    org.python.Object wrapper = (org.python.Object) field.get(value);
                    if (wrapper == null) {
                        wrapper = new org.python.java.Object(value);
                        field.set(value, wrapper);
                    }
                    return wrapper;
                } catch (java.lang.NoSuchFieldException nsf) {
                    return new org.python.java.Object(value);
                } catch (java.lang.IllegalAccessException e) {
                    throw new org.python.exceptions.RuntimeError("Illegal access to __VOC__ attribute");
                }
            }
        }
    }

    public static java.lang.Object toJava(java.lang.Class<?> klass, org.python.Object value) {
        if (value == null) {
            return value;
        } else {
            if (klass == java.lang.Float.TYPE || klass == java.lang.Float.class) {
                return ((java.lang.Number) value.toJava()).floatValue();
            } else if (klass == java.lang.Long.TYPE || klass == java.lang.Long.class) {
                return ((java.lang.Number) value.toJava()).longValue();
            } else if (klass == java.lang.Integer.TYPE || klass == java.lang.Integer.class) {
                return ((java.lang.Number) value.toJava()).intValue();
            } else if (klass == java.lang.Short.TYPE || klass == java.lang.Short.class) {
                return ((java.lang.Number) value.toJava()).shortValue();
            } else if (klass == java.lang.Byte.TYPE || klass == java.lang.Byte.class) {
                return ((java.lang.Number) value.toJava()).byteValue();
            } else {
                return value.toJava();
            }
        }
    }

    public Type(Origin origin, java.lang.Class klass) {
        super(origin, null);

        if (origin != Origin.PLACEHOLDER) {
            this.klass = klass;
        }

        if (origin == Origin.BUILTIN || origin == Origin.PYTHON || origin == Origin.EXTENSION) {
            try {
                this.constructor = this.klass.getConstructor(org.python.Object[].class, java.util.Map.class);
            } catch (java.lang.NoSuchMethodException e) {
                this.constructor = null;
            }
        }
    }

    public Type(java.lang.Class klass) {
        this(Origin.PYTHON, klass);
    }

    public void add_reference(org.python.Object instance) {
        throw new java.lang.RuntimeException("Can't add reference to normal type");
    }

    @org.python.Method(
            __doc__ = "Return repr(self)."
    )
    public org.python.types.Str __repr__() {
        if (this.klass == null) {
            return new org.python.types.Str(
                    String.format("<...type 0x%x (%s) is being initialized...>",
                            this.hashCode(),
                            this.origin
                    )
            );
        }
        return new org.python.types.Str(
                String.format("<class '%s'%s>",
                        org.Python.typeName(this.klass),
                        this.origin == Origin.PLACEHOLDER ? " (placeholder)" : ""
                )
        );
    }

    public org.python.Object __getattribute_null(java.lang.String name) {
        // System.out.println("GETATTRIBUTE CLASS " + this.klass.getName() + " " + name + " " + this.origin);
        // System.out.println("CLASS ATTRS " + this.__dict__);
        org.python.Object value = this.__dict__.get(name);

        // It's an org.python.types Method that hasn't been initialized into __dict__ yet
        if (value == null) {
            value = org.Python.getPythonFunction(name, klass);
            if (value != null) {
                this.__dict__.put(name, value);
            }
        }

        if (value == null) {
            // We need to differentiate between "doesn't exist in the __dict__", and
            // exists, but has a value of null.
            if (!this.__dict__.containsKey(name)) {
                // The class attributes didn't contain a value for the attribute
                // name. Introspect on the object class to see if a field
                // with the given name exists, caching either the Field instance,
                // or an AttributeError representation of the NoSuchFieldException.
                try {
                    java.lang.reflect.Field field = this.klass.getDeclaredField(name);

                    // A field exists. Check that the attribute
                    // should be exposed to the Python namespace.
                    org.python.Attribute annotation =
                            (org.python.Attribute) field.getAnnotation(org.python.Attribute.class);
                    if (annotation != null) {
                        value = new org.python.java.Field(field);
                    } else {
                        value = null;
                    }
                } catch (java.lang.NoSuchFieldException e) {
                    value = null;
                }
                this.__dict__.put(name, value);
            }
        }

        // If the result of the lookup is an AttributeError, there's
        // no local field; so defer to the base type chain.
        if (value == null) {
            if (this.__dict__.get("__bases__") != null) {
                for (org.python.Object base : ((org.python.types.Tuple) this.__dict__.get("__bases__")).value) {
                    value = base.__getattribute_null(name);
                    if (value != null) {
                        break;
                    }
                }
            }
        }

        // If we still don't have a value, look for a global
        // variable defined at the module level.
        if (value == null) {
            // System.out.println("CLASS ATTRS " + this.klass);
            // System.out.println("__dict__ " + this.__dict__);
            org.python.Object module_name = this.__dict__.get("__module__");
            if (module_name != null) {
                org.python.Object module = python.sys.modules.__getitem__(module_name);
                value = module.__getattribute_null(name);
            }
        }

        // If we don't have a module attribute, look for a builtin.
        if (value == null) {
            // System.out.println("Look for attribute in builtins " + name);
            value = org.Python.builtins.get(name);
        }

        // System.out.println("GETATTRIBUTE CLASS " + this.klass.getName() + " " + name + " = " + value);
        return value;
    }

    public void __setattr__(java.lang.String name, org.python.Object value) {
        if (!this.__setattr_null(name, value)) {
            throw new org.python.exceptions.TypeError("Can't set new attributes on built-in type '" + org.Python.typeName(this.klass) + "'");
        }
    }

    public boolean __setattr_null(java.lang.String name, org.python.Object value) {
        // System.out.println("SETATTRIBUTE TYPE " + name + " = " + value);
        // System.out.println("class __dict__ = " + this.__dict__);

        // Can't set attributes of builtin types.
        if (this.origin == Origin.BUILTIN) {
            return false;
        }

        this.__dict__.put(name, value);
        return true;
    }

    public org.python.Object invoke(org.python.Object[] args, java.util.Map<java.lang.String, org.python.Object> kwargs) {
        try {
            // org.Python.debug("Constructor:", this.constructor);
            // org.Python.debug("     Origin:", this.origin);
            // org.Python.debug("       Type:", this);
            // for (org.python.Object arg: args) {
            //     org.Python.debug("            arg: ", arg);
            // }
            // org.Python.debug("         kwargs: ", kwargs);

            if (this.constructor != null) {
                org.python.Method annotation = (org.python.Method) this.constructor.getAnnotation(org.python.Method.class);
                org.python.Object[] adjusted_args;

                if (annotation != null && origin == Origin.BUILTIN) {
                    java.lang.String[] arg_names = annotation.args();
                    java.lang.String[] default_arg_names = annotation.default_args();
                    boolean has_varargs = annotation.varargs().equals("");
                    int a;
                    java.lang.String arg_name;
                    org.python.Object arg;
                    int n_args = arg_names.length + default_arg_names.length;

                    adjusted_args = new org.python.Object[arg_names.length + default_arg_names.length];

                    int n_provided_args = (args == null) ? 0 : args.length;
                    if (n_provided_args < n_args) {
                        // Take as many positional arguments as have been literally provided
                        for (a = 0; a < n_provided_args; a++) {
                            adjusted_args[a] = args[a];
                        }

                        // Populate the rest from kwargs
                        for (a = n_provided_args; a < n_args; a++) {
                            if (a < arg_names.length) {
                                arg_name = arg_names[a];
                            } else {
                                arg_name = default_arg_names[a - arg_names.length];
                            }

                            arg = (kwargs == null) ? null : kwargs.remove(arg_name);
                            if (arg == null && a < arg_names.length) {
                                throw new org.python.exceptions.TypeError(
                                        this.PYTHON_TYPE_NAME + " constructor missing positional argument '" +
                                                arg_name + "'"
                                );
                            }
                            adjusted_args[a] = arg;
                        }
                    } else if (n_provided_args == n_args) {
                        for (a = 0; a < n_args; a++) {
                            adjusted_args[a] = args[a];
                        }

                        for (a = n_args; a < n_provided_args; a++) {
                            if (a < arg_names.length) {
                                arg_name = arg_names[a];
                            } else {
                                arg_name = default_arg_names[a - arg_names.length];
                            }
                            kwargs.put(arg_name, args[a]);
                        }
                    } else {
                        // More arguments than expected, call the constructor anyway to handle too many arguments
                        adjusted_args = args;
                    }
                } else {
                    adjusted_args = args;
                }

                // for (org.python.Object arg: adjusted_args) {
                //     org.Python.debug("            adj arg: ", arg);
                // }
                // org.Python.debug("         adj kwargs: ", kwargs);

                return (org.python.Object) this.constructor.newInstance((adjusted_args != null) ? adjusted_args : getEmptyArgs(), (kwargs != null) ? kwargs : getEmptyKwargs());
            } else {
                throw new org.python.exceptions.RuntimeError("No Python-compatible constructor for type " + this.klass);
            }
        } catch (java.lang.IllegalAccessException e) {
            throw new org.python.exceptions.RuntimeError("Illegal access to Java constructor " + this.constructor);
        } catch (java.lang.reflect.InvocationTargetException e) {
            try {
                // e.getTargetException().printStackTrace();
                // If the Java method raised an Python exception, re-raise that
                // exception as-is. If it wasn't a Python exception, wrap it
                // as one and continue.
                throw (org.python.exceptions.BaseException) e.getCause();
            } catch (ClassCastException java_e) {
                throw new org.python.exceptions.RuntimeError(e.getCause().toString());
            }
        } catch (java.lang.InstantiationException e) {
            throw new org.python.exceptions.RuntimeError(e.getCause().toString());
        // } finally {
            //     System.out.println("CONSTRUCTOR DONE");
        }
    }
}


text:
module Frameit
  # Represents one screenshot
  class Screenshot
    attr_accessor :path # path to the screenshot
    attr_accessor :size # size in px array of 2 elements: height and width
    attr_accessor :screen_size # deliver screen size type, is unique per device type, used in device_name
    attr_accessor :color # the color to use for the frame (from Frameit::Color)

    # path: Path to screenshot
    # color: Color to use for the frame
    def initialize(path, color)
      UI.user_error "Couldn't find file at path '#{path}'" unless File.exist? path
      @color = color
      @path = path
      @size = FastImage.size(path)

      @screen_size = ENV["FRAMEIT_FORCE_DEVICE_TYPE"] || Deliver::AppScreenshot.calculate_screen_size(path)
    end

    # Device name for a given screen size. Used to use the correct template
    def device_name
      sizes = Deliver::AppScreenshot::ScreenSize
      case @screen_size
      when sizes::IOS_55
        return Frameit.config[:use_legacy_iphone6s] ? 'iPhone 6s Plus' : 'iPhone 7 Plus'
      when sizes::IOS_47
        return Frameit.config[:use_legacy_iphone6s] ? 'iPhone 6s' : 'iPhone 7'
      when sizes::IOS_40
        return Frameit.config[:use_legacy_iphone5s] ? 'iPhone 5s' : 'iPhone SE'
      when sizes::IOS_35
        return 'iPhone 4'
      when sizes::IOS_IPAD
        return 'iPad Air 2'
      when sizes::IOS_IPAD_PRO
        return 'iPad Pro'
      when sizes::MAC
        return 'MacBook'
      else
        UI.error "Unknown device type for size #{@screen_size} for path '#{path}'"
      end
    end

    def color
      if !Frameit.config[:use_legacy_iphone6s] && @color == Frameit::Color::BLACK
        if @screen_size == Deliver::AppScreenshot::ScreenSize::IOS_55 || @screen_size == Deliver::AppScreenshot::ScreenSize::IOS_47
          return "Matte Black" # RIP space gray
        end
      end
      return @color
    end

    # Is the device a 3x device? (e.g. 6 Plus)
    def triple_density?
      (screen_size == Deliver::AppScreenshot::ScreenSize::IOS_55)
    end

    # Super old devices (iPhone 4)
    def mini?
      (screen_size == Deliver::AppScreenshot::ScreenSize::IOS_35)
    end

    def mac?
      return device_name == 'Mac'
    end

    # The name of the orientation of a screenshot. Used to find the correct template
    def orientation_name
      return Orientation::PORTRAIT if size[0] < size[1]
      return Orientation::LANDSCAPE
    end

    def portrait?
      return (orientation_name == Orientation::PORTRAIT)
    end

    def to_s
      self.path
    end

    # Add the device frame, this will also call the method that adds the background + title
    def frame!
      if self.mac?
        MacEditor.new.frame!(self)
      else
        Editor.new.frame!(self)
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Session with Qi Lu</title>

  <link rel="stylesheet" href="/assets/css/main.css" type="text/css">
  <link rel="stylesheet" href="/assets/css/social-share-kit.css" type="text/css">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

  <link rel="alternate" type="application/rss+xml" title="RSS Feed for Eddie" href="/feed.xml" />

<title>Session with Qi Lu - Eddie</title>
<meta property="og:title" content="Session with Qi Lu" />
<meta name="description" content="Class notes after session with one of Microsoft's most senior and respected executives" />
<meta property="og:description" content="Class notes after session with one of Microsoft's most senior and respected executives" />
<link rel="canonical" href="http://localhost:4000/2016-05-15/Session-with-Qi-Lu/" />
<meta property="og:url" content="http://localhost:4000/2016-05-15/Session-with-Qi-Lu/" />
<meta property="og:site_name" content="Eddie" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2016-05-15T00:00:00-07:00" />

    Eddie

Session with Qi Lu

    <time>15 May 2016</time>

          Qi Lu

          Microsoft

          Notes

          Entrepreneurship

          Innovation

This article was first written on May 13, 2016. With Qi's departure from Microsoft, I found it refreshing to revisit the session with him, and find renewed inspirations from him. Good luck Qi in your future endeavor.

As part of my COS448 experience we were very fortunate to have Qi Lu from Microsoft calling today for a casual fireside chat. Below is some takeaways I jotted down.

1. What are the three most useful things that you learned from this guest speaker or session that you didn't know before, or that you hadn't thought about much before, and that you think you are likely to carry with you going forward?

The first thing I learned is Qi's view on innovation, "product is the core, technology is the foundation, business is the make-or-break" — it's only by intersecting the three inter-related areas together, finding the common denominator among human desirability, technology feasibility and business viability, that we can find a sustainable product that is wanted by consumers and profitable. All business ventures and product developments need to focus on testing these three areas before coming to any conclusions.

Secondly, I learned that in the life cycle of innovation, Qi thinks that the most difficult challenge lies in "Go-to-Market": it's vital for business to expose the product to the maximum right audience at the right time as fast as possible, and there is as much technicality, expertise and complexity as luck in its success.

Thirdly, I found the stories he shared, both about Yahoo and Microsoft, very interesting and enlightening. Especially on the browser war, I didn't even think deep enough about the essence of our online experience, and Qi teased out his take as the experience is closely tied to search (which dictates discovery, access and interaction processes). As I'm developing apps for this class and thinking about mobile options, it's imperative that I understand what WWW really means to users.

2. What surprised you most?

It surprised me a lot when Qi said Microsoft had won the browser war by having a superior product Internet Explorer (because of its expandability and compatibility), and I, being a millennial, was like "when did this happen?" I guess Microsoft had won the war in the sense that it defeated Netscape in market share — yet the victory was brief, and no one today would certainly regard IE as a good product (even Microsoft itself, since it has publicized Edge, an IE replacement, a great deal).

3. What did you like most about the speaker or the session?

Qi's insight and organization (as seen from his slides) impressed me a lot — and his observation of the industry resonated with me and taught me a great deal.
What do you think of Microsoft? It's gotten so big that I struggle to find a single adjective to sum up my impression of Microsoft; yet it's amazing how Microsoft seems to have reinvented itself and remained relevant for so long.

    Share this:

	© 2016 Eddie Chen. All rights reserved.


text:
class Spree::EasyPost::PostageController < ApplicationController

  require 'easypost'

	def create
		params.each do |key,value|
		  Rails.logger.warn "Param #{key}: #{value}"
		end

		EasyPost.api_key = ENV['EASYPOST_API_KEY']

		order = Spree::Order.find_by_number(params["order_id"])

		package = Spree::Stock::Package.new(order.shipments[0].stock_location, order.contents)

    logger.debug '---refreshing rates---'
    # logger.debug "package: #{package.inspect}"

		to_address = process_address(order.ship_address)
    logger.debug "to_address: #{to_address.inspect}"

	  from_address = process_address(package.stock_location)
    logger.debug "from_address: #{from_address.inspect}"

    parcel = build_parcel(order)
    logger.debug "parcel: #{parcel.inspect}"

		shipment = build_shipment(from_address, to_address, parcel)
    logger.debug "shipment: #{shipment.inspect}"

    rates = shipment.rates.sort_by { |r| r.rate.to_i }
    logger.debug "rates: #{rates.inspect}"
    logger.debug '---end---'

    if !rates.any?
      logger.info "No rates found."
      # logger.info "package: #{package.inspect}"
      logger.info "from_address: #{from_address.inspect}"
      logger.info "to_address: #{to_address.inspect}"
      []
    end

		shipment.buy(
		  :rate => shipment.lowest_rate
		)

		# shipment.insure(amount: 100)
		# puts shipment.insurance

		response = {url: shipment.postage_label.label_url, id: params[:shipment_id] }
		respond_to do |format|
      format.json { render :json => response }
    end
	end

  private

  def process_address(address)
    ep_address_attrs = {}
    # Stock locations do not have "company" attributes,
    ep_address_attrs[:company] = if address.respond_to?(:company)
      address.company
    else
      Spree::Store.current.name
    end
    ep_address_attrs[:name] = address.full_name if address.respond_to?(:full_name)
    ep_address_attrs[:street1] = address.address1
    ep_address_attrs[:street2] = address.address2
    ep_address_attrs[:city] = address.city
    ep_address_attrs[:state] = address.state ? address.state.abbr : address.state_name
    ep_address_attrs[:zip] = address.zipcode
    ep_address_attrs[:phone] = address.phone

    ::EasyPost::Address.create(ep_address_attrs)
  end

  def build_parcel(order)
  	total_weight = 0
    order.line_items.each do |line_item|
      total_weight = total_weight + line_item.quantity * line_item.variant.weight
    end
    parcel = ::EasyPost::Parcel.create(
      :weight => total_weight.to_f
    )
  end

  def build_shipment(from_address, to_address, parcel)
    shipment = ::EasyPost::Shipment.create(
      :to_address => to_address,
      :from_address => from_address,
      :parcel => parcel
    )
  end

  def logger
    @logger ||= Logger.new("#{Rails.root}/log/spree_easypost.log")
  end

end


text:
require 'rails_helper'

describe 'language_switcher', type: :feature, js: true do
  before { allow(Features).to receive(:enable_language_switcher?).and_return(true) }

  context 'user logged out' do
    it 'defaults to English' do
      visit root_path
      expect(page).to have_css('.language-picker')
      within('.language-picker') do
        expect(page).to have_css('.Select-placeholder', text: 'en')
      end
    end

    it 'switches to another language using URL param' do
      visit root_path
      expect(page).to have_css('.language-picker')
      within('.language-picker') do
        find('.Select').click
        expect(page).to have_css('.Select-menu-outer')
        expect(page).to have_text('Français')
        find('.Select-option', text: 'Français').click
      end
      expect(page.current_path).to eq root_path
      uri = URI.parse(current_url)
      expect("#{uri.path}?#{uri.query}").to eq(root_path(locale: 'fr'))
      expect(page).to have_text('Se connecter avec Wikipédia')
    end
  end

  context 'user logged in' do
    before do
      page.driver.restart if defined?(page.driver.restart)
      @user = create(:user)
      login_as(@user, scope: :user)
      page.current_window.resize_to(3000, 1080) # Workaround for PhantomJS layout bug
    end

    it 'defaults to English' do
      visit root_path
      expect(page).to have_css('.language-picker')
      within('.language-picker') do
        expect(page).to have_css('.Select-placeholder', text: 'en')
      end
    end

    it 'switches to another language using user model' do
      visit root_path
      expect(page).to have_css('.language-picker')
      within('.language-picker') do
        expect(page).to have_css('.Select')
        find('.Select').click
        expect(page).to have_css('.Select-menu-outer')
        expect(page).to have_text('Help translate')
        expect(page).to have_text('Français')
        find('.Select-option', text: 'Français').click
      end
      expect(page.current_path).to eq root_path
      uri = URI.parse(current_url)
      expect("#{uri.path}?#{uri.query}").to eq("#{root_path}?")
      expect(page).to have_text('Mon tableau de bord')
      expect(@user.reload.locale).to eq('fr')
    end

    it 'uses URL parameter first, if set' do
      @user.locale = 'fr'
      @user.save
      visit root_path(locale: 'en')
      expect(page).to have_text('My Dashboard')
    end
  end
end


text:
package com.hkurokawa.qiitandroid.screens.board;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ViewAnimator;

import com.hkurokawa.qiitandroid.R;
import com.hkurokawa.qiitandroid.domain.article.ListItem;
import com.hkurokawa.qiitandroid.domain.board.Board;

import java.util.List;

import rx.Observable;
import timber.log.Timber;

/**
 * BoardView is a view to display a list of items.
 * Created by hiroshi on 8/23/15.
 */
public abstract class BoardView<T extends ListItem> extends FrameLayout implements BoardScreen<T>, OnBoardListItemClickListener<T> {
    private BoardPresenter<T> presenter;
    private RecyclerView list;
    private BoardListAdapter<T> adapter;
    private ViewAnimator footerView;
    private Observable<Void> bottomHitObservable;

    public BoardView(Context context) {
        super(context);
        this.init(context);
    }

    public BoardView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.init(context);
    }

    public BoardView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.init(context);
    }

    private void init(Context context) {
        final View root = LayoutInflater.from(context).inflate(R.layout.view_board, this, true);
        this.list = (RecyclerView) root.findViewById(R.id.list);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        this.list.setLayoutManager(layoutManager);

        this.footerView = (ViewAnimator) LayoutInflater.from(context).inflate(R.layout.item_footer, this.list, false);
        this.adapter = this.createAdapter();
        this.adapter.setOnItemClickListener(this);
        this.adapter.setFooterView(this.footerView);
        this.list.setAdapter(this.adapter);
        this.bottomHitObservable = createBottomHitObservable(this.list, layoutManager);
    }

    public void setBoard(Board<T> board) {
        this.presenter = this.createPresenter(board);
        this.presenter.takeView(this);
    }

    @Override
    public void publish(List<T> items) {
        this.adapter.set(items);
        this.adapter.notifyDataSetChanged();
    }

    @Override
    public void onItemClick(T item, int position) {
        this.presenter.onItemClick(item, position);
    }

    @Override
    public Observable<Void> getBottomHitObservable() {
        return this.bottomHitObservable;
    }

    @Override
    public void dismissBottomProgressBar() {
        this.footerView.setDisplayedChild(1);
    }

    @Override
    public void logErr(Throwable e, String msg) {
        Timber.e(e, msg);
    }

    private static Observable<Void> createBottomHitObservable(final RecyclerView lv, final LinearLayoutManager layoutManager) {
        return Observable.create(subscriber ->
                lv.addOnScrollListener(new RecyclerView.OnScrollListener() {
                    boolean onBottom;

                    @Override
                    public void onScrolled(RecyclerView view, int dx, int dy) {
                        int totalItemCount = layoutManager.getItemCount();
                        int visibleItemCount = layoutManager.getChildCount();
                        int pastItemCount = layoutManager.findFirstVisibleItemPosition();

                        final boolean isBottom = pastItemCount + visibleItemCount >= totalItemCount;
                        if (!subscriber.isUnsubscribed() && (!this.onBottom && isBottom)) {
                            Timber.d("Emitting an onBottom event.");
                            subscriber.onNext((Void) null);
                        }
                        this.onBottom = isBottom;
                    }
                }));
    }

    protected abstract BoardPresenter<T> createPresenter(Board<T> board);

    protected abstract BoardListAdapter<T> createAdapter();
}


text:
/**
 * Autogenerated by Thrift Compiler (0.12.0)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package com.microsoft.thrifty.test.gen;

@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})

public class Insanity implements org.apache.thrift.TBase<Insanity, Insanity._Fields>, java.io.Serializable, Cloneable, Comparable<Insanity> {
  private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("Insanity");

  private static final org.apache.thrift.protocol.TField USER_MAP_FIELD_DESC = new org.apache.thrift.protocol.TField("userMap", org.apache.thrift.protocol.TType.MAP, (short)1);
  private static final org.apache.thrift.protocol.TField XTRUCTS_FIELD_DESC = new org.apache.thrift.protocol.TField("xtructs", org.apache.thrift.protocol.TType.LIST, (short)2);

  private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new InsanityStandardSchemeFactory();
  private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new InsanityTupleSchemeFactory();

  public @org.apache.thrift.annotation.Nullable java.util.Map<Numberz,java.lang.Long> userMap; // required
  public @org.apache.thrift.annotation.Nullable java.util.List<Xtruct> xtructs; // required

  /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
  public enum _Fields implements org.apache.thrift.TFieldIdEnum {
    USER_MAP((short)1, "userMap"),
    XTRUCTS((short)2, "xtructs");

    private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();

    static {
      for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
        byName.put(field.getFieldName(), field);
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, or null if its not found.
     */
    @org.apache.thrift.annotation.Nullable
    public static _Fields findByThriftId(int fieldId) {
      switch(fieldId) {
        case 1: // USER_MAP
          return USER_MAP;
        case 2: // XTRUCTS
          return XTRUCTS;
        default:
          return null;
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, throwing an exception
     * if it is not found.
     */
    public static _Fields findByThriftIdOrThrow(int fieldId) {
      _Fields fields = findByThriftId(fieldId);
      if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
      return fields;
    }

    /**
     * Find the _Fields constant that matches name, or null if its not found.
     */
    @org.apache.thrift.annotation.Nullable
    public static _Fields findByName(java.lang.String name) {
      return byName.get(name);
    }

    private final short _thriftId;
    private final java.lang.String _fieldName;

    _Fields(short thriftId, java.lang.String fieldName) {
      _thriftId = thriftId;
      _fieldName = fieldName;
    }

    public short getThriftFieldId() {
      return _thriftId;
    }

    public java.lang.String getFieldName() {
      return _fieldName;
    }
  }

  // isset id assignments
  public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
  static {
    java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
    tmpMap.put(_Fields.USER_MAP, new org.apache.thrift.meta_data.FieldMetaData("userMap", org.apache.thrift.TFieldRequirementType.DEFAULT,
        new org.apache.thrift.meta_data.MapMetaData(org.apache.thrift.protocol.TType.MAP,
            new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, Numberz.class),
            new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64            , "UserId"))));
    tmpMap.put(_Fields.XTRUCTS, new org.apache.thrift.meta_data.FieldMetaData("xtructs", org.apache.thrift.TFieldRequirementType.DEFAULT,
        new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST,
            new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, Xtruct.class))));
    metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
    org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(Insanity.class, metaDataMap);
  }

  public Insanity() {
  }

  public Insanity(
    java.util.Map<Numberz,java.lang.Long> userMap,
    java.util.List<Xtruct> xtructs)
  {
    this();
    this.userMap = userMap;
    this.xtructs = xtructs;
  }

  /**
   * Performs a deep copy on <i>other</i>.
   */
  public Insanity(Insanity other) {
    if (other.isSetUserMap()) {
      java.util.Map<Numberz,java.lang.Long> __this__userMap = new java.util.EnumMap<Numberz,java.lang.Long>(Numberz.class);
      for (java.util.Map.Entry<Numberz, java.lang.Long> other_element : other.userMap.entrySet()) {

        Numberz other_element_key = other_element.getKey();
        java.lang.Long other_element_value = other_element.getValue();

        Numberz __this__userMap_copy_key = other_element_key;

        java.lang.Long __this__userMap_copy_value = other_element_value;

        __this__userMap.put(__this__userMap_copy_key, __this__userMap_copy_value);
      }
      this.userMap = __this__userMap;
    }
    if (other.isSetXtructs()) {
      java.util.List<Xtruct> __this__xtructs = new java.util.ArrayList<Xtruct>(other.xtructs.size());
      for (Xtruct other_element : other.xtructs) {
        __this__xtructs.add(new Xtruct(other_element));
      }
      this.xtructs = __this__xtructs;
    }
  }

  public Insanity deepCopy() {
    return new Insanity(this);
  }

  @Override
  public void clear() {
    this.userMap = null;
    this.xtructs = null;
  }

  public int getUserMapSize() {
    return (this.userMap == null) ? 0 : this.userMap.size();
  }

  public void putToUserMap(Numberz key, long val) {
    if (this.userMap == null) {
      this.userMap = new java.util.EnumMap<Numberz,java.lang.Long>(Numberz.class);
    }
    this.userMap.put(key, val);
  }

  @org.apache.thrift.annotation.Nullable
  public java.util.Map<Numberz,java.lang.Long> getUserMap() {
    return this.userMap;
  }

  public Insanity setUserMap(@org.apache.thrift.annotation.Nullable java.util.Map<Numberz,java.lang.Long> userMap) {
    this.userMap = userMap;
    return this;
  }

  public void unsetUserMap() {
    this.userMap = null;
  }

  /** Returns true if field userMap is set (has been assigned a value) and false otherwise */
  public boolean isSetUserMap() {
    return this.userMap != null;
  }

  public void setUserMapIsSet(boolean value) {
    if (!value) {
      this.userMap = null;
    }
  }

  public int getXtructsSize() {
    return (this.xtructs == null) ? 0 : this.xtructs.size();
  }

  @org.apache.thrift.annotation.Nullable
  public java.util.Iterator<Xtruct> getXtructsIterator() {
    return (this.xtructs == null) ? null : this.xtructs.iterator();
  }

  public void addToXtructs(Xtruct elem) {
    if (this.xtructs == null) {
      this.xtructs = new java.util.ArrayList<Xtruct>();
    }
    this.xtructs.add(elem);
  }

  @org.apache.thrift.annotation.Nullable
  public java.util.List<Xtruct> getXtructs() {
    return this.xtructs;
  }

  public Insanity setXtructs(@org.apache.thrift.annotation.Nullable java.util.List<Xtruct> xtructs) {
    this.xtructs = xtructs;
    return this;
  }

  public void unsetXtructs() {
    this.xtructs = null;
  }

  /** Returns true if field xtructs is set (has been assigned a value) and false otherwise */
  public boolean isSetXtructs() {
    return this.xtructs != null;
  }

  public void setXtructsIsSet(boolean value) {
    if (!value) {
      this.xtructs = null;
    }
  }

  public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) {
    switch (field) {
    case USER_MAP:
      if (value == null) {
        unsetUserMap();
      } else {
        setUserMap((java.util.Map<Numberz,java.lang.Long>)value);
      }
      break;

    case XTRUCTS:
      if (value == null) {
        unsetXtructs();
      } else {
        setXtructs((java.util.List<Xtruct>)value);
      }
      break;

    }
  }

  @org.apache.thrift.annotation.Nullable
  public java.lang.Object getFieldValue(_Fields field) {
    switch (field) {
    case USER_MAP:
      return getUserMap();

    case XTRUCTS:
      return getXtructs();

    }
    throw new java.lang.IllegalStateException();
  }

  /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
  public boolean isSet(_Fields field) {
    if (field == null) {
      throw new java.lang.IllegalArgumentException();
    }

    switch (field) {
    case USER_MAP:
      return isSetUserMap();
    case XTRUCTS:
      return isSetXtructs();
    }
    throw new java.lang.IllegalStateException();
  }

  @Override
  public boolean equals(java.lang.Object that) {
    if (that == null)
      return false;
    if (that instanceof Insanity)
      return this.equals((Insanity)that);
    return false;
  }

  public boolean equals(Insanity that) {
    if (that == null)
      return false;
    if (this == that)
      return true;

    boolean this_present_userMap = true && this.isSetUserMap();
    boolean that_present_userMap = true && that.isSetUserMap();
    if (this_present_userMap || that_present_userMap) {
      if (!(this_present_userMap && that_present_userMap))
        return false;
      if (!this.userMap.equals(that.userMap))
        return false;
    }

    boolean this_present_xtructs = true && this.isSetXtructs();
    boolean that_present_xtructs = true && that.isSetXtructs();
    if (this_present_xtructs || that_present_xtructs) {
      if (!(this_present_xtructs && that_present_xtructs))
        return false;
      if (!this.xtructs.equals(that.xtructs))
        return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    int hashCode = 1;

    hashCode = hashCode * 8191 + ((isSetUserMap()) ? 131071 : 524287);
    if (isSetUserMap())
      hashCode = hashCode * 8191 + userMap.hashCode();

    hashCode = hashCode * 8191 + ((isSetXtructs()) ? 131071 : 524287);
    if (isSetXtructs())
      hashCode = hashCode * 8191 + xtructs.hashCode();

    return hashCode;
  }

  @Override
  public int compareTo(Insanity other) {
    if (!getClass().equals(other.getClass())) {
      return getClass().getName().compareTo(other.getClass().getName());
    }

    int lastComparison = 0;

    lastComparison = java.lang.Boolean.valueOf(isSetUserMap()).compareTo(other.isSetUserMap());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetUserMap()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.userMap, other.userMap);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = java.lang.Boolean.valueOf(isSetXtructs()).compareTo(other.isSetXtructs());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetXtructs()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.xtructs, other.xtructs);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    return 0;
  }

  @org.apache.thrift.annotation.Nullable
  public _Fields fieldForId(int fieldId) {
    return _Fields.findByThriftId(fieldId);
  }

  public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
    scheme(iprot).read(iprot, this);
  }

  public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
    scheme(oprot).write(oprot, this);
  }

  @Override
  public java.lang.String toString() {
    java.lang.StringBuilder sb = new java.lang.StringBuilder("Insanity(");
    boolean first = true;

    sb.append("userMap:");
    if (this.userMap == null) {
      sb.append("null");
    } else {
      sb.append(this.userMap);
    }
    first = false;
    if (!first) sb.append(", ");
    sb.append("xtructs:");
    if (this.xtructs == null) {
      sb.append("null");
    } else {
      sb.append(this.xtructs);
    }
    first = false;
    sb.append(")");
    return sb.toString();
  }

  public void validate() throws org.apache.thrift.TException {
    // check for required fields
    // check for sub-struct validity
  }

  private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
    try {
      write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
    try {
      read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private static class InsanityStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
    public InsanityStandardScheme getScheme() {
      return new InsanityStandardScheme();
    }
  }

  private static class InsanityStandardScheme extends org.apache.thrift.scheme.StandardScheme<Insanity> {

    public void read(org.apache.thrift.protocol.TProtocol iprot, Insanity struct) throws org.apache.thrift.TException {
      org.apache.thrift.protocol.TField schemeField;
      iprot.readStructBegin();
      while (true)
      {
        schemeField = iprot.readFieldBegin();
        if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
          break;
        }
        switch (schemeField.id) {
          case 1: // USER_MAP
            if (schemeField.type == org.apache.thrift.protocol.TType.MAP) {
              {
                org.apache.thrift.protocol.TMap _map0 = iprot.readMapBegin();
                struct.userMap = new java.util.EnumMap<Numberz,java.lang.Long>(Numberz.class);
                @org.apache.thrift.annotation.Nullable Numberz _key1;
                long _val2;
                for (int _i3 = 0; _i3 < _map0.size; ++_i3)
                {
                  _key1 = com.microsoft.thrifty.test.gen.Numberz.findByValue(iprot.readI32());
                  _val2 = iprot.readI64();
                  if (_key1 != null)
                  {
                    struct.userMap.put(_key1, _val2);
                  }
                }
                iprot.readMapEnd();
              }
              struct.setUserMapIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          case 2: // XTRUCTS
            if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {
              {
                org.apache.thrift.protocol.TList _list4 = iprot.readListBegin();
                struct.xtructs = new java.util.ArrayList<Xtruct>(_list4.size);
                @org.apache.thrift.annotation.Nullable Xtruct _elem5;
                for (int _i6 = 0; _i6 < _list4.size; ++_i6)
                {
                  _elem5 = new Xtruct();
                  _elem5.read(iprot);
                  struct.xtructs.add(_elem5);
                }
                iprot.readListEnd();
              }
              struct.setXtructsIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          default:
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
        }
        iprot.readFieldEnd();
      }
      iprot.readStructEnd();

      // check for required fields of primitive type, which can't be checked in the validate method
      struct.validate();
    }

    public void write(org.apache.thrift.protocol.TProtocol oprot, Insanity struct) throws org.apache.thrift.TException {
      struct.validate();

      oprot.writeStructBegin(STRUCT_DESC);
      if (struct.userMap != null) {
        oprot.writeFieldBegin(USER_MAP_FIELD_DESC);
        {
          oprot.writeMapBegin(new org.apache.thrift.protocol.TMap(org.apache.thrift.protocol.TType.I32, org.apache.thrift.protocol.TType.I64, struct.userMap.size()));
          for (java.util.Map.Entry<Numberz, java.lang.Long> _iter7 : struct.userMap.entrySet())
          {
            oprot.writeI32(_iter7.getKey().getValue());
            oprot.writeI64(_iter7.getValue());
          }
          oprot.writeMapEnd();
        }
        oprot.writeFieldEnd();
      }
      if (struct.xtructs != null) {
        oprot.writeFieldBegin(XTRUCTS_FIELD_DESC);
        {
          oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.xtructs.size()));
          for (Xtruct _iter8 : struct.xtructs)
          {
            _iter8.write(oprot);
          }
          oprot.writeListEnd();
        }
        oprot.writeFieldEnd();
      }
      oprot.writeFieldStop();
      oprot.writeStructEnd();
    }

  }

  private static class InsanityTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
    public InsanityTupleScheme getScheme() {
      return new InsanityTupleScheme();
    }
  }

  private static class InsanityTupleScheme extends org.apache.thrift.scheme.TupleScheme<Insanity> {

    @Override
    public void write(org.apache.thrift.protocol.TProtocol prot, Insanity struct) throws org.apache.thrift.TException {
      org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
      java.util.BitSet optionals = new java.util.BitSet();
      if (struct.isSetUserMap()) {
        optionals.set(0);
      }
      if (struct.isSetXtructs()) {
        optionals.set(1);
      }
      oprot.writeBitSet(optionals, 2);
      if (struct.isSetUserMap()) {
        {
          oprot.writeI32(struct.userMap.size());
          for (java.util.Map.Entry<Numberz, java.lang.Long> _iter9 : struct.userMap.entrySet())
          {
            oprot.writeI32(_iter9.getKey().getValue());
            oprot.writeI64(_iter9.getValue());
          }
        }
      }
      if (struct.isSetXtructs()) {
        {
          oprot.writeI32(struct.xtructs.size());
          for (Xtruct _iter10 : struct.xtructs)
          {
            _iter10.write(oprot);
          }
        }
      }
    }

    @Override
    public void read(org.apache.thrift.protocol.TProtocol prot, Insanity struct) throws org.apache.thrift.TException {
      org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
      java.util.BitSet incoming = iprot.readBitSet(2);
      if (incoming.get(0)) {
        {
          org.apache.thrift.protocol.TMap _map11 = new org.apache.thrift.protocol.TMap(org.apache.thrift.protocol.TType.I32, org.apache.thrift.protocol.TType.I64, iprot.readI32());
          struct.userMap = new java.util.EnumMap<Numberz,java.lang.Long>(Numberz.class);
          @org.apache.thrift.annotation.Nullable Numberz _key12;
          long _val13;
          for (int _i14 = 0; _i14 < _map11.size; ++_i14)
          {
            _key12 = com.microsoft.thrifty.test.gen.Numberz.findByValue(iprot.readI32());
            _val13 = iprot.readI64();
            if (_key12 != null)
            {
              struct.userMap.put(_key12, _val13);
            }
          }
        }
        struct.setUserMapIsSet(true);
      }
      if (incoming.get(1)) {
        {
          org.apache.thrift.protocol.TList _list15 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32());
          struct.xtructs = new java.util.ArrayList<Xtruct>(_list15.size);
          @org.apache.thrift.annotation.Nullable Xtruct _elem16;
          for (int _i17 = 0; _i17 < _list15.size; ++_i17)
          {
            _elem16 = new Xtruct();
            _elem16.read(iprot);
            struct.xtructs.add(_elem16);
          }
        }
        struct.setXtructsIsSet(true);
      }
    }
  }

  private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
    return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
  }
}


text:
'use strict';

const assert = require('assert');

let userUtils = require('./../../dev-tools/users-utils');
let User = userUtils.User;

describe('Rooms features', function () {
	describe('Rooms', function () {
		describe('Rooms.get', function () {
			it('should be a function', function () {
				assert.strictEqual(typeof Rooms.get, 'function');
			});

			it('should be equal to `Rooms`', function () {
				assert.strictEqual(Rooms.get, Rooms);
			});
		});
		describe('Rooms.rooms', function () {
			it('should be a Map', function () {
				assert.ok(Rooms.rooms instanceof Map);
			});
		});
	});

	describe('BattleRoom', function () {
		const packedTeam = 'Weavile||lifeorb||swordsdance,knockoff,iceshard,iciclecrash|Jolly|,252,,,4,252|||||';

		let room;
		afterEach(function () {
			if (room) room.expire();
		});

		it('should allow two users to join the battle', function () {
			let p1 = new User();
			let p2 = new User();
			let options = [{rated: false, tour: false}, {rated: false, tour: {onBattleWin() {}}}, {rated: true, tour: false}, {rated: true, tour: {onBattleWin() {}}}];
			for (let option of options) {
				room = Rooms.global.startBattle(p1, p2, 'customgame', packedTeam, packedTeam, option);
				assert.ok(room.battle.p1 && room.battle.p2); // Automatically joined
			}
		});

		it('should copy auth from tournament', function () {
			const p1 = new User();
			const p2 = new User();
			const options = {
				rated: false,
				auth: {},
				tour: {
					onBattleWin() {},
					room: {getAuth() {
						return '%';
					}},
				},
			};
			room = Rooms.global.startBattle(p1, p2, 'customgame', packedTeam, packedTeam, options);
			assert.strictEqual(room.getAuth(new User()), '%');
		});

		it('should prevent overriding tournament room auth by a tournament player', function () {
			const p1 = new User();
			const p2 = new User();
			const roomStaff = new User();
			roomStaff.forceRename("Room auth", true);
			const administrator = new User();
			administrator.forceRename("Admin", true);
			administrator.group = '~';
			const options = {
				rated: false,
				auth: {},
				tour: {
					onBattleWin() {},
					room: {getAuth(user) {
						return '%';
					}},
				},
			};
			room = Rooms.global.startBattle(p1, p2, 'customgame', packedTeam, packedTeam, options);
			administrator.joinRoom(room);
			assert.strictEqual(room.getAuth(roomStaff), '%', 'before promotion attempt');
			Chat.parse("/roomvoice Room auth", room, p1, p1.connections[0]);
			assert.strictEqual(room.getAuth(roomStaff), '%', 'after promotion attempt');
			Chat.parse("/roomvoice Room auth", room, administrator, administrator.connections[0]);
			assert.strictEqual(room.getAuth(roomStaff), '+', 'after being promoted by an administrator');

			for (const user of [roomStaff, administrator]) {
				user.disconnectAll();
				user.destroy();
			}
		});
	});
});


text:
import * as wjcChartRadar from 'wijmo/wijmo.chart.radar';
import { EventEmitter, AfterViewInit } from '@angular/core';
import { ElementRef, Injector } from '@angular/core';
import { OnInit, OnDestroy } from '@angular/core';
import { IWjComponentMetadata } from 'wijmo/wijmo.angular2.directiveBase';
export declare class WjFlexRadar extends wjcChartRadar.FlexRadar implements OnInit, OnDestroy, AfterViewInit {
    static readonly meta: IWjComponentMetadata;
    private _wjBehaviour;
    isInitialized: boolean;
    initialized: EventEmitter<{}>;
    wjModelProperty: string;
    gotFocusNg: EventEmitter<{}>;
    lostFocusNg: EventEmitter<{}>;
    renderingNg: EventEmitter<{}>;
    renderedNg: EventEmitter<{}>;
    seriesVisibilityChangedNg: EventEmitter<{}>;
    selectionChangedNg: EventEmitter<{}>;
    selectionChangePC: EventEmitter<{}>;
    constructor(elRef: ElementRef, injector: Injector, parentCmp: any);
    ngOnInit(): void;
    ngAfterViewInit(): void;
    ngOnDestroy(): void;
    tooltipContent: any;
    labelContent: any;
}
export declare class WjFlexRadarAxis extends wjcChartRadar.FlexRadarAxis implements OnInit, OnDestroy, AfterViewInit {
    static readonly meta: IWjComponentMetadata;
    private _wjBehaviour;
    isInitialized: boolean;
    initialized: EventEmitter<{}>;
    wjProperty: string;
    rangeChangedNg: EventEmitter<{}>;
    constructor(elRef: ElementRef, injector: Injector, parentCmp: any);
    ngOnInit(): void;
    ngAfterViewInit(): void;
    ngOnDestroy(): void;
}
export declare class WjFlexRadarSeries extends wjcChartRadar.FlexRadarSeries implements OnInit, OnDestroy, AfterViewInit {
    static readonly meta: IWjComponentMetadata;
    private _wjBehaviour;
    isInitialized: boolean;
    initialized: EventEmitter<{}>;
    wjProperty: string;
    renderingNg: EventEmitter<{}>;
    renderedNg: EventEmitter<{}>;
    visibilityChangePC: EventEmitter<{}>;
    constructor(elRef: ElementRef, injector: Injector, parentCmp: any);
    ngOnInit(): void;
    ngAfterViewInit(): void;
    ngOnDestroy(): void;
}
export declare class WjChartRadarModule {
}


text:
<?php

namespace LBcrew\BootstrapExtensionBundle\Controller;

/**
 * This code has been auto-generated by the JMSDiExtraBundle.
 *
 * Manual changes to it will be lost.
 */
class DefaultController__JMSInjector
{
    public static function inject($container) {
        $instance = new \LBcrew\BootstrapExtensionBundle\Controller\DefaultController();
        return $instance;
    }
}


text:
package com.google.cloud.bigquery;

import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkNotNull;

import com.google.api.client.util.Data;
import com.google.api.client.util.Strings;
import com.google.api.core.BetaApi;
import com.google.api.services.bigquery.model.Table;
import com.google.common.base.Function;
import com.google.common.base.MoreObjects;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.Map;
import java.util.Objects;

/**
 * Google BigQuery table information. Use {@link StandardTableDefinition} to create simple BigQuery
 * table. Use {@link ViewDefinition} to create a BigQuery view. Use {@link ExternalTableDefinition}
 * to create a BigQuery a table backed by external data.
 *
 * @see Managing Tables
 */
public class TableInfo implements Serializable {

  static final Function
 FROM_PB_FUNCTION =
      new Function
() {
        @Override
        public TableInfo apply(Table pb) {
          return TableInfo.fromPb(pb);
        }
      };
  static final Function<TableInfo, Table> TO_PB_FUNCTION =
      new Function<TableInfo, Table>() {
        @Override
        public Table apply(TableInfo tableInfo) {
          return tableInfo.toPb();
        }
      };

  private static final long serialVersionUID = 609769795097719407L;

  private final String etag;
  private final String generatedId;
  private final String selfLink;
  private final TableId tableId;
  private final String friendlyName;
  private final String description;
  private final Long creationTime;
  private final Long expirationTime;
  private final Long lastModifiedTime;
  private final Long numBytes;
  private final Long numLongTermBytes;
  private final BigInteger numRows;
  private final TableDefinition definition;
  private final EncryptionConfiguration encryptionConfiguration;
  private final Labels labels;
  private final Boolean requirePartitionFilter;

  /** A builder for {@code TableInfo} objects. */
  public abstract static class Builder {

    abstract Builder setCreationTime(Long creationTime);

    /** Sets a user-friendly description for the table. */
    public abstract Builder setDescription(String description);

    abstract Builder setEtag(String etag);

    /**
     * Sets the time when this table expires, in milliseconds since the epoch. If not present, the
     * table will persist indefinitely. Expired tables will be deleted and their storage reclaimed.
     */
    public abstract Builder setExpirationTime(Long expirationTime);

    /** Sets a user-friendly name for the table. */
    public abstract Builder setFriendlyName(String friendlyName);

    abstract Builder setGeneratedId(String generatedId);

    abstract Builder setLastModifiedTime(Long lastModifiedTime);

    abstract Builder setNumBytes(Long numBytes);

    abstract Builder setNumLongTermBytes(Long numLongTermBytes);

    abstract Builder setNumRows(BigInteger numRows);

    abstract Builder setSelfLink(String selfLink);

    /** Sets the table identity. */
    public abstract Builder setTableId(TableId tableId);

    /**
     * Sets the table definition. Use {@link StandardTableDefinition} to create simple BigQuery
     * table. Use {@link ViewDefinition} to create a BigQuery view. Use {@link
     * ExternalTableDefinition} to create a BigQuery a table backed by external data.
     */
    public abstract Builder setDefinition(TableDefinition definition);

    /**
     * Sets the labels applied to this table.
     *
     *
Unstable, because labels are experimental.
     *
     *
When used with {@link BigQuery#update(TableInfo, TableOption...)}, setting {@code labels}
     * to {@code null} removes all labels; otherwise all keys that are mapped to {@code null} values
     * are removed and other keys are updated to their respective values.
     */
    @BetaApi
    public abstract Builder setLabels(Map<String, String> labels);

    /** Creates a {@code TableInfo} object. */
    public abstract TableInfo build();

    public abstract Builder setEncryptionConfiguration(EncryptionConfiguration configuration);

    public Builder setRequirePartitionFilter(Boolean requirePartitionFilter) {
      return this;
    }
  }

  static class BuilderImpl extends Builder {

    private String etag;
    private String generatedId;
    private String selfLink;
    private TableId tableId;
    private String friendlyName;
    private String description;
    private Long creationTime;
    private Long expirationTime;
    private Long lastModifiedTime;
    private Long numBytes;
    private Long numLongTermBytes;
    private BigInteger numRows;
    private TableDefinition definition;
    private EncryptionConfiguration encryptionConfiguration;
    private Labels labels = Labels.ZERO;
    private Boolean requirePartitionFilter;

    BuilderImpl() {}

    BuilderImpl(TableInfo tableInfo) {
      this.etag = tableInfo.etag;
      this.generatedId = tableInfo.generatedId;
      this.selfLink = tableInfo.selfLink;
      this.tableId = tableInfo.tableId;
      this.friendlyName = tableInfo.friendlyName;
      this.description = tableInfo.description;
      this.creationTime = tableInfo.creationTime;
      this.expirationTime = tableInfo.expirationTime;
      this.lastModifiedTime = tableInfo.lastModifiedTime;
      this.numBytes = tableInfo.numBytes;
      this.numLongTermBytes = tableInfo.numLongTermBytes;
      this.numRows = tableInfo.numRows;
      this.definition = tableInfo.definition;
      this.encryptionConfiguration = tableInfo.encryptionConfiguration;
      this.labels = tableInfo.labels;
      this.requirePartitionFilter = tableInfo.requirePartitionFilter;
    }

    BuilderImpl(Table tablePb) {
      this.tableId = TableId.fromPb(tablePb.getTableReference());
      if (tablePb.getLastModifiedTime() != null) {
        this.setLastModifiedTime(tablePb.getLastModifiedTime().longValue());
      }
      this.description = tablePb.getDescription();
      this.expirationTime = tablePb.getExpirationTime();
      this.friendlyName = tablePb.getFriendlyName();
      this.creationTime = tablePb.getCreationTime();
      this.etag = tablePb.getEtag();
      this.generatedId = tablePb.getId();
      this.selfLink = tablePb.getSelfLink();
      this.numBytes = tablePb.getNumBytes();
      this.numLongTermBytes = tablePb.getNumLongTermBytes();
      this.numRows = tablePb.getNumRows();
      this.definition = TableDefinition.fromPb(tablePb);
      if (tablePb.getEncryptionConfiguration() != null) {
        this.encryptionConfiguration =
            new EncryptionConfiguration.Builder(tablePb.getEncryptionConfiguration()).build();
      }
      this.labels = Labels.fromPb(tablePb.getLabels());
      this.requirePartitionFilter = tablePb.getRequirePartitionFilter();
    }

    @Override
    Builder setCreationTime(Long creationTime) {
      this.creationTime = creationTime;
      return this;
    }

    @Override
    public Builder setDescription(String description) {
      this.description = firstNonNull(description, Data.<String>nullOf(String.class));
      return this;
    }

    @Override
    Builder setEtag(String etag) {
      this.etag = etag;
      return this;
    }

    @Override
    public Builder setExpirationTime(Long expirationTime) {
      this.expirationTime = firstNonNull(expirationTime, Data.<Long>nullOf(Long.class));
      return this;
    }

    @Override
    public Builder setFriendlyName(String friendlyName) {
      this.friendlyName = firstNonNull(friendlyName, Data.<String>nullOf(String.class));
      return this;
    }

    @Override
    Builder setGeneratedId(String generatedId) {
      this.generatedId = generatedId;
      return this;
    }

    @Override
    Builder setLastModifiedTime(Long lastModifiedTime) {
      this.lastModifiedTime = lastModifiedTime;
      return this;
    }

    @Override
    Builder setNumBytes(Long numBytes) {
      this.numBytes = numBytes;
      return this;
    }

    @Override
    Builder setNumLongTermBytes(Long numLongTermBytes) {
      this.numLongTermBytes = numLongTermBytes;
      return this;
    }

    @Override
    Builder setNumRows(BigInteger numRows) {
      this.numRows = numRows;
      return this;
    }

    @Override
    Builder setSelfLink(String selfLink) {
      this.selfLink = selfLink;
      return this;
    }

    @Override
    public Builder setTableId(TableId tableId) {
      this.tableId = checkNotNull(tableId);
      return this;
    }

    @Override
    public Builder setDefinition(TableDefinition definition) {
      this.definition = checkNotNull(definition);
      return this;
    }

    @Override
    public Builder setEncryptionConfiguration(EncryptionConfiguration configuration) {
      this.encryptionConfiguration = configuration;
      return this;
    }

    @Override
    public Builder setLabels(Map<String, String> labels) {
      this.labels = Labels.fromUser(labels);
      return this;
    }

    @Override
    public Builder setRequirePartitionFilter(Boolean requirePartitionFilter) {
      this.requirePartitionFilter = requirePartitionFilter;
      return this;
    }

    @Override
    public TableInfo build() {
      return new TableInfo(this);
    }
  }

  TableInfo(BuilderImpl builder) {
    this.tableId = checkNotNull(builder.tableId);
    this.etag = builder.etag;
    this.generatedId = builder.generatedId;
    this.selfLink = builder.selfLink;
    this.friendlyName = builder.friendlyName;
    this.description = builder.description;
    this.creationTime = builder.creationTime;
    this.expirationTime = builder.expirationTime;
    this.lastModifiedTime = builder.lastModifiedTime;
    this.numBytes = builder.numBytes;
    this.numLongTermBytes = builder.numLongTermBytes;
    this.numRows = builder.numRows;
    this.definition = builder.definition;
    this.encryptionConfiguration = builder.encryptionConfiguration;
    labels = builder.labels;
    this.requirePartitionFilter = builder.requirePartitionFilter;
  }

  /** Returns the hash of the table resource. */
  public String getEtag() {
    return etag;
  }

  /** Returns the service-generated id for the table. */
  public String getGeneratedId() {
    return generatedId;
  }

  /**
   * Returns an URL that can be used to access the resource again. The returned URL can be used for
   * get or update requests.
   */
  public String getSelfLink() {
    return selfLink;
  }

  /** Returns the table identity. */
  public TableId getTableId() {
    return tableId;
  }

  /** Returns a user-friendly name for the table. */
  public String getFriendlyName() {
    return Data.isNull(friendlyName) ? null : friendlyName;
  }

  /** Returns a user-friendly description for the table. */
  public String getDescription() {
    return Data.isNull(description) ? null : description;
  }

  /** Returns the time when this table was created, in milliseconds since the epoch. */
  public Long getCreationTime() {
    return creationTime;
  }

  /**
   * Returns the time when this table expires, in milliseconds since the epoch. If not present, the
   * table will persist indefinitely. Expired tables will be deleted and their storage reclaimed.
   */
  public Long getExpirationTime() {
    return Data.isNull(expirationTime) ? null : expirationTime;
  }

  /** Returns the time when this table was last modified, in milliseconds since the epoch. */
  public Long getLastModifiedTime() {
    return lastModifiedTime;
  }

  public EncryptionConfiguration getEncryptionConfiguration() {
    return encryptionConfiguration;
  }

  /** Returns the table definition. */
  @SuppressWarnings("unchecked")
  public <T extends TableDefinition> T getDefinition() {
    return (T) definition;
  }

  /** Returns the size of this table in bytes */
  public Long getNumBytes() {
    return numBytes;
  }

  /**
   * Returns the number of bytes considered "long-term storage" for reduced billing purposes.
   *
   * @see Long Term Storage
   *     Pricing
   */
  public Long getNumLongTermBytes() {
    return numLongTermBytes;
  }

  /** Returns the number of rows of data in this table */
  public BigInteger getNumRows() {
    return numRows;
  }

  /**
   * Return a map for labels applied to the table.
   *
   *
Unstable, because labels are experimental.
   */
  @BetaApi
  public Map<String, String> getLabels() {
    return labels.userMap();
  }

  /**
   * Returns true if a partition filter (that can be used for partition elimination) is required for
   * queries over this table.
   */
  public Boolean getRequirePartitionFilter() {
    return requirePartitionFilter;
  }

  /** Returns a builder for the table object. */
  public Builder toBuilder() {
    return new BuilderImpl(this);
  }

  @Override
  public String toString() {
    return MoreObjects.toStringHelper(this)
        .add("tableId", tableId)
        .add("etag", etag)
        .add("generatedId", generatedId)
        .add("selfLink", selfLink)
        .add("friendlyName", friendlyName)
        .add("description", description)
        .add("expirationTime", expirationTime)
        .add("creationTime", creationTime)
        .add("lastModifiedTime", lastModifiedTime)
        .add("numBytes", numBytes)
        .add("numLongTermBytes", numLongTermBytes)
        .add("numRows", numRows)
        .add("definition", definition)
        .add("encryptionConfiguration", encryptionConfiguration)
        .add("labels", labels)
        .add("requirePartitionFilter", requirePartitionFilter)
        .toString();
  }

  @Override
  public int hashCode() {
    return Objects.hash(tableId);
  }

  @Override
  public boolean equals(Object obj) {
    return obj == this
        || obj != null
            && obj.getClass().equals(TableInfo.class)
            && Objects.equals(toPb(), ((TableInfo) obj).toPb());
  }

  /**
   * Returns a builder for a {@code TableInfo} object given table identity and definition. Use
   * {@link StandardTableDefinition} to create simple BigQuery table. Use {@link ViewDefinition} to
   * create a BigQuery view. Use {@link ExternalTableDefinition} to create a BigQuery a table backed
   * by external data.
   */
  public static Builder newBuilder(TableId tableId, TableDefinition definition) {
    return new BuilderImpl().setTableId(tableId).setDefinition(definition);
  }

  /**
   * Returns a {@code TableInfo} object given table identity and definition. Use {@link
   * StandardTableDefinition} to create simple BigQuery table. Use {@link ViewDefinition} to create
   * a BigQuery view. Use {@link ExternalTableDefinition} to create a BigQuery a table backed by
   * external data.
   */
  public static TableInfo of(TableId tableId, TableDefinition definition) {
    return newBuilder(tableId, definition).build();
  }

  TableInfo setProjectId(String projectId) {
    if (Strings.isNullOrEmpty(getTableId().getProject())) {
      return toBuilder().setTableId(getTableId().setProjectId(projectId)).build();
    }
    return this;
  }

  Table toPb() {
    Table tablePb = definition.toPb();
    tablePb.setTableReference(tableId.toPb());
    if (lastModifiedTime != null) {
      tablePb.setLastModifiedTime(BigInteger.valueOf(lastModifiedTime));
    }
    tablePb.setCreationTime(creationTime);
    tablePb.setDescription(description);
    tablePb.setEtag(etag);
    tablePb.setExpirationTime(expirationTime);
    tablePb.setFriendlyName(friendlyName);
    tablePb.setId(generatedId);
    tablePb.setSelfLink(selfLink);
    if (encryptionConfiguration != null) {
      tablePb.setEncryptionConfiguration(encryptionConfiguration.toPb());
    }
    tablePb.setLabels(labels.toPb());
    tablePb.setRequirePartitionFilter(requirePartitionFilter);
    return tablePb;
  }

  static TableInfo fromPb(Table tablePb) {
    return new BuilderImpl(tablePb).build();
  }
}


text:
package com.github.salvatorenovelli.io;

import com.github.salvatorenovelli.redirectcheck.io.RedirectSpecExcelParser;
import com.github.salvatorenovelli.redirectcheck.model.RedirectSpecification;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.github.salvatorenovelli.redirectcheck.io.RedirectSpecExcelParser.DEFAULT_STATUS_CODE;
import static org.apache.poi.ss.usermodel.CellType.BLANK;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertThat;

@RunWith(MockitoJUnitRunner.class)
public class RedirectSpecExcelParserTest {

    @Rule
    public TemporaryFolder temporaryFolder = new TemporaryFolder();

    private List<RedirectSpecification> specs = new ArrayList<>();

    @Test
    public void lineNumberShouldBeSetCorrectly() throws Exception {
        String filename = givenAnExcelFile()
                .withRow("SourceURI1", "ExpectedDestination1")
                .withRow("SourceURI2", "ExpectedDestination2")
                .get();

        RedirectSpecExcelParser sut = new RedirectSpecExcelParser(filename);
        sut.parse(specs::add);

        assertThat(specs, hasSize(2));
        assertThat(specs.get(0).getLineNumber(), is(1));
        assertThat(specs.get(1).getLineNumber(), is(2));
    }

    @Test
    public void shouldAcceptOptionalExpectedStatusCode() throws Exception {

        String filename = givenAnExcelFile()
                .withRow("SourceURI1", "ExpectedDestination1", 1234)
                .get();

        new RedirectSpecExcelParser(filename).parse(specs::add);

        assertThat(specs, hasSize(1));
        assertThat(specs.get(0).getSourceURI(), is("SourceURI1"));
        assertThat(specs.get(0).getExpectedDestination(), is("ExpectedDestination1"));
        assertThat(specs.get(0).getExpectedStatusCode(), is(1234));

    }

    @Test
    public void shouldAcceptOptionalExpectedStatusCodesString() throws Exception {

        String filename = givenAnExcelFile()
                .withRow("SourceURI1", "ExpectedDestination1", "2234")
                .get();

        new RedirectSpecExcelParser(filename).parse(specs::add);

        assertThat(specs, hasSize(1));
        assertThat(specs.get(0).getSourceURI(), is("SourceURI1"));
        assertThat(specs.get(0).getExpectedDestination(), is("ExpectedDestination1"));
        assertThat(specs.get(0).getExpectedStatusCode(), is(2234));

    }

    @Test
    public void shouldAcceptEmptyStatusCode() throws Exception {

        String filename = givenAnExcelFile()
                .withRow("SourceURI1", "ExpectedDestination1", "")
                .get();

        new RedirectSpecExcelParser(filename).parse(specs::add);

        assertThat(specs, hasSize(1));
        assertThat(specs.get(0).getExpectedStatusCode(), is(DEFAULT_STATUS_CODE));
    }

    @Test
    public void shouldAcceptBlankStatusCode() throws Exception {

        String filename = givenAnExcelFile()
                .withRow("SourceURI1", "ExpectedDestination1", BLANK)
                .get();

        new RedirectSpecExcelParser(filename).parse(specs::add);

        assertThat(specs, hasSize(1));
        assertThat(specs.get(0).getExpectedStatusCode(), is(DEFAULT_STATUS_CODE));
    }

    @Test
    public void specificationWithoutExpectedDestinationShouldBeConsideredAsInvalid() throws Exception {
        String filename = givenAnExcelFile()
                .withRow("SourceURI1", "ExpectedDestination1", "1234")
                .withRow("sourceURI")
                .get();

        new RedirectSpecExcelParser(filename).parse(specs::add);

        assertThat(valid(specs), hasSize(1));
        assertThat(invalid(specs), hasSize(1));
    }

    @Test
    public void whenNoStatusCodeIsSpecifiedShouldDefaultTo200() throws Exception {

        String filename = givenAnExcelFile()
                .withRow("SourceURI1", "ExpectedDestination1")
                .get();

        new RedirectSpecExcelParser(filename).parse(specs::add);

        assertThat(specs, hasSize(1));
        assertThat(specs.get(0).getSourceURI(), is("SourceURI1"));
        assertThat(specs.get(0).getExpectedDestination(), is("ExpectedDestination1"));
        assertThat(specs.get(0).getExpectedStatusCode(), is(200));

    }

    @Test
    public void shouldBeAbleToParseXls() throws Exception {

        String filename = givenAnExcelFile()
                .withRow("SourceURI1", "ExpectedDestination1")
                .withRow("SourceURI2", "ExpectedDestination2")
                .get();

        RedirectSpecExcelParser sut = new RedirectSpecExcelParser(filename);
        sut.parse(specs::add);

        assertThat(specs, hasSize(2));
        assertThat(specs.get(0).getSourceURI(), is("SourceURI1"));
        assertThat(specs.get(0).getExpectedDestination(), is("ExpectedDestination1"));

        assertThat(specs.get(1).getSourceURI(), is("SourceURI2"));
        assertThat(specs.get(1).getExpectedDestination(), is("ExpectedDestination2"));
    }

    @Test
    public void shouldBeAbleToParseXlsx() throws Exception {

        String filename = givenAnExcelXFile()
                .withRow("SourceURI1", "ExpectedDestination1")
                .withRow("SourceURI2", "ExpectedDestination2")
                .get();

        new RedirectSpecExcelParser(filename).parse(specs::add);

        assertThat(specs, hasSize(2));
        assertThat(specs.get(0).getSourceURI(), is("SourceURI1"));
        assertThat(specs.get(0).getExpectedDestination(), is("ExpectedDestination1"));

        assertThat(specs.get(1).getSourceURI(), is("SourceURI2"));
        assertThat(specs.get(1).getExpectedDestination(), is("ExpectedDestination2"));
    }

    @Test
    public void rowNumberShouldBeCountedForValidAndInvalidSpecs() throws Exception {

        String filename = givenAnExcelXFile()
                .withRow("SourceURI1", "ExpectedDestination1")
                .withRow("SourceURI3")
                .withRow("SourceURI4", "ExpectedDestination4")
                .get();

        new RedirectSpecExcelParser(filename).parse(specs::add);

        assertThat(valid(specs), hasSize(2));
        assertThat(invalid(specs), hasSize(1));

        assertThat(valid(specs).get(0).getLineNumber(), is(1));
        assertThat(invalid(specs).get(0).getLineNumber(), is(2));
        assertThat(valid(specs).get(1).getLineNumber(), is(3));
    }

    @Test
    public void parserReturnMeaningfulErrorWhenSourceUriIsMissing() throws Exception {
        String filename = givenAnExcelXFile()
                .withRow("", "ExpectedDestination1")
                .get();

        new RedirectSpecExcelParser(filename).parse(specs::add);

        assertThat(invalid(specs), hasSize(1));
        assertThat(specs.get(0).getErrorMessage(), containsString("'Source URI' parameter is invalid or missing"));

    }

    @Test
    public void parserReturnMeaningfulErrorWhenExpectedUriIsNull() throws Exception {
        String filename = givenAnExcelXFile()
                .withRow("SourceUri")
                .get();

        new RedirectSpecExcelParser(filename).parse(specs::add);

        assertThat(invalid(specs), hasSize(1));
        assertThat(specs.get(0).getErrorMessage(), containsString("'Expected Destination' parameter is invalid or missing"));
    }

    @Test
    public void parserReturnMeaningfulErrorWhenExpectedUriIsEmpty() throws Exception {
        String filename = givenAnExcelXFile()
                .withRow("SourceUri", "")
                .get();

        new RedirectSpecExcelParser(filename).parse(specs::add);
        assertThat(invalid(specs), hasSize(1));
        assertThat(specs.get(0).getErrorMessage(), containsString("'Expected Destination' parameter is invalid or missing"));
    }

    @Test
    public void shouldReturnTheNumberOfRows() throws Exception {
        int NUM_ROWS = 10;
        String filename = givenAnExcelFileWithRows(NUM_ROWS);
        RedirectSpecExcelParser parser = new RedirectSpecExcelParser(filename);
        assertThat(parser.getNumSpecs(), is(NUM_ROWS));
    }

    @Test
    public void hiddenSheetsShouldNotBeConsidered() throws Exception {
        final String filename = givenAnExcelFile()
                .withAnHiddenSheetAsFirstSheet()
                .withRow("SourceURI1", "ExpectedDestination1")
                .get();

        RedirectSpecExcelParser parser = new RedirectSpecExcelParser(filename);
        assertThat(parser.getNumSpecs(), is(1));
    }

    @Test
    public void veryHiddenSheetsShouldNotBeConsidered() throws Exception {
        final String filename = givenAnExcelFile()
                .withAVeryHiddenSheetAsFirstSheet()
                .withRow("SourceURI1", "ExpectedDestination1")
                .get();

        RedirectSpecExcelParser parser = new RedirectSpecExcelParser(filename);
        assertThat(parser.getNumSpecs(), is(1));
    }

    private String givenAnExcelFileWithRows(int NUM_ROWS) throws IOException {
        ExcelTestFileBuilder excelTestFileBuilder = givenAnExcelFile();
        for (int i = 0; i < NUM_ROWS; i++) {
            excelTestFileBuilder.withRow("SourceURI" + i, "ExpectedDestination" + i);
        }
        return excelTestFileBuilder.get();
    }

    private List<RedirectSpecification> invalid(List<RedirectSpecification> specs) {
        return specs.stream().filter(it -> !it.isValid()).collect(Collectors.toList());
    }

    private List<RedirectSpecification> valid(List<RedirectSpecification> specs) {
        return specs.stream().filter(it -> it.isValid()).collect(Collectors.toList());
    }

    private ExcelTestFileBuilder givenAnExcelXFile() {
        return new ExcelTestFileBuilder(true);
    }

    private ExcelTestFileBuilder givenAnExcelFile() {
        return new ExcelTestFileBuilder(false);
    }

    class ExcelTestFileBuilder {

        private final Workbook workbook;
        private final Sheet sheet;
        private int curRowNumber = 0;

        ExcelTestFileBuilder(boolean xslsx) {
            if (xslsx) {
                this.workbook = new XSSFWorkbook();
            } else {
                this.workbook = new HSSFWorkbook();
            }

            this.sheet = workbook.createSheet("Test sheet");
        }

        ExcelTestFileBuilder withAnHiddenSheetAsFirstSheet() {
            String hiddenSheetName = "HiddenSheet";
            Sheet hiddenSheet = workbook.createSheet(hiddenSheetName);
            workbook.setSheetOrder(hiddenSheetName, 0);
            workbook.setSheetHidden(workbook.getSheetIndex(hiddenSheet), Workbook.SHEET_STATE_HIDDEN);
            return this;
        }

        public ExcelTestFileBuilder withAVeryHiddenSheetAsFirstSheet() {
            String hiddenSheetName = "VeryHiddenSheet";
            Sheet hiddenSheet = workbook.createSheet(hiddenSheetName);
            workbook.setSheetOrder(hiddenSheetName, 0);
            workbook.setSheetHidden(workbook.getSheetIndex(hiddenSheet), Workbook.SHEET_STATE_VERY_HIDDEN);
            return this;
        }

        ExcelTestFileBuilder withRow(Object... values) {
            Row row = sheet.createRow(curRowNumber++);
            int cellNumber = 0;
            for (Object value : values) {
                if (value instanceof String) {
                    row.createCell(cellNumber++).setCellValue((String) value);
                }
                if (value instanceof Number) {
                    row.createCell(cellNumber++).setCellValue( ((Number) value).doubleValue());
                }
                if(value == BLANK){
                    row.createCell(cellNumber++).setCellType(BLANK);
                }
            }
            return this;
        }

        String get() throws IOException {
            File file = temporaryFolder.newFile();
            FileOutputStream out = new FileOutputStream(file);
            workbook.write(out);
            out.close();
            return file.getPath();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<Locale>
  <Name>Français (fr-FR)</Name>
  <Common>
    <Cancel>Annuler</Cancel>
    <Close>Fermer</Close>
    <Next>Prochaine</Next>
    <OK>Bien</OK>
    <Previous>Précédente</Previous>
    <No>Aucun</No>
    <Yes>Oui</Yes>
    <Unread>Non lus</Unread>
  </Common>
  <JumpList>
    <DefaultAccount>Compte par défaut</DefaultAccount>
    <Inbox>Allez à votre boîte de réception</Inbox>
    <Compose>Composer de nouveau Courriel</Compose>
    <Check>Vérifiez de nouveau Courriel</Check>
    <Preferences>Préférences</Preferences>
    <About>Sur Gmail Notifier Plus</About>
    <Help>Aide Wiki</Help>
  </JumpList>
  <About>
    <WindowTitle>Sur</WindowTitle>
    <Button>Sweet. Merci !</Button>
    <FirstRun>Allons-y!</FirstRun>
    <Donate>Merci de considérer faire un don</Donate>
  </About>
  <Preferences>
    <WindowTitle>Préférences</WindowTitle>
    <Navigation>
      <General>Préférences générales</General>
      <Accounts>Gérer vos comptes</Accounts>
      <Appearance>Préférences d'affichage de changement</Appearance>
      <Donate>Veuillez faire un don</Donate>
    </Navigation>
    <Panels>
      <General>
        <Title>Paramètres généraux de Gmail Notifier Plus</Title>
        <ApplyChanges>Appliquer les modifications</ApplyChanges>
        <Sound>
          <Title>Notification sonore</Title>
          <None>Aucun</None>
          <Default>Par défaut</Default>
          <Custom>Personnalisé...</Custom>
          <Browse>Parcourir...</Browse>
          <BrowseWindowTitle>Sélectionnez un son de notification</BrowseWindowTitle>
          <WaveFiles>Fichier wave</WaveFiles>
        </Sound>
        <CheckEmail>Vérification de courriel intervalle (en minutes)</CheckEmail>
        <Language>Langue d'affichage</Language>
        <FlashTaskbar>Flash de la barre des tâches pour le nouveau Courriel</FlashTaskbar>
        <ShowTray>Montrer le comte de courriel dans la barre d'état système</ShowTray>
        <ShowToast>Afficher les notifications Toast pour nouveau Courriel</ShowToast>
      </General>
      <Accounts>
        <Title>Choisissez le compte que vous souhaitez modifier</Title>
        <AddNew>Ajouter un nouveau compte</AddNew>
        <Account>
          <Title>Gérer {0}</Title>
          <Address>Adresse de Courriel</Address>
          <Password>Mot de passe</Password>
          <Mailto>Utilisez ce compte pour des liens mailto</Mailto>
          <DefaultAccount>Utiliser ce compte comme compte par défaut</DefaultAccount>
          <Browser>Navigateur</Browser>
          <AddAccount>Ajoutez le compte</AddAccount>
          <RemoveAccount>Supprimer ce compte</RemoveAccount>
          <RemoveConfirmation>Êtes-vous sûr de que vouloir supprimer ce compte ?</RemoveConfirmation>
          <RemoveConfirmationTitle>Supprimer le compte</RemoveConfirmationTitle>
          <AccountsIntroNone>Bienvenue à Gmail Notifier Plus.\n\nTo commencer, veuillez cliquer sur le bouton ci-dessous pour ajouter un nouveau compte.</AccountsIntroNone>
          <Error>Il existe déjà un compte avec cette adresse. Veuillez entrer une adresse différente.</Error>
        </Account>
      </Accounts>
    </Panels>
  </Preferences>
  <Thumbnails>
    <CheckLogin>Veuillez vérifier les paramètres de votre compte</CheckLogin>
    <Connecting>Vérifier de nouveau Courriel...</Connecting>
    <ConnectionUnavailable>Veuillez vérifier votre connexion réseau</ConnectionUnavailable>
    <Inbox>Boîte de réception</Inbox>
    <NoSubject>(aucun sujet)</NoSubject>
    <NoAccount>Veuillez ajouter un compte</NoAccount>
    <NoMail>Aucun nouveau message</NoMail>
  </Thumbnails>
  <Toast>
    <ViewEmail>Voir ce courriel</ViewEmail>
    <NoSubject>(aucun sujet)</NoSubject>
  </Toast>
  <Updates>
    <WindowTitle>Mise à jour</WindowTitle>
    <Text>Une nouvelle version de Gmail Notifier Plus a été téléchargée et il est prête ! Vous pouvez redémarrer Gmail Notifier Plus maintenant d'appliquer la mise à jour.</Text>
    <YesText>Redémarrez Gmail Notifier Plus</YesText>
    <YesInstruction>J'ai besoin de la chaleur de nouveau.</YesInstruction>
    <NoText>Non merci</NoText>
    <NoInstruction>J'aimerais vivre sur le bord.</NoInstruction>
  </Updates>
</Locale>