text:
// Copyright (c) 2017-2019 Jae-jun Kang
// See the file LICENSE for details.

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace x2net.xpiler
{
    class CSharpFormatter : Formatter
    {
        private const string Extension = ".cs";

        public override string Description { get { return "C#"; } }

        public override bool Format(Unit unit, string outDir)
        {
            try
            {
                var context = new CSharpFormatterContext()
                {
                    Unit = unit,
                    Target = Path.Combine(outDir, unit.BaseName + Extension)
                };
                using (var writer = new StreamWriter(new FileStream(context.Target, FileMode.Create)))
                {
                    context.Writer = writer;
                    FormatHead(context);
                    FormatBody(context);
                    writer.Flush();
                }
            }
            catch (IOException)
            {
                // mayt be in the middle of processing
                return true;
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e);
                return false;
            }
            return true;
        }

        private void FormatHead(CSharpFormatterContext context)
        {
            var o = context.Writer;
            o.WriteLine("// auto-generated by x2net.xpiler");
            o.WriteLine();
            o.WriteLine("using System;");
            o.WriteLine("using System.Collections.Generic;");
            o.WriteLine("using System.Text;");
            o.WriteLine();
            o.WriteLine("using x2net;");
            o.WriteLine();

            foreach (var reference in context.Unit.References)
            {
                reference.Format(context);
            }
        }

        private void FormatBody(CSharpFormatterContext context)
        {
            var o = context.Writer;
            if (!String.IsNullOrEmpty(context.Unit.Namespace))
            {
                o.WriteLine("namespace {0}", context.Unit.Namespace.Replace('/', '.'));
                o.WriteLine("{");
                context.Indent();
            }
            var leading = true;
            foreach (var def in context.Unit.Definitions)
            {
                if (leading)
                {
                    leading = false;
                }
                else
                {
                    context.NewLine();
                }
                def.Format(context);
            }
            if (!String.IsNullOrEmpty(context.Unit.Namespace))
            {
                context.Unindent();
                o.WriteLine("}");
            }
        }

        public override bool IsUpToDate(string path, string outDir)
        {
            var baseName = Path.GetFileNameWithoutExtension(path);
            var target = Path.Combine(outDir, baseName + Extension);
            return File.Exists(target) &&
                   File.GetLastWriteTime(target) >= File.GetLastWriteTime(path);
        }
    }

    class CSharpFormatterContext : FormatterContext
    {
        private const string Tab = "    ";

        private static Dictionary<string, string> nativeTypes;
        private static Dictionary<string, string> defaultValues;
        private static HashSet<string> keywords;

        private int baseIndentation = 0;

        static CSharpFormatterContext()
        {
            nativeTypes = new Dictionary<string, string>();
            nativeTypes.Add("bool", "bool");
            nativeTypes.Add("byte", "byte");
            nativeTypes.Add("bytes", "byte[]");
            nativeTypes.Add("int8", "sbyte");
            nativeTypes.Add("int16", "short");
            nativeTypes.Add("int32", "int");
            nativeTypes.Add("int64", "long");
            nativeTypes.Add("float32", "float");
            nativeTypes.Add("float64", "double");
            nativeTypes.Add("string", "string");
            nativeTypes.Add("datetime", "DateTime");
            nativeTypes.Add("list", "List");
            nativeTypes.Add("map", "Dictionary");

            defaultValues = new Dictionary<string, string>();
            defaultValues.Add("bool", "false");
            defaultValues.Add("byte", "0");
            defaultValues.Add("bytes", "null");
            defaultValues.Add("int8", "0");
            defaultValues.Add("int16", "0");
            defaultValues.Add("int32", "0");
            defaultValues.Add("int64", "0");
            defaultValues.Add("float32", ".0f");
            defaultValues.Add("float64", ".0");
            defaultValues.Add("datetime", "new DateTime(621355968000000000)");
            defaultValues.Add("string", "");

            keywords = new HashSet<string>  {
                "abstract","event","new","struct","as","explicit","null","switch","base","extern",
                "this","false","operator","throw","break","finally","out","true",
                "fixed","override","try","case","params","typeof","catch","for",
                "private","foreach","protected","checked","goto","public",
                "unchecked","class","if","readonly","unsafe","const","implicit","ref",
                "continue","in","return","using","virtual","default",
                "interface","sealed","volatile","delegate","internal","do","is",
                "sizeof","while","lock","stackalloc","else","static","enum",
                "namespace",
                "object","bool","byte","float","uint","char","ulong","ushort",
                "decimal","int","sbyte","short","double","long","string","void",
                "partial", "yield", "where"
            };
        }

        public string Target { get; set; }

        public override void FormatCell(CellDef def)
        {
            def.BaseClass = def.Base;
            if (String.IsNullOrEmpty(def.BaseClass))
            {
                def.BaseClass = (def.IsEvent ? "Event" : "Cell");
            }
            PreprocessProperties(def);

            FormatComment(0, def.Comment);
            Out(0, "public class {0} : {1}", def.Name, def.BaseClass);
            Out(0, "{");
            Out(1, "protected static new readonly Tag tag;");
            NewLine();
            if (def.IsEvent)
            {
                Out(1, "public static new int TypeId { get { return tag.TypeId; } }");
                NewLine();
            }
            FormatFields(def);
            if (def.HasProperties)
            {
                NewLine();
            }
            FormatProperties(def);
            if (def.HasProperties)
            {
                NewLine();
            }
            FormatMethods(def);
            Out(0, "}");
        }

        public override void FormatConsts(ConstsDef def)
        {
            if (nativeTypes.ContainsKey(def.Type))
            {
                def.NativeType = nativeTypes[def.Type];
            }
            else
            {
                return;
            }

            PreprocessConsts(def);

            FormatComment(0, def.Comment);
            Out(0, "public static class {0}", def.Name);
            Out(0, "{");
            foreach (var constant in def.Constants)
            {
                FormatComment(1, constant.Comment);
                Indent(1);
                Writer.Write("public const {0} {1}", def.NativeType, constant.Name);
                if (!String.IsNullOrEmpty(constant.Value))
                {
                    Writer.Write(" = {0}", constant.Value);
                }
                Writer.Write(';');
                NewLine();
            }
            NewLine();
            Out(1, "private static ConstsInfo<{0}> info;", def.NativeType);
            NewLine();
            Out(1, "static {0}()", def.Name);
            Out(1, "{");
            Out(2, "info = new ConstsInfo<{0}>();", def.NativeType);
            foreach (var constant in def.Constants)
            {
                Out(2, "info.Add(\"{0}\", {1});", constant.Name, constant.Value);
            }
            Out(1, "}");
            NewLine();
            Out(1, "public static bool ContainsName(string name)", def.NativeType);
            Out(1, "{");
            Out(2, "return info.ContainsName(name);");
            Out(1, "}");
            NewLine();
            Out(1, "public static bool ContainsValue({0} value)", def.NativeType);
            Out(1, "{");
            Out(2, "return info.ContainsValue(value);");
            Out(1, "}");
            NewLine();
            Out(1, "public static IEnumerator<KeyValuePair<string, {0}>> GetEnumerator()", def.NativeType);
            Out(1, "{");
            Out(2, "return info.GetEnumerator();");
            Out(1, "}");
            NewLine();
            Out(1, "public static string GetName({0} value)", def.NativeType);
            Out(1, "{");
            Out(2, "return info.GetName(value);");
            Out(1, "}");
            NewLine();
            Out(1, "public static {0} Parse(string name)", def.NativeType);
            Out(1, "{");
            Out(2, "return info.Parse(name);");
            Out(1, "}");
            NewLine();
            Out(1, "public static bool TryParse(string name, out {0} result)", def.NativeType);
            Out(1, "{");
            Out(2, "return info.TryParse(name, out result);");
            Out(1, "}");
            Out(0, "}");
        }

        public override void FormatReference(Reference def)
        {
            Out(0, "using {0};", def.Target.Replace('/', '.'));
            NewLine();
        }

        private void FormatFields(CellDef def)
        {
            foreach (var property in def.Properties)
            {
                Out(1, "private {0} {1};", property.NativeType, property.NativeName);
            }
        }

        private void FormatProperties(CellDef def)
        {
            var leading = true;
            foreach (var property in def.Properties)
            {
                if (leading)
                {
                    leading = false;
                }
                else
                {
                    NewLine();
                }

                FormatComment(1, property.Comment);

                Out(1, "public {0} {1}", property.NativeType, property.SafeName);
                Out(1, "{");
                Out(2, "get {{ return {0}; }}", property.NativeName);
                Out(2, "set");
                Out(2, "{");
                Out(3, "fingerprint.Touch(tag.Offset + {0});", property.Index);
                Out(3, "{0} = value;", property.NativeName);
                Out(2, "}");
                Out(1, "}");
            }
        }

        private void FormatMethods(CellDef def)
        {
            FormatStaticConstructor(def);
            NewLine();
            FormatConstructor(def);
            NewLine();
            FormatEqualsTo(def);
            NewLine();
            FormatGetHashCode(def);
            NewLine();
            FormatGetType(def);
            NewLine();
            FormatIsEquivalent(def);
            if (!def.IsLocal)
            {
                NewLine();
                FormatDeserialize(def);
                NewLine();
                FormatSerialize(def);
            }
            FormatUpdate(def);
            NewLine();
            FormatDescribe(def);
            if (!def.IsLocal)
            {
                NewLine();
                FormatInitializer(def);
            }
        }

        private void FormatStaticConstructor(CellDef def)
        {
            string baseTag = def.Base;
            if (String.IsNullOrEmpty(baseTag))
            {
                baseTag = (def.IsEvent ? "Event.tag" : "null");
            }
            else
            {
                baseTag += ".tag";
            }
            Out(1, "static {0}()", def.Name);
            Out(1, "{");
            Indent(2);
            Writer.Write("tag = new Tag({0}, typeof({1}), {2}", baseTag, def.Name,
                def.Properties.Count);
            if (def.IsEvent)
            {
                int i;
                string s = ((EventDef)def).Id;
                Writer.WriteLine(",");
                Writer.Write("                    ");
                if (!Int32.TryParse(s, out i))
                {
                    Writer.Write("(int)");
                }
                Writer.Write("{0}", s);
            }
            Writer.WriteLine(");");
            Out(1, "}");

            if (def.IsEvent)
            {
                NewLine();
                Out(1, "public new static {0} New()", def.Name);
                Out(1, "{");
                Out(2, "return new {0}();", def.Name);
                Out(1, "}");
            }
        }

        private void FormatConstructor(CellDef def)
        {
            Out(1, "public {0}()", def.Name);
            Out(2, ": base(tag.NumProps)");
            Out(1, "{");
            if (!def.IsLocal)
            {
                Out(2, "Initialize();");
            }
            Out(1, "}");
            NewLine();
            Out(1, "protected {0}(int length)", def.Name);
            Out(2, ": base(length + tag.NumProps)");
            Out(1, "{");
            if (!def.IsLocal)
            {
                Out(2, "Initialize();");
            }
            Out(1, "}");
        }

        private void FormatEqualsTo(CellDef def)
        {
            Out(1, "protected override bool EqualsTo(Cell other)");
            Out(1, "{");
            Out(2, "if (!base.EqualsTo(other))");
            Out(2, "{");
            Out(3, "return false;");
            Out(2, "}");
            if (def.HasProperties)
            {
                Out(2, "{0} o = ({0})other;", def.Name);
                foreach (var property in def.Properties)
                {
                    if (Types.IsCollective(property.TypeSpec.Type))
                    {
                        Out(2, "if (!{0}.EqualsEx(o.{0}))", property.NativeName);
                    }
                    else
                    {
                        Out(2, "if ({0} != o.{0})", property.NativeName);
                    }
                    Out(2, "{");
                    Out(3, "return false;");
                    Out(2, "}");
                }
            }
            Out(2, "return true;");
            Out(1, "}");
        }

        private void FormatGetHashCode(CellDef def)
        {
            Out(1, "public override int GetHashCode(Fingerprint fingerprint)");
            Out(1, "{");
            Out(2, "var hash = new Hash(base.GetHashCode(fingerprint));");
            if (def.HasProperties)
            {
                Out(2, "if (fingerprint.Length <= tag.Offset)");
                Out(2, "{");
                Out(3, "return hash.Code;");
                Out(2, "}");

                Out(2, "var touched = new Capo<bool>(fingerprint, tag.Offset);");
                foreach (var property in def.Properties)
                {
                    Out(2, "if (touched[{0}])", property.Index);
                    Out(2, "{");
                    Out(3, "hash.Update(tag.Offset + {0});", property.Index);
                    Out(3, "hash.Update({0});", property.NativeName);
                    Out(2, "}");
                }
            }
            Out(2, "return hash.Code;");
            Out(1, "}");
        }

        private void FormatGetType(CellDef def)
        {
            if (def.IsEvent)
            {
                Out(1, "public override int GetTypeId()");
                Out(1, "{");
                Out(2, "return tag.TypeId;");
                Out(1, "}");
                NewLine();
            }

            Out(1, "public override Cell.Tag GetTypeTag() ");
            Out(1, "{");
            Out(2, "return tag;");
            Out(1, "}");

            if (def.IsEvent)
            {
                NewLine();
                Out(1, "public override Func<Event> GetFactoryMethod()");
                Out(1, "{");
                Out(2, "return {0}.New;", def.Name);
                Out(1, "}");
            }
        }

        private void FormatIsEquivalent(CellDef def)
        {
            Out(1, "protected override bool IsEquivalent(Cell other, Fingerprint fingerprint)");
            Out(1, "{");
            Out(2, "if (!base.IsEquivalent(other, fingerprint))");
            Out(2, "{");
            Out(3, "return false;");
            Out(2, "}");
            if (def.HasProperties)
            {
                Out(2, "{0} o = ({0})other;", def.Name);
                Out(2, "var touched = new Capo<bool>(fingerprint, tag.Offset);");

                foreach (var property in def.Properties)
                {
                    Out(2, "if (touched[{0}])", property.Index);
                    Out(2, "{");
                    if (Types.IsCollective(property.TypeSpec.Type))
                    {
                        Out(3, "if (!{0}.EqualsEx(o.{0}))", property.NativeName);
                    }
                    else
                    {
                        Out(3, "if ({0} != o.{0})", property.NativeName);
                    }
                    Out(3, "{");
                    Out(4, "return false;");
                    Out(3, "}");
                    Out(2, "}");
                }
            }
            Out(2, "return true;");
            Out(1, "}");
        }

        private void FormatDeserialize(CellDef def)
        {
            // Deserialize(Deserializer)
            Out(1, "public override void Deserialize(Deserializer deserializer)");
            Out(1, "{");
            Out(2, "base.Deserialize(deserializer);");
            if (def.HasProperties)
            {
                Out(2, "var touched = new Capo<bool>(fingerprint, tag.Offset);");
                foreach (var property in def.Properties)
                {
                    Out(2, "if (touched[{0}])", property.Index);
                    Out(2, "{");
                    Out(3, "deserializer.Read(out {0});", property.NativeName);
                    Out(2, "}");
                }
            }
            Out(1, "}");
        }

        private void FormatSerialize(CellDef def)
        {
            // GetLength
            Out(1, "public override int GetLength(Type targetType, ref bool flag)");
            Out(1, "{");
            Out(2, "int length = base.GetLength(targetType, ref flag);");
            Out(2, "if (!flag) { return length; }");
            if (def.HasProperties)
            {
                Out(2, "var touched = new Capo<bool>(fingerprint, tag.Offset);");
                foreach (var property in def.Properties)
                {
                    Out(2, "if (touched[{0}])", property.Index);
                    Out(2, "{");
                    Out(3, "length += Serializer.GetLength({0});", property.NativeName);
                    Out(2, "}");
                }
            }
            Out(2, "if (targetType != null && targetType == typeof({0}))", def.Name);
            Out(2, "{");
            Out(3, "flag = false;");
            Out(2, "}");
            Out(2, "return length;");
            Out(1, "}");

            // Serialize(Serializer)
            NewLine();
            Out(1, "public override void Serialize(Serializer serializer,");
            Out(2, "Type targetType, ref bool flag)");
            Out(1, "{");
            Out(2, "base.Serialize(serializer, targetType, ref flag);");
            Out(2, "if (!flag) { return; }");
            if (def.HasProperties)
            {
                Out(2, "var touched = new Capo<bool>(fingerprint, tag.Offset);");
                foreach (var property in def.Properties)
                {
                    Out(2, "if (touched[{0}])", property.Index);
                    Out(2, "{");
                    Out(3, "serializer.Write({0});", property.NativeName);
                    Out(2, "}");
                }
            }
            Out(2, "if (targetType != null && targetType == typeof({0}))", def.Name);
            Out(2, "{");
            Out(3, "flag = false;");
            Out(2, "}");
            Out(1, "}");
        }

        private void FormatDescribe(CellDef def)
        {
            Out(1, "protected override void Describe(StringBuilder stringBuilder)");
            Out(1, "{");
            Out(2, "base.Describe(stringBuilder);");
            foreach (var property in def.Properties)
            {
                Out(2, "stringBuilder.AppendFormat(\" {0}:{{0}}\", {1}.ToStringEx());",
                    property.Name, property.NativeName);
            }
            Out(1, "}");
        }

        private void FormatUpdate(CellDef def)
        {
            foreach (var property in def.Properties)
            {
                NewLine();
                Out(1, "public bool Has{0}()", FirstToUpper(property.Name));
                Out(1, "{");
                Out(2, "return fingerprint.Get(tag.Offset + {0});", property.Index);
                Out(1, "}");
            }

            if (def.Properties.Count != 0)
            {
                NewLine();
            }
            Out(1, "public void Update({0} o)", def.Name);
            Out(1, "{");
            foreach (var property in def.Properties)
            {
                Out(2, "if (o.Has{0}()) {{ {1} = o.{1}; }}",
                    FirstToUpper(property.Name), property.SafeName);
            }
            Out(1, "}");
        }

        private void FormatInitializer(CellDef def)
        {
            Out(1, "private void Initialize()");
            Out(1, "{");
            foreach (var property in def.Properties)
            {
                Out(2, "{0} = {1};", property.NativeName, property.DefaultValue);
            }
            Out(1, "}");
        }

        private void FormatComment(int indent, string text)
        {
            if (String.IsNullOrEmpty(text)) { return; }
            string[] lines = text.Split(new char[] { '\n', '\r' },
                StringSplitOptions.RemoveEmptyEntries);
            Out(indent, "/// <summary>");
            for (int i = 0; i < lines.Length; ++i)
            {
                Out(indent, "/// {0}", lines[i]);
            }
            Out(indent, "/// </summary>");
        }

        private static void PreprocessConsts(ConstsDef def)
        {
            if (def.Type == "string")
            {
                foreach (var constant in def.Constants)
                {
                    constant.Value = "\"" + constant.Value + "\"";
                }
            }
        }

        private static void PreprocessProperties(CellDef def)
        {
            int index = 0;
            foreach (var property in def.Properties)
            {
                property.Index = index++;

                property.Name = property.Name.TrimStart(' ', '\t', '\n', '\r', '_');
                property.Name = property.Name.TrimEnd(' ', '\t', '\n', '\r', '_');

                property.NativeName = FirstToLower(property.Name) + "_";
                if (!def.IsLocal && !def.AsIs)
                {
                    property.Name = FirstToUpper(property.Name);
                }

                // Avoid keywords
                if (isKeyword(property.Name))
                {
                    property.SafeName = "@" + property.Name;
                }
                else
                {
	                property.SafeName = property.Name;
                }

                if (Types.IsPrimitive(property.TypeSpec.Type))
                {
                    if (String.IsNullOrEmpty(property.DefaultValue))
                    {
                        property.DefaultValue = defaultValues[property.TypeSpec.Type];
                    }
                    if (property.TypeSpec.Type == "string")
                    {
                        property.DefaultValue = "\"" + property.DefaultValue + "\"";
                    }
                }
                else
                {
                    property.DefaultValue = "null";
                }

                property.NativeType = FormatTypeSpec(property.TypeSpec);
            }
        }

        private static string FormatTypeSpec(TypeSpec typeSpec)
        {
            string type = typeSpec.Type;
            if (!Types.IsBuiltin(type))
            {
                return type;  // custom type
            }
            return Types.IsPrimitive(type) ? nativeTypes[type]
                                           : FormatCollectiveType(typeSpec);
        }

        private static string FormatCollectiveType(TypeSpec typeSpec)
        {
            var sb = new StringBuilder(nativeTypes[typeSpec.Type]);
            if ((object)typeSpec.Details != null)
            {
                sb.Append('<');
                var leading = true;
                foreach (var detail in typeSpec.Details)
                {
                    if (leading)
                    {
                        leading = false;
                    }
                    else
                    {
                        sb.Append(", ");
                    }
                    sb.Append(FormatTypeSpec(detail));
                }
                sb.Append('>');
            }
            return sb.ToString();
        }

        #region WriterMethods

        private void Out(int indent, string format)
        {
            Indent(indent);
            Writer.WriteLine(format);
        }

        private void Out(int indent, string format, object arg0)
        {
            Indent(indent);
            Writer.WriteLine(format, arg0);
        }

        private void Out(int indent, string format, object arg0, object arg1)
        {
            Indent(indent);
            Writer.WriteLine(format, arg0, arg1);
        }

        private void Out(int indent, string format, object arg0, object arg1, object arg2)
        {
            Indent(indent);
            Writer.WriteLine(format, arg0, arg1, arg2);
        }

        private void Out(int indent, string format, object[] args)
        {
            Indent(indent);
            Writer.WriteLine(format, args);
        }

        public void NewLine()
        {
            Writer.WriteLine();
        }

        #endregion

        #region Indentation

        public void Indent()
        {
            ++baseIndentation;
        }

        public void Unindent()
        {
            --baseIndentation;
        }

        private void Indent(int level)
        {
            for (int i = 0; i < (baseIndentation + level); ++i)
            {
                Writer.Write(Tab);
            }
        }

        #endregion

        private static string FirstToLower(string s)
        {
            if (!String.IsNullOrEmpty(s))
            {
                var chars = s.ToCharArray();
                if (Char.IsUpper(chars[0]))
                {
                    chars[0] = Char.ToLower(chars[0]);
                    return new string(chars);
                }
            }
            return s;
        }

        private static string FirstToUpper(string s)
        {
            if (!String.IsNullOrEmpty(s))
            {
                var chars = s.ToCharArray();
                if (Char.IsLower(chars[0]))
                {
                    chars[0] = Char.ToUpper(chars[0]);
                    return new string(chars);
                }
                else if (chars[0] == '@')
                {
                    if (isKeyword(new string(chars, 1, chars.Length - 1)))
                    {
                        chars[1] = Char.ToUpper(chars[1]);
                        return new string(chars, 1, chars.Length - 1);
                    }
                }
            }
            return s;
        }

        private static bool isKeyword(string s)
        {
            return keywords.Contains(s);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.google.android.enterprise.connectedapps.processor.containers;

import com.google.android.enterprise.connectedapps.processor.TypeUtils;
import com.google.auto.value.AutoValue;
import java.util.Optional;
import javax.lang.model.type.TypeMirror;

/** A type which may be supported by a given {@code CrossProfileConfiguration}. */
@AutoValue
public abstract class Type {
  public static Builder builder() {
    return new AutoValue_Type.Builder()
        .setAcceptableParameterType(false)
        .setAcceptableReturnType(false)
        .setSupportedWithAnyGenericType(false)
        .setSupportedInsideWrapper(true)
        .setSupportedInsideCrossProfileCallback(true);
  }

  public abstract Builder toBuilder();

  public abstract TypeMirror getTypeMirror();

  public String getQualifiedName() {
    return getTypeMirror().toString();
  }

  public abstract boolean isAcceptableReturnType();

  public abstract boolean isAcceptableParameterType();

  public abstract Optional<String> getAutomaticallyResolvedReplacement();

  public boolean isArray() {
    return TypeUtils.isArray(getTypeMirror());
  }

  public boolean canBeBundled() {
    return getPutIntoBundleCode().isPresent() && getGetFromBundleCode().isPresent();
  }

  public boolean isPrimitive() {
    return getTypeMirror().getKind().isPrimitive();
  }

  public boolean isGeneric() {
    return TypeUtils.isGeneric(getTypeMirror());
  }

  /**
   * If this is set, then type arguments will not validated.
   *
   *
This allows for Parcelables which take responsibility for their own generics and do not use
   * Bundler.
   */
  public abstract boolean isSupportedWithAnyGenericType();

  /**
   * Can this type be used inside a wrapper type? For example a List or an array.
   *
   *
This allows for async listeners to only be acceptable as parameter types but not type
   * arguments
   */
  public abstract boolean isSupportedInsideWrapper();

  public abstract boolean isSupportedInsideCrossProfileCallback();

  public abstract Optional<FutureWrapper> getFutureWrapper();

  public boolean isFuture() {
    return getFutureWrapper().isPresent();
  }

  public abstract Optional<CrossProfileCallbackInterfaceInfo> getCrossProfileCallbackInterface();

  public boolean isCrossProfileCallbackInterface() {
    return getCrossProfileCallbackInterface().isPresent();
  }

  // If this is a generated Parcelable Wrapper then this will be set to the simple name
  // (e.g. ParcelableList)
  public abstract Optional<ParcelableWrapper> getParcelableWrapper();

  public abstract Optional<String> getPutIntoBundleCode();

  public abstract Optional<String> getGetFromBundleCode();

  public abstract Optional<String> getWriteToParcelCode();

  public abstract Optional<String> getReadFromParcelCode();

  /** A builder for {@link Type}. */
  @AutoValue.Builder
  public abstract static class Builder {

    public abstract Builder setTypeMirror(TypeMirror typeMirror);

    public abstract Builder setAcceptableReturnType(boolean acceptableReturnType);

    public abstract Builder setAcceptableParameterType(boolean acceptableParameterType);

    public abstract Builder setAutomaticallyResolvedReplacement(
        String automaticallyResolvedReplacement);

    public abstract Builder setSupportedWithAnyGenericType(boolean supportedWithAnyGenericType);

    public abstract Builder setSupportedInsideWrapper(boolean supportedInsideWrapper);

    public abstract Builder setSupportedInsideCrossProfileCallback(
        boolean supportedInsideCrossProfileCallback);

    public abstract Builder setFutureWrapper(FutureWrapper futureWrapper);

    public abstract Builder setCrossProfileCallbackInterface(
        CrossProfileCallbackInterfaceInfo crossProfileCallbackInterface);

    public abstract Builder setPutIntoBundleCode(String putIntoBundleCode);

    public abstract Builder setGetFromBundleCode(String getFromBundleCode);

    public abstract Builder setWriteToParcelCode(String writeToParcelCode);

    public abstract Builder setReadFromParcelCode(String readFromParcelCode);

    public abstract Builder setParcelableWrapper(ParcelableWrapper parcelableWrapper);

    public abstract Type build();
  }
}


text:
package com.structurizr.analysis.reflections;

import com.structurizr.Workspace;
import com.structurizr.analysis.*;
import com.structurizr.model.*;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;

public class AbstractComponentFinderStrategyTests {

    private Container webApplication;

    @Before
    public void setUp() {
        Workspace workspace = new Workspace("Name", "Description");
        Model model = workspace.getModel();

        SoftwareSystem softwareSystem = model.addSoftwareSystem("Name", "Description");
        webApplication = softwareSystem.addContainer("Name", "Description", "Technology");
    }

    @Test
    public void test_findComponents_DoesNotBreak_WhenThereIsACyclicDependency() throws Exception {
        ComponentFinder componentFinder = new ComponentFinder(
                webApplication,
                "com.structurizr.analysis.reflections.cyclicDependency",
                new TypeMatcherComponentFinderStrategy(
                        new NameSuffixTypeMatcher("Component", "", "")
                )
        );
        componentFinder.findComponents();

        assertEquals(2, webApplication.getComponents().size());

        Component aComponent = webApplication.getComponentWithName("AComponent");
        assertNotNull(aComponent);
        assertEquals("AComponent", aComponent.getName());
        assertEquals("com.structurizr.analysis.reflections.cyclicDependency.AComponent", aComponent.getType().getType());

        Component bComponent = webApplication.getComponentWithName("BComponent");
        assertNotNull(bComponent);
        assertEquals("BComponent", bComponent.getName());
        assertEquals("com.structurizr.analysis.reflections.cyclicDependency.BComponent", bComponent.getType().getType());

        assertEquals(1, aComponent.getRelationships().size());
        assertNotNull(aComponent.getRelationships().stream().filter(r -> r.getDestination() == bComponent).findFirst().get());

        assertEquals(1, bComponent.getRelationships().size());
        assertNotNull(bComponent.getRelationships().stream().filter(r -> r.getDestination() == aComponent).findFirst().get());
    }

    @Test
    public void test_findComponents_CorrectlyFindsDependenciesFromSuperclass() throws Exception {
        ComponentFinder componentFinder = new ComponentFinder(
                webApplication,
                "com.structurizr.analysis.reflections.dependenciesFromSuperClass",
                new TypeMatcherComponentFinderStrategy(
                        new NameSuffixTypeMatcher("Component", "", "")
                )
        );
        componentFinder.findComponents();

        assertEquals(2, webApplication.getComponents().size());

        Component someComponent = webApplication.getComponentWithName("SomeComponent");
        assertNotNull(someComponent);
        assertEquals("SomeComponent", someComponent.getName());
        assertEquals("com.structurizr.analysis.reflections.dependenciesFromSuperClass.SomeComponent", someComponent.getType().getType());

        Component loggingComponent = webApplication.getComponentWithName("LoggingComponent");
        assertNotNull(loggingComponent);
        assertEquals("LoggingComponent", loggingComponent.getName());
        assertEquals("com.structurizr.analysis.reflections.dependenciesFromSuperClass.LoggingComponent", loggingComponent.getType().getType());

        assertEquals(1, someComponent.getRelationships().size());
        assertNotNull(someComponent.getRelationships().stream().filter(r -> r.getDestination() == loggingComponent).findFirst().get());
    }

    @Test
    public void test_findComponents_CorrectlyFindsNoDependenciesWhenTwoComponentsImplementTheSameInterface() throws Exception {
        ComponentFinder componentFinder = new ComponentFinder(
                webApplication,
                "com.structurizr.analysis.reflections.featureinterface",
                new TypeMatcherComponentFinderStrategy(
                        new NameSuffixTypeMatcher("Component", "", "")
                )
        );
        componentFinder.findComponents();

        assertEquals(2, webApplication.getComponents().size());

        Component someComponent = webApplication.getComponentWithName("SomeComponent");
        assertNotNull(someComponent);
        assertEquals("SomeComponent", someComponent.getName());
        assertEquals("com.structurizr.analysis.reflections.featureinterface.SomeComponent", someComponent.getType().getType());

        Component otherComponent = webApplication.getComponentWithName("OtherComponent");
        assertNotNull(otherComponent);
        assertEquals("OtherComponent", otherComponent.getName());
        assertEquals("com.structurizr.analysis.reflections.featureinterface.OtherComponent", otherComponent.getType().getType());

        assertEquals(0, someComponent.getRelationships().size());
        assertEquals(0, otherComponent.getRelationships().size());
    }

    @Test
    public void test_findComponents_CorrectlyFindsDependenciesBetweenComponentsFoundByDifferentComponentFinders_WhenPackage1IsScannedFirst() throws Exception {
        ComponentFinder componentFinder1 = new ComponentFinder(
                webApplication,
                "com.structurizr.analysis.reflections.multipleComponentFinders.package1",
                new TypeMatcherComponentFinderStrategy(
                        new NameSuffixTypeMatcher("Controller", "", "")
                )
        );

        ComponentFinder componentFinder2 = new ComponentFinder(
                webApplication,
                "com.structurizr.analysis.reflections.multipleComponentFinders.package2",
                new TypeMatcherComponentFinderStrategy(
                        new NameSuffixTypeMatcher("Repository", "", "")
                )
        );

        componentFinder1.findComponents();
        componentFinder2.findComponents();

        assertEquals(2, webApplication.getComponents().size());
        Component myController = webApplication.getComponentWithName("MyController");
        Component myRepository = webApplication.getComponentWithName("MyRepository");
        assertEquals(1, myController.getRelationships().size());
        assertNotNull(myController.getRelationships().stream().filter(r -> r.getDestination() == myRepository).findFirst().get());
    }

    @Test
    public void test_findComponents_CorrectlyFindsDependenciesBetweenComponentsFoundByDifferentComponentFinders_WhenPackage2IsScannedFirst() throws Exception {
        ComponentFinder componentFinder1 = new ComponentFinder(
                webApplication,
                "com.structurizr.analysis.reflections.multipleComponentFinders.package1",
                new TypeMatcherComponentFinderStrategy(
                        new NameSuffixTypeMatcher("Controller", "", "")
                )
        );

        ComponentFinder componentFinder2 = new ComponentFinder(
                webApplication,
                "com.structurizr.analysis.reflections.multipleComponentFinders.package2",
                new TypeMatcherComponentFinderStrategy(
                        new NameSuffixTypeMatcher("Repository", "", "")
                )
        );

        componentFinder2.findComponents();
        componentFinder1.findComponents();

        assertEquals(2, webApplication.getComponents().size());
        Component myController = webApplication.getComponentWithName("MyController");
        Component myRepository = webApplication.getComponentWithName("MyRepository");
        assertEquals(1, myController.getRelationships().size());
        assertNotNull(myController.getRelationships().stream().filter(r -> r.getDestination() == myRepository).findFirst().get());
    }

    @Test
    public void test_findComponents_CorrectlyFindsSupportingTypes_WhenTheDefaultStrategyIsUsed() throws Exception {
        ComponentFinder componentFinder = new ComponentFinder(
                webApplication,
                "com.structurizr.analysis.reflections.supportingTypes.myapp",
                new StructurizrAnnotationsComponentFinderStrategy()
        );
        componentFinder.findComponents();

        assertEquals(2, webApplication.getComponents().size());
        Component myController = webApplication.getComponentWithName("MyController");
        Component myRepository = webApplication.getComponentWithName("MyRepository");
        assertEquals(1, myController.getRelationships().size());
        assertNotNull(myController.getRelationships().stream().filter(r -> r.getDestination() == myRepository).findFirst().get());

        // the default strategy for supporting types is to find the first implementation
        // class if the component type is an interface
        assertEquals(1, myController.getCode().size());
        assertCodeElementInComponent(myController, "com.structurizr.analysis.reflections.supportingTypes.myapp.web.MyController", CodeElementRole.Primary);

        assertEquals(2, myRepository.getCode().size());
        assertCodeElementInComponent(myRepository, "com.structurizr.analysis.reflections.supportingTypes.myapp.data.MyRepository", CodeElementRole.Primary);
        assertCodeElementInComponent(myRepository, "com.structurizr.analysis.reflections.supportingTypes.myapp.data.MyRepositoryImpl", CodeElementRole.Supporting);
    }

    @Test
    public void test_findComponents_CorrectlyFindsSupportingTypes_WhenTheReferencedTypesInSamePackageSupportingTypesStrategyIsUsed() throws Exception {
        ComponentFinder componentFinder = new ComponentFinder(
                webApplication,
                "com.structurizr.analysis.reflections.supportingTypes.myapp",
                new StructurizrAnnotationsComponentFinderStrategy(
                        new FirstImplementationOfInterfaceSupportingTypesStrategy(),
                        new ReferencedTypesInSamePackageSupportingTypesStrategy()
                )
        );
        componentFinder.findComponents();

        assertEquals(2, webApplication.getComponents().size());
        Component myController = webApplication.getComponentWithName("MyController");
        Component myRepository = webApplication.getComponentWithName("MyRepository");
        assertEquals(1, myController.getRelationships().size());
        assertNotNull(myController.getRelationships().stream().filter(r -> r.getDestination() == myRepository).findFirst().get());

        assertEquals(1, myController.getCode().size());
        assertEquals(3, myRepository.getCode().size());
        assertCodeElementInComponent(myRepository, "com.structurizr.analysis.reflections.supportingTypes.myapp.data.MyRepository", CodeElementRole.Primary);
        assertCodeElementInComponent(myRepository, "com.structurizr.analysis.reflections.supportingTypes.myapp.data.MyRepositoryImpl", CodeElementRole.Supporting);
        assertCodeElementInComponent(myRepository, "com.structurizr.analysis.reflections.supportingTypes.myapp.data.MyRepositoryRowMapper", CodeElementRole.Supporting);
    }

    @Test
    public void test_findComponents_CorrectlyFindsSupportingTypes_WhenTheReferencedTypesStrategyIsUsedAndIndirectlyReferencedTypesShouldBeIncluded() throws Exception {
        ComponentFinder componentFinder = new ComponentFinder(
                webApplication,
                "com.structurizr.analysis.reflections.supportingTypes.myapp",
                new StructurizrAnnotationsComponentFinderStrategy(
                        new FirstImplementationOfInterfaceSupportingTypesStrategy(),
                        new ReferencedTypesSupportingTypesStrategy()
                )
        );
        componentFinder.findComponents();

        assertEquals(2, webApplication.getComponents().size());
        Component myController = webApplication.getComponentWithName("MyController");
        Component myRepository = webApplication.getComponentWithName("MyRepository");
        assertEquals(1, myController.getRelationships().size());
        assertNotNull(myController.getRelationships().stream().filter(r -> r.getDestination() == myRepository).findFirst().get());

        assertEquals(2, myController.getCode().size());
        assertCodeElementInComponent(myController, "com.structurizr.analysis.reflections.supportingTypes.myapp.web.MyController", CodeElementRole.Primary);
        assertCodeElementInComponent(myController, "com.structurizr.analysis.reflections.supportingTypes.myapp.AbstractComponent", CodeElementRole.Supporting);

        assertEquals(5, myRepository.getCode().size());
        assertCodeElementInComponent(myRepository, "com.structurizr.analysis.reflections.supportingTypes.myapp.data.MyRepository", CodeElementRole.Primary);
        assertCodeElementInComponent(myRepository, "com.structurizr.analysis.reflections.supportingTypes.myapp.AbstractComponent", CodeElementRole.Supporting);
        assertCodeElementInComponent(myRepository, "com.structurizr.analysis.reflections.supportingTypes.myapp.data.MyRepositoryImpl", CodeElementRole.Supporting);
        assertCodeElementInComponent(myRepository, "com.structurizr.analysis.reflections.supportingTypes.myapp.data.MyRepositoryRowMapper", CodeElementRole.Supporting);
        assertCodeElementInComponent(myRepository, "com.structurizr.analysis.reflections.supportingTypes.myapp.util.RowMapperHelper", CodeElementRole.Supporting);
    }

    @Test
    public void test_findComponents_CorrectlyFindsSupportingTypes_WhenTheReferencedTypesStrategyIsUsedAndIndirectlyReferencedTypesShouldBeExcluded() throws Exception {
        ComponentFinder componentFinder = new ComponentFinder(
                webApplication,
                "com.structurizr.analysis.reflections.supportingTypes.myapp",
                new StructurizrAnnotationsComponentFinderStrategy(
                        new FirstImplementationOfInterfaceSupportingTypesStrategy(),
                        new ReferencedTypesSupportingTypesStrategy(false)
                )
        );
        componentFinder.findComponents();

        assertEquals(2, webApplication.getComponents().size());
        Component myController = webApplication.getComponentWithName("MyController");
        Component myRepository = webApplication.getComponentWithName("MyRepository");
        assertEquals(1, myController.getRelationships().size());
        assertNotNull(myController.getRelationships().stream().filter(r -> r.getDestination() == myRepository).findFirst().get());

        assertEquals(2, myController.getCode().size());
        assertCodeElementInComponent(myController, "com.structurizr.analysis.reflections.supportingTypes.myapp.web.MyController", CodeElementRole.Primary);
        assertCodeElementInComponent(myController, "com.structurizr.analysis.reflections.supportingTypes.myapp.AbstractComponent", CodeElementRole.Supporting);

        assertEquals(4, myRepository.getCode().size());
        assertCodeElementInComponent(myRepository, "com.structurizr.analysis.reflections.supportingTypes.myapp.data.MyRepository", CodeElementRole.Primary);
        assertCodeElementInComponent(myRepository, "com.structurizr.analysis.reflections.supportingTypes.myapp.AbstractComponent", CodeElementRole.Supporting);
        assertCodeElementInComponent(myRepository, "com.structurizr.analysis.reflections.supportingTypes.myapp.data.MyRepositoryImpl", CodeElementRole.Supporting);
        assertCodeElementInComponent(myRepository, "com.structurizr.analysis.reflections.supportingTypes.myapp.data.MyRepositoryRowMapper", CodeElementRole.Supporting);
    }

    private void assertCodeElementInComponent(Component component, String type, CodeElementRole role) {
        for (CodeElement codeElement : component.getCode()) {
            if (codeElement.getType().equals(type) && codeElement.getRole() == role) {
                return;
            }
        }

        fail("Component " + component.getName() + " does not have a " + role + " code element of type " + type);
    }

}


text:
* * *

title: "Bee: Functions" view: page_curriculum theme: none

* * *

<%= partial('curriculum_header', :unittitle=>'Course 3', :lesson=>6, :title=> 'Bee: Functions', :unplugged=>false, :time=>30) %>

[content]

[together]

## Stundenübersicht

Using the Bee environment, students use and modify functions to help the bee collect nectar and make honey.

[summary]

## Teaching Summary

### **Getting Started**

[Introduction](#GetStarted)

### **Activity: Bee: Functions**

[Bee: Functions](#Activity)

### **Extended Learning**

[Extension Activities](#Extended)

[/summary]

## Lesson Objectives

### Students will:

  * Use a pre-determined functions to complete commonly repeated tasks
  * Modify an existing function to complete a different task
  * Create a function from scratch

[/together]

[together]

## Getting Started

###  Introduction

[/together]

[together]

## Activity

###  [Bee: Functions](http://learn.code.org/s/course3/stage/6/puzzle/1)

[/together]

[together]

## Extended Learning

Use these activities to enhance student learning. They can be used as outside of class activities or other enrichment.

### Functionalize Your Classroom

  * Brainstorm a list of daily classroom activities with students (turning in work, lining up for recess, eating lunch, etc.)
  * Break students into small groups and assign each group an activitiy and a big sheet of paper
  * Each group will write the daily activity as a function and create a poster with that function's "code"
  * As a whole class you can then write a program for a typical day in class, calling each group's function as necessary

[/together]

[standards]

## Connections and Background Information

### PARCC / Smarter Balanced Assessment Skills

  * Click / tap
  * Drag and drop
  * Select and drag / slide
  * Select object
  * Use video player

### ISTE Standards (formerly NETS)

  * 1.a - Apply existing knowledge to generate new ideas, products, or processes.
  * 1.c - Use models and simulation to explore complex systems and issues.
  * 4.b - Plan and manage activities to develop a solution or complete a project.
  * 6.a - Understand and use technology systems.
  * 6.c - Troubleshoot systems and applications.
  * 6.d - Transfer current knowledge to learning of new technologies.

### CSTA K-12 Computer Science Standards

  * CL.L1:3-02. Work cooperatively and collaboratively with peers teachers, and others using technology.
  * CT.L1:3-01. Use technology resources (e.g., puzzles, logical thinking programs) to solve age appropriate problems.
  * CT.L1:6-01. Understand and use the basic steps in algorithmic problem-solving.
  * CPP.L1:6-05. Construct a program as a set of step-by-step instructions to be acted out.
  * CPP.L1:6-06. Implement problem solutions using a block-based visual programming language.
  * CT.L2-01. Use the basic steps in algorithmic problem solving to design solutions.
  * CT.L2-06. Describe and analyze a sequence of instructions being followed.
  * CT.L2-07. Represent data in a variety of ways: text, sounds, pictures, numbers.
  * CT.L2-08. Use visual representations of problem states, structures, and data.
  * CT.L2-12. Use abstraction to decompose a problem into sub problems.
  * CT.L2-14. Examine connections between elements of mathematics and computer science including binary numbers, logic, sets, and functions.
  * CT.L3A-03. Explain how sequence, selection, iteration, and recursion are building blocks of algorithms.

### Next-Gen Science Standards

  * 3-5-ETS1-2. Generate and compare multiple possible solutions to a problem based on how well each is likely to meet the criteria and constraints of the problem. .

### Common Core Mathematical Practices

  *   1. Make sense of problems and persevere in solving them.
  *   1. Reason abstractly and quantitatively.
  *   1. Model with mathematics
  *   1. Use appropriate tools strategically.
  *   1. Attend to precision.
  *   1. Look for and make use of structure.
  *   1. Look for and express regularity in repeated reasoning.

### Common Core Math Standards

  * 3.OA.3 - Use multiplication and division within 100 to solve word problems in situations involving equal groups, arrays, and measurement quantities.
  * 4.NBT.B.4 - Fluently add and subtract multi-digit whole numbers using the standard algorithm.
  * 5.NBT.B.5 - Fluently multiply multi-digit whole numbers using the standard algorithm.

### Common Core Language Arts Standards

  * L.3.6 - Acquire and use accurately grade-appropriate conversational, general academic, and domain-specific words and phrases, including those that signal spatial and temporal relationships.
  * L.4.6 - Acquire and use accurately grade-appropriate general academic and domain-specific words and phrases, including those that signal precise actions, emotions, or states of being and that are basic to a particular topic.
  * L.5.6 - Acquire and use accurately grade-appropriate general academic and domain-specific words and phrases, including those that signal contrast, addition, and other logical relationships

[/standards]

[/content]

<link rel="stylesheet" type="text/css" href="../docs/morestyle.css" />


text:
package org.cubeengine.converter.converter;

import org.cubeengine.converter.ConversionException;
import org.cubeengine.converter.node.ByteNode;
import org.cubeengine.converter.node.Node;

public class ByteConverter extends SimpleConverter<Byte>
{
    @Override
    public Node toNode(Byte object) throws ConversionException
    {
        return new ByteNode(object);
    }

    @Override
    public Byte fromNode(Node node) throws ConversionException
    {
        if (node instanceof ByteNode)
        {
            return ((ByteNode)node).getValue();
        }
        String s = node.asText();
        try
        {
            return Byte.parseByte(s);
        }
        catch (NumberFormatException e)
        {
            throw ConversionException.of(this, node, "Node incompatible with Byte!", e);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <artifactId>parent.twelve.1200</artifactId>
    <groupId>org.jetbrains.idea</groupId>
    <version>12.0.0</version>
    <relativePath>../../../pom.xml</relativePath>
  </parent>
  <groupId>org.jetbrains.idea</groupId>
  <artifactId>maven-server-api</artifactId>

  <name>Maven module for maven-server-api</name>
  <description>Maven integration for module maven-server-api</description>
  <build>
    <sourceDirectory>${idea.home}/plugins/maven/maven-server-api/src</sourceDirectory>
    <resources>
      <resource>
        <directory>${idea.home}/plugins/maven/maven-server-api/src</directory>
        <excludes>
          <exclude>**/*.java</exclude>
          <exclude>**/*.groovy</exclude>
        </excludes>
      </resource>
    </resources>
  </build>
  <dependencies>
    <dependency>
      <groupId>org.jetbrains.idea</groupId>
      <artifactId>util</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.lucene</groupId>
      <artifactId>lucene-core</artifactId>
    </dependency>
  </dependencies>
</project>


text:
(function (exports) {
    'use strict';

    var doc = document;
    exports.helper = {
        isNumeric: function (n) {
            return !isNaN(parseFloat(n)) && isFinite(n);
        },
        extend: function (target, source) {
            for (var name in source) {
                if (source.hasOwnProperty(name)) {
                    target[name] = source[name];
                }
            }
        },
        getPrefix: function (el, exp) {
            var _prefix = ['', '-ms-', '-o-','-moz-','-webkit-'];
            var _style = el.style;

            for(var i=0, len=_prefix.length; i<len; i+=1) {
                var result = _prefix[i] + exp;
                if( result in _style) {
                    return result;
                }
            }
            return '';
        },
        num2rate: function (num, size) {
            return num * (100 / size);
        },
        rate2num: function (rate, size) {
            return rate * (size / 100);
        },
        getPropsName: function (orientation) {
            if (orientation === 'vertical') {
                return { 'POSITION': 'top',    'SIZE': 'height',  'DX': 'dy'};
            } else {
                return { 'POSITION': 'left',   'SIZE': 'width',   'DX': 'dx' };
            }
        },
        createEl: function (tagName, className) {
            var el = doc.createElement(tagName);
            if (className) {
                el.className = className;
            }
            return el;
        }
    };

})(window.SliderBar = (typeof window.SliderBar === 'undefined') ? {} : window.SliderBar);


text:
<?php

namespace Application\Controller;

use Zend\View\Model\ViewModel;

class IndexController extends AbstractController
{
    use \Application\Log\LoggerTrait;

    public function indexAction()
    {
        $client = $this->getServiceLocator()->get('GoogleGlass\Service\GlassService');

        $timelineItems = $client->execute('timeline::list');

        return new ViewModel(compact('timelineItems'));
    }
}


text:
$scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
$config = (Get-Content (Join-Path $scriptPath "config.json") | Out-String | ConvertFrom-Json)
foreach($var in $config.variables) {
    iex "`$$($var.name) = '$($ExecutionContext.InvokeCommand.ExpandString($var.value))'"
}

# Load Scripts
ls $scriptPath -Recurse -Filter "Import*.ps1" | % { . $_.FullName }

# Install Chocolatey
Install-Chocolatey -ProgressBegin 0 -ProgressEnd 20
Install-ChocolateyPackages -ProgressBegin 20 -ProgressEnd 50

# Install hard links
Install-Links -ProgressBegin 50 -ProgressEnd 100


text:
/**
 * The checkReleaseArtifacts.scala script checks whether every artifact (.jar or .war file) has
 * attached -javadoc.jar and -sources.jar files.
 *
 * To run it, type e.g.:
 *
 *   scala checkReleaseArtifacts.scala ~/.m2/repository/org/ow2/xlcloud
 */

import java.io.File

def fileNames(dir: File): Array[String] = if (dir.isDirectory) dir.listFiles.map(_.getName) else Array.empty

def validateContains(dir: File, filename: String) {
  if (!fileNames(dir).exists(_ == filename)) {
    println(dir.getAbsolutePath + ": does not contain " + filename)
  }
}

def checkDir(dir: File) {
  if (dir.isDirectory) {
    val hasJars = fileNames(dir).exists(_ endsWith ".jar")
    val hasWars = fileNames(dir).exists(_ endsWith ".war")
    if (hasJars || hasWars) {
      val moduleName = dir.getParentFile.getName
      val version = dir.getName
      validateContains(dir, moduleName + "-" + version + "-sources.jar")
      validateContains(dir, moduleName + "-" + version + "-javadoc.jar")
    }
    dir.listFiles.foreach(checkDir)
  }
}

checkDir(new File(args(0)))


text:
/**
 * @file oval_parser.c
 * \brief Open Vulnerability and Assessment Language
 *
 * See more details at http://oval.mitre.org/
 */

/*
 * Copyright 2011 Red Hat Inc., Durham, North Carolina.
 * All Rights Reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Authors:
 *      "Peter Vrabec" <pvrabec@redhat.com
 *      "David Niemoller" <David.Niemoller@g2-inc.com>
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <string.h>
#include <libxml/xmlreader.h>
#include <stddef.h>

#include "public/oval_agent_api.h"
#include "oval_agent_api_impl.h"
#include "oval_parser_impl.h"
#include "oval_definitions_impl.h"
#include "oval_system_characteristics_impl.h"
#include "common/util.h"
#include "common/elements.h"
#include "common/debug_priv.h"
#include "common/_error.h"

int oval_syschar_model_parse(xmlTextReaderPtr reader, struct oval_parser_context *context)
{
	int depth = xmlTextReaderDepth(reader);
	int ret = 0;

	xmlTextReaderRead(reader);
	while ((xmlTextReaderDepth(reader) > depth) && (ret != -1 )) {
		if (xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
			char *tagname = (char *)xmlTextReaderLocalName(reader);
			char *namespace = (char *)xmlTextReaderNamespaceUri(reader);

			int is_ovalsys = strcmp((const char*)OVAL_SYSCHAR_NAMESPACE, namespace) == 0;
			if (is_ovalsys && (strcmp(tagname, "generator") == 0)) {
				struct oval_generator *gen;
				gen = oval_syschar_model_get_generator(context->syschar_model);
				ret = oval_parser_parse_tag(reader, context, &oval_generator_parse_tag, gen);
			} else if (is_ovalsys && (strcmp(tagname, "system_info") == 0)) {
				ret = oval_sysinfo_parse_tag(reader, context);
			} else if (is_ovalsys && (strcmp(tagname, "collected_objects") == 0)) {
				ret = oval_parser_parse_tag(reader, context, &oval_syschar_parse_tag, NULL);
			} else if (is_ovalsys && (strcmp(tagname, "system_data") == 0)) {
				ret = oval_parser_parse_tag(reader, context, &oval_sysitem_parse_tag, NULL);
			} else {
				dW("Unprocessed tag: <%s:%s>.\n", namespace, tagname);
				oval_parser_skip_tag(reader, context);
			}

			oscap_free(tagname);
			oscap_free(namespace);
		} else {
			if (xmlTextReaderRead(reader) != 1) {
				ret = -1;
				break;
			}
		}
	}

	return ret;
}


text:
function varargout = process_apply_spfilter2( varargin )
% PROCESS_SPATIAL_FILTER2: Apply one or several spatial filters to a sensor
% data file. File A contains filters, File B the data.
%
% USAGE:  OutputFiles = process_compare2('Run', sProcess, sInputsA, sInputsB)

% @=============================================================================
% This software is part of the Brainstorm software:
% http://neuroimage.usc.edu/brainstorm
%
% Copyright (c)2000-2014 University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPL
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Peter Donhauser, 2015

eval(macro_method);
end

%% ===== GET DESCRIPTION =====
function sProcess = GetDescription()
    % Description the process
    sProcess.Comment     = 'Apply spatial filter';
    sProcess.FileTag     = '';
    sProcess.Category    = 'Custom';
    sProcess.SubGroup    = 'iES plugin';
    sProcess.Index       = 302;
    % Definition of the input accepted by this process
    sProcess.InputTypes  = {'data'};
    sProcess.OutputTypes = {'matrix'};
    sProcess.nInputs     = 2;
    sProcess.nMinFiles   = 1;
    sProcess.isSeparator = 0;

    % === Number of components
    sProcess.options.ncomp.Comment = 'Number of components:  ';
    sProcess.options.ncomp.Type    = 'value';
    sProcess.options.ncomp.Value   = {1, '', 0};
    % === Order of components
    sProcess.options.label4.Type    = 'label';
    sProcess.options.label4.Comment = '
Order :';
    sProcess.options.order.Comment = {'first', 'last'};
    sProcess.options.order.Type    = 'radio';
    sProcess.options.order.Value   = 0;
    % === Matrix ordering
    sProcess.options.matrix.Type    = 'label';
    sProcess.options.matrix.Comment = '
Rows in output represent :';
    sProcess.options.matrix.Comment = {'Epochs (one matrix per component)', ...
                                        'Components (one matrix per epoch)'};
    sProcess.options.matrix.Type    = 'radio';
    sProcess.options.matrix.Value   = 0;
    % === Comment
    sProcess.options.comment.Comment = 'Comment:';
    sProcess.options.comment.Type    = 'text';
    sProcess.options.comment.Value   = '';
    % Normalize
    sProcess.options.isnoisenorm.Comment = 'Normalize values using noise statistics';
    sProcess.options.isnoisenorm.Type    = 'checkbox';
    sProcess.options.isnoisenorm.Value   = 0;
end

%% ===== FORMAT COMMENT =====
function Comment = FormatComment(sProcess)
    Comment = sProcess.Comment;
end

%% ===== RUN =====
function OutputFiles = Run(sProcess, sInputsA, sInputsB)

Options.nComp = sProcess.options.ncomp.Value{1};
Options.Comment = sProcess.options.comment.Value;
Options.order = sProcess.options.order.Value;
Options.matrix = sProcess.options.matrix.Value;
isNoiseNorm = sProcess.options.isnoisenorm.Value;

if isempty(Options.Comment)
    Options.Comment = 'Spatial filter';
end

if isNoiseNorm
    % The noise covariance matrix is used to normalize the signal power
    sStudy = bst_get('Study', sInputsA.iStudy);
    NoiseFile = sStudy.NoiseCov.FileName;
else
    NoiseFile = [];
end

OutputFiles = apply_spatial_filter(sInputsA.FileName, ...
    {sInputsB.FileName}, NoiseFile, Options);
% I need to output this, to avoid error in bst_process()
% OutputFiles = {sInputsB.FileName};
% db_reload_conditions(sInputsB(1).iStudy);

end

function MatrixFiles = apply_spatial_filter(FilterFile, DataFiles, NoiseFile, Options)

sInput = bst_process('GetInputStruct',DataFiles{1});
sInputA = bst_process('GetInputStruct',FilterFile);
% Load filter file
sMat = in_bst_data(FilterFile);
% Check that it's an appropriate file
if ~isfield(sMat, 'C1')||~isfield(sMat, 'GoodChannel')
    bst_error('Not an appropriate subspace or dipole file');
end
if sInputA.iStudy~=sInput(1).iStudy
    ChannelMatFilt = in_bst_channel(sInputA.ChannelFile);
    ChannelMatData = in_bst_channel(sInput(1).ChannelFile);
    ChannelNames = {ChannelMatFilt.Channel(sMat.GoodChannel).Name};
    iChanDat = channel_find(ChannelMatData.Channel, ChannelNames);
    if length(sMat.GoodChannel)~=length(iChanDat)
        ChannelNames = {ChannelMatData.Channel(iChanDat).Name};
        iChanFilt = channel_find(ChannelMatFilt.Channel, ChannelNames);
        [~,~,iChanChan]=intersect(iChanFilt,sMat.GoodChannel);
    else
        iChanFilt = sMat.GoodChannel;
        iChanChan = 1:length(iChanFilt);
    end
else
    iChanDat = sMat.GoodChannel;
    iChanFilt = sMat.GoodChannel;
    iChanChan = 1:length(iChanFilt);
end

%% Compute filter kernel

% Get relevant topographies and noise covariance
if Options.order==1
    P = sMat.F(iChanFilt, 1:Options.nComp);
    Cn = sMat.C2(iChanChan,iChanChan);
elseif Options.order==2
    P = sMat.F(iChanFilt, end-Options.nComp+1:end);
    Cn = sMat.C1(iChanChan,iChanChan);
end
% Compute whitener
[U, S] = svd(Cn,'econ');
% regularize
if isfield(sMat.Options, 'epsilon')
    epsilon = sMat.Options.epsilon;
else
    epsilon = .05;
end
s = diag(S);
ss = sum(s);
sss = 1 - (cumsum(s)./ss);
i = find(sss<epsilon);
if isempty(i)
    i = length(sss);
else
    i = i(1);
end
Proj = sqrt(inv(S(1:i,1:i)))*U(:,1:i)';
% Compute filter
W = (Proj'*pinv(Proj*P)')';

%% Load noise covariance

if ~isempty(NoiseFile)
    NoiseMat = load(file_fullpath(NoiseFile));
    Nm = NoiseMat.NoiseCov(iChanFilt,iChanFilt);
    noisenorm = sqrt(diag(W*Nm*W'));
end

%% Apply to data files

for iFile = 1:numel(DataFiles)
    DataMat = in_bst_data(DataFiles{iFile});
    Events{iFile} = DataMat.Events;
    X = DataMat.F(iChanDat,:);
    if ~isempty(NoiseFile)
        if Options.matrix==1
            Y(:,:,iFile) = bsxfun(@rdivide, W * X, noisenorm);
        else
            Y{iFile} = bsxfun(@rdivide, W * X, noisenorm);
            t{iFile} = DataMat.Time;
        end
    else
        Y{iFile} = W * X;
        if Options.matrix==1
            Y(:,:,iFile) = W * X;
        else
            Y{iFile} = W * X;
            t{iFile} = DataMat.Time;
        end
    end
end

%% Save resulting matrix files

if Options.matrix==1
    for iComp = 1:Options.nComp
        MatrixMat = db_template('matrixmat');
        MatrixMat.Value = squeeze(Y(iComp,:,:))';
        MatrixMat.Description = {};
        %     MatrixMat.Events = Events;
        for iFile = 1:numel(DataFiles)
            MatrixMat.Description{iFile,1} = ['Epoch ' num2str(iFile)];
        end
        MatrixMat.Time = DataMat.Time;
        MatrixMat.Comment = [Options.Comment ' component #' num2str(iComp)];
        % Get filename
        MatrixFiles{iComp} = bst_process('GetNewFilename', bst_fileparts(DataFiles{1}), 'matrix');
        % Output filename: add file tag
        MatrixFiles{iComp} = file_unique(MatrixFiles{iComp});
        % Save file
        bst_save(MatrixFiles{iComp}, MatrixMat, 'v6');
        db_add_data(sInput.iStudy, MatrixFiles{iComp}, MatrixMat);
    end
elseif Options.matrix==2
    MatrixMat = db_template('matrixmat');
    MatrixMat.Description = {};
    for iComp = 1:Options.nComp
        MatrixMat.Description{iComp,1} = ['Component ' num2str(iComp)];
    end
    for iFile = 1:numel(DataFiles)
        MatrixMat.Value = Y{iFile};
        MatrixMat.Time = t{iFile};
        MatrixMat.Comment = [Options.Comment ' epoch (#' num2str(iFile) ')'];
        MatrixMat.Events = Events{iFile};
        % Get filename
        MatrixFiles{iFile} = bst_process('GetNewFilename', bst_fileparts(DataFiles{1}), 'matrix');
        % Output filename: add file tag
        MatrixFiles{iFile} = file_unique(MatrixFiles{iFile});
        % Save file
        bst_save(MatrixFiles{iFile}, MatrixMat, 'v6');
        db_add_data(sInput.iStudy, MatrixFiles{iFile}, MatrixMat);
    end
end

end


text:
class CreateCells < ActiveRecord::Migration
  def self.up
    create_table :cells do |t|
      t.integer :page_id
      t.string :name

      t.timestamps
    end
  end

  def self.down
    drop_table :cells
  end
end


text:
/* This file is the lexical analyzer for GNU C++.  */

#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "tm.h"
#include "input.h"
#include "tree.h"
#include "cp-tree.h"
#include "cpplib.h"
#include "flags.h"
#include "c-family/c-pragma.h"
#include "c-family/c-objc.h"
#include "output.h"
#include "tm_p.h"
#include "timevar.h"

static int interface_strcmp (const char *);
static void init_cp_pragma (void);

static tree parse_strconst_pragma (const char *, int);
static void handle_pragma_vtable (cpp_reader *);
static void handle_pragma_unit (cpp_reader *);
static void handle_pragma_interface (cpp_reader *);
static void handle_pragma_implementation (cpp_reader *);
static void handle_pragma_java_exceptions (cpp_reader *);

static void init_operators (void);
static void copy_lang_type (tree);

/* A constraint that can be tested at compile time.  */
#define CONSTRAINT(name, expr) extern int constraint_##name [(expr) ? 1 : -1]

/* Functions and data structures for #pragma interface.

   `#pragma implementation' means that the main file being compiled
   is considered to implement (provide) the classes that appear in
   its main body.  I.e., if this is file "foo.cc", and class `bar'
   is defined in "foo.cc", then we say that "foo.cc implements bar".

   All main input files "implement" themselves automagically.

   `#pragma interface' means that unless this file (of the form "foo.h"
   is not presently being included by file "foo.cc", the
   CLASSTYPE_INTERFACE_ONLY bit gets set.  The effect is that none
   of the vtables nor any of the inline functions defined in foo.h
   will ever be output.

   There are cases when we want to link files such as "defs.h" and
   "main.cc".  In this case, we give "defs.h" a `#pragma interface',
   and "main.cc" has `#pragma implementation "defs.h"'.  */

struct impl_files
{
  const char *filename;
  struct impl_files *next;
};

static struct impl_files *impl_file_chain;

/* True if we saw "#pragma GCC java_exceptions".  */
bool pragma_java_exceptions;

void
cxx_finish (void)
{
  c_common_finish ();
}

/* A mapping from tree codes to operator name information.  */
operator_name_info_t operator_name_info[(int) MAX_TREE_CODES];
/* Similar, but for assignment operators.  */
operator_name_info_t assignment_operator_name_info[(int) MAX_TREE_CODES];

/* Initialize data structures that keep track of operator names.  */

#define DEF_OPERATOR(NAME, C, M, AR, AP) \
 CONSTRAINT (C, sizeof "operator " + sizeof NAME <= 256);
#include "operators.def"
#undef DEF_OPERATOR

static void
init_operators (void)
{
  tree identifier;
  char buffer[256];
  struct operator_name_info_t *oni;

#define DEF_OPERATOR(NAME, CODE, MANGLING, ARITY, ASSN_P)		    \
  sprintf (buffer, ISALPHA (NAME[0]) ? "operator %s" : "operator%s", NAME); \
  identifier = get_identifier (buffer);					    \
  IDENTIFIER_OPNAME_P (identifier) = 1;					    \
									    \
  oni = (ASSN_P								    \
	 ? &assignment_operator_name_info[(int) CODE]			    \
	 : &operator_name_info[(int) CODE]);				    \
  oni->identifier = identifier;						    \
  oni->name = NAME;							    \
  oni->mangled_name = MANGLING;						    \
  oni->arity = ARITY;

#include "operators.def"
#undef DEF_OPERATOR

  operator_name_info[(int) ERROR_MARK].identifier
    = get_identifier ("<invalid operator>");

  /* Handle some special cases.  These operators are not defined in
     the language, but can be produced internally.  We may need them
     for error-reporting.  (Eventually, we should ensure that this
     does not happen.  Error messages involving these operators will
     be confusing to users.)  */

  operator_name_info [(int) INIT_EXPR].name
    = operator_name_info [(int) MODIFY_EXPR].name;
  operator_name_info [(int) EXACT_DIV_EXPR].name = "(ceiling /)";
  operator_name_info [(int) CEIL_DIV_EXPR].name = "(ceiling /)";
  operator_name_info [(int) FLOOR_DIV_EXPR].name = "(floor /)";
  operator_name_info [(int) ROUND_DIV_EXPR].name = "(round /)";
  operator_name_info [(int) CEIL_MOD_EXPR].name = "(ceiling %)";
  operator_name_info [(int) FLOOR_MOD_EXPR].name = "(floor %)";
  operator_name_info [(int) ROUND_MOD_EXPR].name = "(round %)";
  operator_name_info [(int) ABS_EXPR].name = "abs";
  operator_name_info [(int) TRUTH_AND_EXPR].name = "strict &&";
  operator_name_info [(int) TRUTH_OR_EXPR].name = "strict ||";
  operator_name_info [(int) RANGE_EXPR].name = "...";
  operator_name_info [(int) UNARY_PLUS_EXPR].name = "+";

  assignment_operator_name_info [(int) EXACT_DIV_EXPR].name
    = "(exact /=)";
  assignment_operator_name_info [(int) CEIL_DIV_EXPR].name
    = "(ceiling /=)";
  assignment_operator_name_info [(int) FLOOR_DIV_EXPR].name
    = "(floor /=)";
  assignment_operator_name_info [(int) ROUND_DIV_EXPR].name
    = "(round /=)";
  assignment_operator_name_info [(int) CEIL_MOD_EXPR].name
    = "(ceiling %=)";
  assignment_operator_name_info [(int) FLOOR_MOD_EXPR].name
    = "(floor %=)";
  assignment_operator_name_info [(int) ROUND_MOD_EXPR].name
    = "(round %=)";
}

/* Initialize the reserved words.  */

void
init_reswords (void)
{
  unsigned int i;
  tree id;
  int mask = 0;

  if (cxx_dialect != cxx0x)
    mask |= D_CXX0X;
  if (flag_no_asm)
    mask |= D_ASM | D_EXT;
  if (flag_no_gnu_keywords)
    mask |= D_EXT;

  /* The Objective-C keywords are all context-dependent.  */
  mask |= D_OBJC;

  ridpointers = ggc_alloc_cleared_vec_tree ((int) RID_MAX);
  for (i = 0; i < num_c_common_reswords; i++)
    {
      if (c_common_reswords[i].disable & D_CONLY)
	continue;
      id = get_identifier (c_common_reswords[i].word);
      C_SET_RID_CODE (id, c_common_reswords[i].rid);
      ridpointers [(int) c_common_reswords[i].rid] = id;
      if (! (c_common_reswords[i].disable & mask))
	C_IS_RESERVED_WORD (id) = 1;
    }
}

static void
init_cp_pragma (void)
{
  c_register_pragma (0, "vtable", handle_pragma_vtable);
  c_register_pragma (0, "unit", handle_pragma_unit);
  c_register_pragma (0, "interface", handle_pragma_interface);
  c_register_pragma (0, "implementation", handle_pragma_implementation);
  c_register_pragma ("GCC", "interface", handle_pragma_interface);
  c_register_pragma ("GCC", "implementation", handle_pragma_implementation);
  c_register_pragma ("GCC", "java_exceptions", handle_pragma_java_exceptions);
}

/* TRUE if a code represents a statement.  */

bool statement_code_p[MAX_TREE_CODES];

/* Initialize the C++ front end.  This function is very sensitive to
   the exact order that things are done here.  It would be nice if the
   initialization done by this routine were moved to its subroutines,
   and the ordering dependencies clarified and reduced.  */
bool
cxx_init (void)
{
  location_t saved_loc;
  unsigned int i;
  static const enum tree_code stmt_codes[] = {
   CTOR_INITIALIZER,	TRY_BLOCK,	HANDLER,
   EH_SPEC_BLOCK,	USING_STMT,	TAG_DEFN,
   IF_STMT,		CLEANUP_STMT,	FOR_STMT,
   RANGE_FOR_STMT,	WHILE_STMT,	DO_STMT,
   BREAK_STMT,		CONTINUE_STMT,	SWITCH_STMT,
   EXPR_STMT
  };

  memset (&statement_code_p, 0, sizeof (statement_code_p));
  for (i = 0; i < ARRAY_SIZE (stmt_codes); i++)
    statement_code_p[stmt_codes[i]] = true;

  saved_loc = input_location;
  input_location = BUILTINS_LOCATION;

  init_reswords ();
  init_tree ();
  init_cp_semantics ();
  init_operators ();
  init_method ();
  init_error ();

  current_function_decl = NULL;

  class_type_node = ridpointers[(int) RID_CLASS];

  cxx_init_decl_processing ();

  if (c_common_init () == false)
    {
      input_location = saved_loc;
      return false;
    }

  init_cp_pragma ();

  init_repo ();

  input_location = saved_loc;
  return true;
}

/* Return nonzero if S is not considered part of an
   INTERFACE/IMPLEMENTATION pair.  Otherwise, return 0.  */

static int
interface_strcmp (const char* s)
{
  /* Set the interface/implementation bits for this scope.  */
  struct impl_files *ifiles;
  const char *s1;

  for (ifiles = impl_file_chain; ifiles; ifiles = ifiles->next)
    {
      const char *t1 = ifiles->filename;
      s1 = s;

      if (*s1 == 0 || filename_ncmp (s1, t1, 1) != 0)
	continue;

      while (*s1 != 0 && filename_ncmp (s1, t1, 1) == 0)
	s1++, t1++;

      /* A match.  */
      if (*s1 == *t1)
	return 0;

      /* Don't get faked out by xxx.yyy.cc vs xxx.zzz.cc.  */
      if (strchr (s1, '.') || strchr (t1, '.'))
	continue;

      if (*s1 == '\0' || s1[-1] != '.' || t1[-1] != '.')
	continue;

      /* A match.  */
      return 0;
    }

  /* No matches.  */
  return 1;
}

/* Parse a #pragma whose sole argument is a string constant.
   If OPT is true, the argument is optional.  */
static tree
parse_strconst_pragma (const char* name, int opt)
{
  tree result, x;
  enum cpp_ttype t;

  t = pragma_lex (&result);
  if (t == CPP_STRING)
    {
      if (pragma_lex (&x) != CPP_EOF)
	warning (0, "junk at end of #pragma %s", name);
      return result;
    }

  if (t == CPP_EOF && opt)
    return NULL_TREE;

  error ("invalid #pragma %s", name);
  return error_mark_node;
}

static void
handle_pragma_vtable (cpp_reader* dfile ATTRIBUTE_UNUSED )
{
  parse_strconst_pragma ("vtable", 0);
  sorry ("#pragma vtable no longer supported");
}

static void
handle_pragma_unit (cpp_reader* dfile ATTRIBUTE_UNUSED )
{
  /* Validate syntax, but don't do anything.  */
  parse_strconst_pragma ("unit", 0);
}

static void
handle_pragma_interface (cpp_reader* dfile ATTRIBUTE_UNUSED )
{
  tree fname = parse_strconst_pragma ("interface", 1);
  struct c_fileinfo *finfo;
  const char *filename;

  if (fname == error_mark_node)
    return;
  else if (fname == 0)
    filename = lbasename (input_filename);
  else
    filename = TREE_STRING_POINTER (fname);

  finfo = get_fileinfo (input_filename);

  if (impl_file_chain == 0)
    {
      /* If this is zero at this point, then we are
	 auto-implementing.  */
      if (main_input_filename == 0)
	main_input_filename = input_filename;
    }

  finfo->interface_only = interface_strcmp (filename);
  /* If MULTIPLE_SYMBOL_SPACES is set, we cannot assume that we can see
     a definition in another file.  */
  if (!MULTIPLE_SYMBOL_SPACES || !finfo->interface_only)
    finfo->interface_unknown = 0;
}

/* Note that we have seen a #pragma implementation for the key MAIN_FILENAME.
   We used to only allow this at toplevel, but that restriction was buggy
   in older compilers and it seems reasonable to allow it in the headers
   themselves, too.  It only needs to precede the matching #p interface.

   We don't touch finfo->interface_only or finfo->interface_unknown;
   the user must specify a matching #p interface for this to have
   any effect.  */

static void
handle_pragma_implementation (cpp_reader* dfile ATTRIBUTE_UNUSED )
{
  tree fname = parse_strconst_pragma ("implementation", 1);
  const char *filename;
  struct impl_files *ifiles = impl_file_chain;

  if (fname == error_mark_node)
    return;

  if (fname == 0)
    {
      if (main_input_filename)
	filename = main_input_filename;
      else
	filename = input_filename;
      filename = lbasename (filename);
    }
  else
    {
      filename = TREE_STRING_POINTER (fname);
      if (cpp_included_before (parse_in, filename, input_location))
	warning (0, "#pragma implementation for %qs appears after "
		 "file is included", filename);
    }

  for (; ifiles; ifiles = ifiles->next)
    {
      if (! filename_cmp (ifiles->filename, filename))
	break;
    }
  if (ifiles == 0)
    {
      ifiles = XNEW (struct impl_files);
      ifiles->filename = xstrdup (filename);
      ifiles->next = impl_file_chain;
      impl_file_chain = ifiles;
    }
}

/* Indicate that this file uses Java-personality exception handling.  */
static void
handle_pragma_java_exceptions (cpp_reader* dfile ATTRIBUTE_UNUSED)
{
  tree x;
  if (pragma_lex (&x) != CPP_EOF)
    warning (0, "junk at end of #pragma GCC java_exceptions");

  choose_personality_routine (lang_java);
  pragma_java_exceptions = true;
}

/* Issue an error message indicating that the lookup of NAME (an
   IDENTIFIER_NODE) failed.  Returns the ERROR_MARK_NODE.  */

tree
unqualified_name_lookup_error (tree name)
{
  if (IDENTIFIER_OPNAME_P (name))
    {
      if (name != ansi_opname (ERROR_MARK))
	error ("%qD not defined", name);
    }
  else
    {
      if (!objc_diagnose_private_ivar (name))
	{
	  error ("%qD was not declared in this scope", name);
	  suggest_alternatives_for (location_of (name), name);
	}
      /* Prevent repeated error messages by creating a VAR_DECL with
	 this NAME in the innermost block scope.  */
      if (local_bindings_p ())
	{
	  tree decl;
	  decl = build_decl (input_location,
			     VAR_DECL, name, error_mark_node);
	  DECL_CONTEXT (decl) = current_function_decl;
	  push_local_binding (name, decl, 0);
	  /* Mark the variable as used so that we do not get warnings
	     about it being unused later.  */
	  TREE_USED (decl) = 1;
	}
    }

  return error_mark_node;
}

/* Like unqualified_name_lookup_error, but NAME is an unqualified-id
   used as a function.  Returns an appropriate expression for
   NAME.  */

tree
unqualified_fn_lookup_error (tree name)
{
  if (processing_template_decl)
    {
      /* In a template, it is invalid to write "f()" or "f(3)" if no
	 declaration of "f" is available.  Historically, G++ and most
	 other compilers accepted that usage since they deferred all name
	 lookup until instantiation time rather than doing unqualified
	 name lookup at template definition time; explain to the user what
	 is going wrong.

	 Note that we have the exact wording of the following message in
	 the manual (trouble.texi, node "Name lookup"), so they need to
	 be kept in synch.  */
      permerror (input_location, "there are no arguments to %qD that depend on a template "
		 "parameter, so a declaration of %qD must be available",
		 name, name);

      if (!flag_permissive)
	{
	  static bool hint;
	  if (!hint)
	    {
	      inform (input_location, "(if you use %<-fpermissive%>, G++ will accept your "
		     "code, but allowing the use of an undeclared name is "
		     "deprecated)");
	      hint = true;
	    }
	}
      return name;
    }

  return unqualified_name_lookup_error (name);
}

/* Wrapper around build_lang_decl_loc(). Should gradually move to
   build_lang_decl_loc() and then rename build_lang_decl_loc() back to
   build_lang_decl().  */

tree
build_lang_decl (enum tree_code code, tree name, tree type)
{
  return build_lang_decl_loc (input_location, code, name, type);
}

/* Build a decl from CODE, NAME, TYPE declared at LOC, and then add
   DECL_LANG_SPECIFIC info to the result.  */

tree
build_lang_decl_loc (location_t loc, enum tree_code code, tree name, tree type)
{
  tree t;

  t = build_decl (loc, code, name, type);
  retrofit_lang_decl (t);

  return t;
}

/* Add DECL_LANG_SPECIFIC info to T.  Called from build_lang_decl
   and pushdecl (for functions generated by the back end).  */

void
retrofit_lang_decl (tree t)
{
  struct lang_decl *ld;
  size_t size;
  int sel;

  if (TREE_CODE (t) == FUNCTION_DECL)
    sel = 1, size = sizeof (struct lang_decl_fn);
  else if (TREE_CODE (t) == NAMESPACE_DECL)
    sel = 2, size = sizeof (struct lang_decl_ns);
  else if (TREE_CODE (t) == PARM_DECL)
    sel = 3, size = sizeof (struct lang_decl_parm);
  else if (LANG_DECL_HAS_MIN (t))
    sel = 0, size = sizeof (struct lang_decl_min);
  else
    gcc_unreachable ();

  ld = ggc_alloc_cleared_lang_decl (size);

  ld->u.base.selector = sel;

  DECL_LANG_SPECIFIC (t) = ld;
  if (current_lang_name == lang_name_cplusplus
      || decl_linkage (t) == lk_none)
    SET_DECL_LANGUAGE (t, lang_cplusplus);
  else if (current_lang_name == lang_name_c)
    SET_DECL_LANGUAGE (t, lang_c);
  else if (current_lang_name == lang_name_java)
    SET_DECL_LANGUAGE (t, lang_java);
  else
    gcc_unreachable ();

#ifdef GATHER_STATISTICS
  tree_node_counts[(int)lang_decl] += 1;
  tree_node_sizes[(int)lang_decl] += size;
#endif
}

void
cxx_dup_lang_specific_decl (tree node)
{
  int size;
  struct lang_decl *ld;

  if (! DECL_LANG_SPECIFIC (node))
    return;

  if (TREE_CODE (node) == FUNCTION_DECL)
    size = sizeof (struct lang_decl_fn);
  else if (TREE_CODE (node) == NAMESPACE_DECL)
    size = sizeof (struct lang_decl_ns);
  else if (TREE_CODE (node) == PARM_DECL)
    size = sizeof (struct lang_decl_parm);
  else if (LANG_DECL_HAS_MIN (node))
    size = sizeof (struct lang_decl_min);
  else
    gcc_unreachable ();

  ld = ggc_alloc_lang_decl (size);
  memcpy (ld, DECL_LANG_SPECIFIC (node), size);
  DECL_LANG_SPECIFIC (node) = ld;

#ifdef GATHER_STATISTICS
  tree_node_counts[(int)lang_decl] += 1;
  tree_node_sizes[(int)lang_decl] += size;
#endif
}

/* Copy DECL, including any language-specific parts.  */

tree
copy_decl (tree decl)
{
  tree copy;

  copy = copy_node (decl);
  cxx_dup_lang_specific_decl (copy);
  return copy;
}

/* Replace the shared language-specific parts of NODE with a new copy.  */

static void
copy_lang_type (tree node)
{
  int size;
  struct lang_type *lt;

  if (! TYPE_LANG_SPECIFIC (node))
    return;

  if (TYPE_LANG_SPECIFIC (node)->u.h.is_lang_type_class)
    size = sizeof (struct lang_type);
  else
    size = sizeof (struct lang_type_ptrmem);
  lt = ggc_alloc_lang_type (size);
  memcpy (lt, TYPE_LANG_SPECIFIC (node), size);
  TYPE_LANG_SPECIFIC (node) = lt;

#ifdef GATHER_STATISTICS
  tree_node_counts[(int)lang_type] += 1;
  tree_node_sizes[(int)lang_type] += size;
#endif
}

/* Copy TYPE, including any language-specific parts.  */

tree
copy_type (tree type)
{
  tree copy;

  copy = copy_node (type);
  copy_lang_type (copy);
  return copy;
}

tree
cxx_make_type (enum tree_code code)
{
  tree t = make_node (code);

  /* Create lang_type structure.  */
  if (RECORD_OR_UNION_CODE_P (code)
      || code == BOUND_TEMPLATE_TEMPLATE_PARM)
    {
      struct lang_type *pi
          = ggc_alloc_cleared_lang_type (sizeof (struct lang_type));

      TYPE_LANG_SPECIFIC (t) = pi;
      pi->u.c.h.is_lang_type_class = 1;

#ifdef GATHER_STATISTICS
      tree_node_counts[(int)lang_type] += 1;
      tree_node_sizes[(int)lang_type] += sizeof (struct lang_type);
#endif
    }

  /* Set up some flags that give proper default behavior.  */
  if (RECORD_OR_UNION_CODE_P (code))
    {
      struct c_fileinfo *finfo = get_fileinfo (input_filename);
      SET_CLASSTYPE_INTERFACE_UNKNOWN_X (t, finfo->interface_unknown);
      CLASSTYPE_INTERFACE_ONLY (t) = finfo->interface_only;
    }

  return t;
}

tree
make_class_type (enum tree_code code)
{
  tree t = cxx_make_type (code);
  SET_CLASS_TYPE_P (t, 1);
  return t;
}

/* Returns true if we are currently in the main source file, or in a
   template instantiation started from the main source file.  */

bool
in_main_input_context (void)
{
  struct tinst_level *tl = outermost_tinst_level();

  if (tl)
    return filename_cmp (main_input_filename,
			 LOCATION_FILE (tl->locus)) == 0;
  else
    return filename_cmp (main_input_filename, input_filename) == 0;
}


text:
`heroku notifications`
======================

display notifications

* [`heroku notifications`](#heroku-notifications)

## `heroku notifications`

display notifications

```
display notifications

USAGE
  $ heroku notifications

OPTIONS
  -a, --app=app        app to run command against
  -r, --remote=remote  git remote of app to use
  --all                view all notifications (not just the ones for the current app)
  --json               output in json format
  --read               show notifications already read
```


text:
<configuration >

<!--
  <timestamp key="bySecond" datePattern="yyyyMMdd'T'HHmmss"/>

<appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>log-${bySecond}.txt</file>
    <encoder>
      <pattern>%d %-5level [%thread] %logger{0}: %msg%n</pattern>
       <immediateFlush>false</immediateFlush>
    </encoder>
  </appender> -->

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <!-- encoders are assigned the type
         ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
    <encoder>
      <pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern>
    </encoder>
  </appender>

  <root level="ERROR">
    <appender-ref ref="STDOUT" />
    <!-- <appender-ref ref="FILE" /> -->
  </root>
</configuration>


text:
package org.apache.hadoop.hive.serde2.avro;

import java.util.ArrayList;
import java.util.List;

import org.apache.avro.Schema;
import org.apache.hadoop.hive.serde2.SerDeException;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.typeinfo.ListTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.MapTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.StructTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.UnionTypeInfo;

/**
 * An AvroObjectInspectorGenerator takes an Avro schema and creates the three
 * data structures Hive needs to work with Avro-encoded data:
 *   * A list of the schema field names
 *   * A list of those fields equivalent types in Hive
 *   * An ObjectInspector capable of working with an instance of that datum.
 */
public class AvroObjectInspectorGenerator {
  final private List<String> columnNames;
  final private List<TypeInfo> columnTypes;
  final private List<String> columnComments;
  final private ObjectInspector oi;

  public AvroObjectInspectorGenerator(Schema schema) throws SerDeException {
    verifySchemaIsARecord(schema);

    this.columnNames = AvroObjectInspectorGenerator.generateColumnNames(schema);
    this.columnTypes = SchemaToTypeInfo.generateColumnTypes(schema);
    this.columnComments = AvroObjectInspectorGenerator.generateColumnComments(schema);
    assert columnNames.size() == columnTypes.size();
    this.oi = createObjectInspector();
  }

  private void verifySchemaIsARecord(Schema schema) throws SerDeException {
    if(!schema.getType().equals(Schema.Type.RECORD)) {
      throw new AvroSerdeException("Schema for table must be of type RECORD. " +
          "Received type: " + schema.getType());
    }
  }

  public List<String> getColumnNames() {
    return columnNames;
  }

  public List<TypeInfo> getColumnTypes() {
    return columnTypes;
  }

  public ObjectInspector getObjectInspector() {
    return oi;
  }

  private ObjectInspector createObjectInspector() throws SerDeException {
    List<ObjectInspector> columnOIs = new ArrayList<ObjectInspector>(columnNames.size());

    // At this point we've verified the types are correct.
    for(int i = 0; i < columnNames.size(); i++) {
      columnOIs.add(i, createObjectInspectorWorker(columnTypes.get(i)));
    }
    return ObjectInspectorFactory.getStandardStructObjectInspector(columnNames, columnOIs, columnComments);
  }

  private ObjectInspector createObjectInspectorWorker(TypeInfo ti) throws SerDeException {
    // We don't need to do the check for U[T,Null] here because we'll give the real type
    // at deserialization and the object inspector will never see the actual union.
    if(!supportedCategories(ti)) {
      throw new AvroSerdeException("Don't yet support this type: " + ti);
    }
    ObjectInspector result;
    switch(ti.getCategory()) {
      case PRIMITIVE:
        PrimitiveTypeInfo pti = (PrimitiveTypeInfo)ti;
        result = PrimitiveObjectInspectorFactory.getPrimitiveJavaObjectInspector(pti);
        break;
      case STRUCT:
        StructTypeInfo sti = (StructTypeInfo)ti;
        ArrayList<ObjectInspector> ois = new ArrayList<ObjectInspector>(sti.getAllStructFieldTypeInfos().size());
        for(TypeInfo typeInfo : sti.getAllStructFieldTypeInfos()) {
          ois.add(createObjectInspectorWorker(typeInfo));
        }

        result = ObjectInspectorFactory
                .getStandardStructObjectInspector(sti.getAllStructFieldNames(), ois);

        break;
      case MAP:
        MapTypeInfo mti = (MapTypeInfo)ti;
        result = ObjectInspectorFactory.getStandardMapObjectInspector(
            PrimitiveObjectInspectorFactory
                    .getPrimitiveJavaObjectInspector(PrimitiveObjectInspector.PrimitiveCategory.STRING),
            createObjectInspectorWorker(mti.getMapValueTypeInfo()));
        break;
      case LIST:
        ListTypeInfo ati = (ListTypeInfo)ti;
        result = ObjectInspectorFactory
                .getStandardListObjectInspector(createObjectInspectorWorker(ati.getListElementTypeInfo()));
        break;
      case UNION:
        UnionTypeInfo uti = (UnionTypeInfo)ti;
        List<TypeInfo> allUnionObjectTypeInfos = uti.getAllUnionObjectTypeInfos();
        List<ObjectInspector> unionObjectInspectors = new ArrayList<ObjectInspector>(allUnionObjectTypeInfos.size());

        for (TypeInfo typeInfo : allUnionObjectTypeInfos) {
          unionObjectInspectors.add(createObjectInspectorWorker(typeInfo));
        }

        result = ObjectInspectorFactory.getStandardUnionObjectInspector(unionObjectInspectors);
        break;
      default:
        throw new AvroSerdeException("No Hive categories matched: " + ti);
    }

    return result;
  }

  private boolean supportedCategories(TypeInfo ti) {
    final ObjectInspector.Category c = ti.getCategory();
    return c.equals(ObjectInspector.Category.PRIMITIVE) ||
           c.equals(ObjectInspector.Category.MAP)       ||
           c.equals(ObjectInspector.Category.LIST)      ||
           c.equals(ObjectInspector.Category.STRUCT)    ||
           c.equals(ObjectInspector.Category.UNION);
  }

  public static List<String> generateColumnNames(Schema schema) {
    List<Schema.Field> fields = schema.getFields();
    List<String> fieldsList = new ArrayList<String>(fields.size());

    for (Schema.Field field : fields) {
      fieldsList.add(field.name());
    }

    return fieldsList;
  }

  public static List<String> generateColumnComments(Schema schema) {
    List<Schema.Field> fields = schema.getFields();
    List<String> fieldComments = new ArrayList<String>(fields.size());

    for (Schema.Field field : fields) {
      String fieldComment = field.doc() == null ? "" : field.doc();
      fieldComments.add(fieldComment);
    }

    return fieldComments;
  }
}


text:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { URLS, IProfile } from './profile';

@Injectable()
export class ProfileService {

  private _item: Observable<IProfile> = null;

  constructor(private http: Http) { }

  clearCache() {
    this._item = null;
  }

  getProfile(): Observable<IProfile> {
    if (!this._item) {
      // no retry
      this._item = this.http.get(URLS.PROFILE).map(res => <IProfile>(res.json() || {})).publishReplay(1).refCount();
    }
    return this._item;
  }

}