text:
typedef struct {
  const char * dataPath;
  uint32_t minThreadCount;
  uint32_t entityTypeMask;
  uint32_t sleepTime;
} ecg_config_editable_t;

static ecg_config_t default_settings = { "data/", 2, 0, 50 };
static ecg_config_t current_settings = default_settings;

ecg_config_t config_default()
{
  return default_settings;
}

ecg_config_t config_current()
{
  return current_settings;
}

bool config_setCurrent(ecg_config_t* a_Config)
{
  bool exists = a_Config != nullptr;
  if (exists)
  {
    current_settings = *a_Config;
  }

  return exists;
}

bool config_setDataPath(void* a_Config, const char * a_Path)
{
  bool exists = a_Config != nullptr && a_Path != nullptr;
  if (exists)
  {
    ecg_config_editable_t* editable = static_cast<ecg_config_editable_t*>(a_Config);
    editable->dataPath = a_Path;
  }

  return exists;
}


text:
namespace v8 {
namespace internal {

//
// IC is the base class for LoadIC, StoreIC, KeyedLoadIC, and KeyedStoreIC.
//
class IC {
 public:
  // Alias the inline cache state type to make the IC code more readable.
  typedef InlineCacheState State;

  // The IC code is either invoked with no extra frames on the stack
  // or with a single extra frame for supporting calls.
  enum FrameDepth { NO_EXTRA_FRAME = 0, EXTRA_CALL_FRAME = 1 };

  // Construct the IC structure with the given number of extra
  // JavaScript frames on the stack.
  IC(FrameDepth depth, Isolate* isolate, FeedbackNexus* nexus = NULL);
  virtual ~IC() {}

  State state() const { return state_; }
  inline Address address() const;

  // Compute the current IC state based on the target stub, receiver and name.
  void UpdateState(Handle<Object> receiver, Handle<Object> name);

  bool RecomputeHandlerForName(Handle<Object> name);
  void MarkRecomputeHandler(Handle<Object> name) {
    DCHECK(RecomputeHandlerForName(name));
    old_state_ = state_;
    state_ = RECOMPUTE_HANDLER;
  }

  // Clear the inline cache to initial state.
  static void Clear(Isolate* isolate, Address address, Address constant_pool);

#ifdef DEBUG
  bool IsLoadStub() const {
    return kind_ == Code::LOAD_IC || kind_ == Code::LOAD_GLOBAL_IC ||
           kind_ == Code::KEYED_LOAD_IC;
  }
  bool IsStoreStub() const {
    return kind_ == Code::STORE_IC || kind_ == Code::KEYED_STORE_IC;
  }
  bool IsCallStub() const { return kind_ == Code::CALL_IC; }
#endif

  static inline Handle<Map> GetHandlerCacheHolder(Handle<Map> receiver_map,
                                                  bool receiver_is_holder,
                                                  Isolate* isolate,
                                                  CacheHolderFlag* flag);
  static inline Handle<Map> GetICCacheHolder(Handle<Map> receiver_map,
                                             Isolate* isolate,
                                             CacheHolderFlag* flag);

  static bool IsCleared(FeedbackNexus* nexus) {
    InlineCacheState state = nexus->StateFromFeedback();
    return !FLAG_use_ic || state == UNINITIALIZED || state == PREMONOMORPHIC;
  }

  static bool ICUseVector(Code::Kind kind) {
    return kind == Code::LOAD_IC || kind == Code::LOAD_GLOBAL_IC ||
           kind == Code::KEYED_LOAD_IC || kind == Code::CALL_IC ||
           kind == Code::STORE_IC || kind == Code::KEYED_STORE_IC;
  }

  // The ICs that don't pass slot and vector through the stack have to
  // save/restore them in the dispatcher.
  static bool ShouldPushPopSlotAndVector(Code::Kind kind);

  static InlineCacheState StateFromCode(Code* code);

  static inline bool IsHandler(Object* object);

 protected:
  Address fp() const { return fp_; }
  Address pc() const { return *pc_address_; }
  Isolate* isolate() const { return isolate_; }

  // Get the shared function info of the caller.
  SharedFunctionInfo* GetSharedFunctionInfo() const;
  // Get the code object of the caller.
  Code* GetCode() const;

  inline bool AddressIsDeoptimizedCode() const;
  inline static bool AddressIsDeoptimizedCode(Isolate* isolate,
                                              Address address);

  // Set the call-site target.
  inline void set_target(Code* code);
  bool is_vector_set() { return vector_set_; }

  bool UseVector() const {
    bool use = ICUseVector(kind());
    // If we are supposed to use the nexus, verify the nexus is non-null.
    DCHECK(!use || nexus_ != nullptr);
    return use;
  }

  // Configure for most states.
  void ConfigureVectorState(IC::State new_state, Handle<Object> key);
  // Configure the vector for MONOMORPHIC.
  void ConfigureVectorState(Handle<Name> name, Handle<Map> map,
                            Handle<Object> handler);
  // Configure the vector for POLYMORPHIC.
  void ConfigureVectorState(Handle<Name> name, MapHandleList* maps,
                            List<Handle<Object>>* handlers);
  // Configure the vector for POLYMORPHIC with transitions (only for element
  // keyed stores).
  void ConfigureVectorState(MapHandleList* maps,
                            MapHandleList* transitioned_maps,
                            List<Handle<Object>>* handlers);

  char TransitionMarkFromState(IC::State state);
  void TraceIC(const char* type, Handle<Object> name);
  void TraceIC(const char* type, Handle<Object> name, State old_state,
               State new_state);

  MaybeHandle<Object> TypeError(MessageTemplate::Template,
                                Handle<Object> object, Handle<Object> key);
  MaybeHandle<Object> ReferenceError(Handle<Name> name);

  // Access the target code for the given IC address.
  static inline Code* GetTargetAtAddress(Address address,
                                         Address constant_pool);
  static inline void SetTargetAtAddress(Address address, Code* target,
                                        Address constant_pool);
  // As a vector-based IC, type feedback must be updated differently.
  static void OnTypeFeedbackChanged(Isolate* isolate, Code* host);
  static void PostPatching(Address address, Code* target, Code* old_target);

  void TraceHandlerCacheHitStats(LookupIterator* lookup);

  // Compute the handler either by compiling or by retrieving a cached version.
  Handle<Object> ComputeHandler(LookupIterator* lookup,
                                Handle<Object> value = Handle<Code>::null());
  virtual Handle<Object> GetMapIndependentHandler(LookupIterator* lookup) {
    UNREACHABLE();
    return Handle<Code>::null();
  }
  virtual Handle<Object> CompileHandler(LookupIterator* lookup,
                                        Handle<Object> value,
                                        CacheHolderFlag cache_holder) {
    UNREACHABLE();
    return Handle<Object>::null();
  }

  void UpdateMonomorphicIC(Handle<Object> handler, Handle<Name> name);
  bool UpdatePolymorphicIC(Handle<Name> name, Handle<Object> code);
  void UpdateMegamorphicCache(Map* map, Name* name, Object* code);

  StubCache* stub_cache();

  void CopyICToMegamorphicCache(Handle<Name> name);
  bool IsTransitionOfMonomorphicTarget(Map* source_map, Map* target_map);
  void PatchCache(Handle<Name> name, Handle<Object> code);
  Code::Kind kind() const { return kind_; }
  bool is_keyed() const {
    return kind_ == Code::KEYED_LOAD_IC || kind_ == Code::KEYED_STORE_IC;
  }
  Code::Kind handler_kind() const {
    if (kind_ == Code::KEYED_LOAD_IC) return Code::LOAD_IC;
    DCHECK(kind_ == Code::LOAD_IC || kind_ == Code::STORE_IC ||
           kind_ == Code::KEYED_STORE_IC);
    return kind_;
  }
  bool ShouldRecomputeHandler(Handle<String> name);

  ExtraICState extra_ic_state() const { return extra_ic_state_; }

  Handle<Map> receiver_map() { return receiver_map_; }
  void update_receiver_map(Handle<Object> receiver) {
    if (receiver->IsSmi()) {
      receiver_map_ = isolate_->factory()->heap_number_map();
    } else {
      receiver_map_ = handle(HeapObject::cast(*receiver)->map());
    }
  }

  void TargetMaps(MapHandleList* list) {
    FindTargetMaps();
    for (int i = 0; i < target_maps_.length(); i++) {
      list->Add(target_maps_.at(i));
    }
  }

  Map* FirstTargetMap() {
    FindTargetMaps();
    return target_maps_.length() > 0 ? *target_maps_.at(0) : NULL;
  }

  Handle<TypeFeedbackVector> vector() const { return nexus()->vector_handle(); }
  FeedbackVectorSlot slot() const { return nexus()->slot(); }
  State saved_state() const {
    return state() == RECOMPUTE_HANDLER ? old_state_ : state();
  }

  template <class NexusClass>
  NexusClass* casted_nexus() {
    return static_cast<NexusClass*>(nexus_);
  }
  FeedbackNexus* nexus() const { return nexus_; }

  inline Code* get_host();
  inline Code* target() const;

 private:
  inline Address constant_pool() const;
  inline Address raw_constant_pool() const;

  void FindTargetMaps() {
    if (target_maps_set_) return;
    target_maps_set_ = true;
    DCHECK(UseVector());
    nexus()->ExtractMaps(&target_maps_);
  }

  // Frame pointer for the frame that uses (calls) the IC.
  Address fp_;

  // All access to the program counter and constant pool of an IC structure is
  // indirect to make the code GC safe. This feature is crucial since
  // GetProperty and SetProperty are called and they in turn might
  // invoke the garbage collector.
  Address* pc_address_;

  // The constant pool of the code which originally called the IC (which might
  // be for the breakpointed copy of the original code).
  Address* constant_pool_address_;

  Isolate* isolate_;

  bool vector_set_;
  State old_state_;  // For saving if we marked as prototype failure.
  State state_;
  Code::Kind kind_;
  Handle<Map> receiver_map_;
  MaybeHandle<Object> maybe_handler_;

  ExtraICState extra_ic_state_;
  MapHandleList target_maps_;
  bool target_maps_set_;

  FeedbackNexus* nexus_;

  DISALLOW_IMPLICIT_CONSTRUCTORS(IC);
};

class CallIC : public IC {
 public:
  CallIC(Isolate* isolate, CallICNexus* nexus)
      : IC(EXTRA_CALL_FRAME, isolate, nexus) {
    DCHECK(nexus != NULL);
  }

  void HandleMiss(Handle<Object> function);

  static void Clear(Isolate* isolate, Code* host, CallICNexus* nexus);
};

class LoadIC : public IC {
 public:
  LoadIC(FrameDepth depth, Isolate* isolate, FeedbackNexus* nexus = NULL)
      : IC(depth, isolate, nexus) {
    DCHECK(nexus != NULL);
    DCHECK(IsLoadStub());
  }

  bool ShouldThrowReferenceError() const {
    return kind() == Code::LOAD_GLOBAL_IC &&
           LoadGlobalICState::GetTypeofMode(extra_ic_state()) ==
               NOT_INSIDE_TYPEOF;
  }

  MUST_USE_RESULT MaybeHandle<Object> Load(Handle<Object> object,
                                           Handle<Name> name);

  static void Clear(Isolate* isolate, Code* host, LoadICNexus* nexus);

 protected:
  virtual Handle<Code> slow_stub() const {
    return isolate()->builtins()->LoadIC_Slow();
  }

  // Update the inline cache and the global stub cache based on the
  // lookup result.
  void UpdateCaches(LookupIterator* lookup);

  Handle<Object> GetMapIndependentHandler(LookupIterator* lookup) override;

  Handle<Object> CompileHandler(LookupIterator* lookup, Handle<Object> unused,
                                CacheHolderFlag cache_holder) override;

 private:
  // Creates a data handler that represents a load of a field by given index.
  static Handle<Object> SimpleFieldLoad(Isolate* isolate, FieldIndex index);

  // Creates a data handler that represents a prototype chain check followed
  // by given Smi-handler that encoded a load from the holder.
  // Can be used only if GetPrototypeCheckCount() returns non negative value.
  Handle<Object> LoadFromPrototype(Handle<Map> receiver_map,
                                   Handle<JSObject> holder, Handle<Name> name,
                                   Handle<Object> smi_handler);

  // Creates a data handler that represents a load of a non-existent property.
  Handle<Object> LoadNonExistent(Handle<Map> receiver_map, Handle<Name> name);

  friend class IC;
  friend class NamedLoadHandlerCompiler;
};

class LoadGlobalIC : public LoadIC {
 public:
  LoadGlobalIC(FrameDepth depth, Isolate* isolate, FeedbackNexus* nexus = NULL)
      : LoadIC(depth, isolate, nexus) {}

  MUST_USE_RESULT MaybeHandle<Object> Load(Handle<Name> name);

  static void Clear(Isolate* isolate, Code* host, LoadGlobalICNexus* nexus);

 protected:
  Handle<Code> slow_stub() const override {
    return isolate()->builtins()->LoadGlobalIC_Slow();
  }
};

class KeyedLoadIC : public LoadIC {
 public:
  KeyedLoadIC(FrameDepth depth, Isolate* isolate,
              KeyedLoadICNexus* nexus = NULL)
      : LoadIC(depth, isolate, nexus) {
    DCHECK(nexus != NULL);
  }

  MUST_USE_RESULT MaybeHandle<Object> Load(Handle<Object> object,
                                           Handle<Object> key);

  static void Clear(Isolate* isolate, Code* host, KeyedLoadICNexus* nexus);

 protected:
  // receiver is HeapObject because it could be a String or a JSObject
  void UpdateLoadElement(Handle<HeapObject> receiver);

 private:
  friend class IC;
};

class StoreIC : public IC {
 public:
  StoreIC(FrameDepth depth, Isolate* isolate, FeedbackNexus* nexus = NULL)
      : IC(depth, isolate, nexus) {
    DCHECK(IsStoreStub());
  }

  LanguageMode language_mode() const {
    return StoreICState::GetLanguageMode(extra_ic_state());
  }

  MUST_USE_RESULT MaybeHandle<Object> Store(
      Handle<Object> object, Handle<Name> name, Handle<Object> value,
      JSReceiver::StoreFromKeyed store_mode =
          JSReceiver::CERTAINLY_NOT_STORE_FROM_KEYED);

  bool LookupForWrite(LookupIterator* it, Handle<Object> value,
                      JSReceiver::StoreFromKeyed store_mode);

  static void Clear(Isolate* isolate, Code* host, StoreICNexus* nexus);

 protected:
  // Stub accessors.
  Handle<Code> slow_stub() const {
    switch (language_mode()) {
      case SLOPPY:
        return isolate()->builtins()->StoreIC_SlowSloppy();
      case STRICT:
        return isolate()->builtins()->StoreIC_SlowStrict();
      default:
        UNREACHABLE();
        return Handle<Code>();
    }
  }

  // Update the inline cache and the global stub cache based on the
  // lookup result.
  void UpdateCaches(LookupIterator* lookup, Handle<Object> value,
                    JSReceiver::StoreFromKeyed store_mode);
  Handle<Object> GetMapIndependentHandler(LookupIterator* lookup) override;
  Handle<Object> CompileHandler(LookupIterator* lookup, Handle<Object> value,
                                CacheHolderFlag cache_holder) override;

 private:
  Handle<Object> StoreTransition(Handle<Map> receiver_map,
                                 Handle<JSObject> holder,
                                 Handle<Map> transition, Handle<Name> name);

  friend class IC;
};

enum KeyedStoreCheckMap { kDontCheckMap, kCheckMap };

enum KeyedStoreIncrementLength { kDontIncrementLength, kIncrementLength };

class KeyedStoreIC : public StoreIC {
 public:
  KeyedAccessStoreMode GetKeyedAccessStoreMode() {
    return casted_nexus<KeyedStoreICNexus>()->GetKeyedAccessStoreMode();
  }

  KeyedStoreIC(FrameDepth depth, Isolate* isolate,
               KeyedStoreICNexus* nexus = NULL)
      : StoreIC(depth, isolate, nexus) {}

  MUST_USE_RESULT MaybeHandle<Object> Store(Handle<Object> object,
                                            Handle<Object> name,
                                            Handle<Object> value);

  // Code generators for stub routines.  Only called once at startup.
  static void GenerateMiss(MacroAssembler* masm);
  static void GenerateSlow(MacroAssembler* masm);
  static void GenerateMegamorphic(MacroAssembler* masm,
                                  LanguageMode language_mode);

  static void Clear(Isolate* isolate, Code* host, KeyedStoreICNexus* nexus);

 protected:
  void UpdateStoreElement(Handle<Map> receiver_map,
                          KeyedAccessStoreMode store_mode);

 private:
  Handle<Map> ComputeTransitionedMap(Handle<Map> map,
                                     KeyedAccessStoreMode store_mode);

  friend class IC;
};

// Type Recording BinaryOpIC, that records the types of the inputs and outputs.
class BinaryOpIC : public IC {
 public:
  explicit BinaryOpIC(Isolate* isolate) : IC(EXTRA_CALL_FRAME, isolate) {}

  MaybeHandle<Object> Transition(Handle<AllocationSite> allocation_site,
                                 Handle<Object> left,
                                 Handle<Object> right) WARN_UNUSED_RESULT;
};

class CompareIC : public IC {
 public:
  CompareIC(Isolate* isolate, Token::Value op)
      : IC(EXTRA_CALL_FRAME, isolate), op_(op) {}

  // Update the inline cache for the given operands.
  Code* UpdateCaches(Handle<Object> x, Handle<Object> y);

  // Helper function for computing the condition for a compare operation.
  static Condition ComputeCondition(Token::Value op);

 private:
  static bool HasInlinedSmiCode(Address address);

  bool strict() const { return op_ == Token::EQ_STRICT; }
  Condition GetCondition() const { return ComputeCondition(op_); }

  static Code* GetRawUninitialized(Isolate* isolate, Token::Value op);

  static void Clear(Isolate* isolate, Address address, Code* target,
                    Address constant_pool);

  Token::Value op_;

  friend class IC;
};

class ToBooleanIC : public IC {
 public:
  explicit ToBooleanIC(Isolate* isolate) : IC(EXTRA_CALL_FRAME, isolate) {}

  Handle<Object> ToBoolean(Handle<Object> object);
};

// Helper for BinaryOpIC and CompareIC.
enum InlinedSmiCheck { ENABLE_INLINED_SMI_CHECK, DISABLE_INLINED_SMI_CHECK };
void PatchInlinedSmiCode(Isolate* isolate, Address address,
                         InlinedSmiCheck check);

}  // namespace internal
}  // namespace v8

#endif  // V8_IC_H_

redpajama_set_name: RedPajamaGithub


text:
 // Create a string variable with quoted text in it.

var quotedPirsig = 'After a while he says, "Do you believe in ghosts?"\n' +
    ' "No," I say.\n "Why not?"\n "Because they are un-sci-en-ti-fic."\n' +
    ' The way I say this makes John smile. "They contain no matter," I continue, "and have no energy and therefore, ' +
    'according to the laws of science, do not exist except in people\'s minds."\n' +
    ' The whiskey, the fatigue and the wind in the trees start mixing in my mind. "Of course," I add, ' +
    '"the laws of science contain no matter and have no energy either and therefore do not exist except in people\'s minds. ' +
    'It\'s best to be completely scientific about the whole thing and refuse to believe in either ghosts or the laws of science. ' +
    'That way you\'re safe. That doesn\'t leave you very much to believe in, but that\'s scientific too."';

console.log(quotedPirsig);


text: I allow users to see and publish existing local commits.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Pytocs.Core.CodeModel;

namespace Pytocs.Core.Translate
{
    public class LocalVariableGenerator : ICodeStatementVisitor<int>
    {
        private Dictionary<CodeStatement, List<CodeStatement>> parentOf;
        private List<CodeStatement> path;
        private Dictionary<CodeVariableReferenceExpression, List<List<CodeStatement>>> paths;
        private List<CodeParameterDeclarationExpression> parameters;
        private List<CodeStatement> statements;
        private HashSet<string> globals;

        public static void Generate(CodeMemberMethod method, HashSet<string> globals)
        {
            var gen = new LocalVariableGenerator(method.Parameters, method.Statements, globals);
            gen.Analyze(new List<CodeStatement>(), method.Statements);
            gen.Generate();
        }

        public static void Generate(List<CodeParameterDeclarationExpression>? parameters, List<CodeStatement> statements, HashSet<string> globals)
        {
            parameters ??= new List<CodeParameterDeclarationExpression>();
            var gen = new LocalVariableGenerator(parameters, statements, globals);
            gen.Analyze(new List<CodeStatement>(), statements);
            gen.Generate();
        }

        private LocalVariableGenerator(
            List<CodeParameterDeclarationExpression> parameters,
            List<CodeStatement> statements,
            HashSet<string> globals)
        {
            this.parameters = parameters;
            this.statements = statements;
            this.globals = globals;
            this.parentOf = new Dictionary<CodeStatement, List<CodeStatement>>();
            this.path = new List<CodeStatement>();
            this.paths = new Dictionary<CodeVariableReferenceExpression, List<List<CodeStatement>>>(
                new IdCmp());
        }

        private void Analyze(List<CodeStatement> basePath, List<CodeStatement> statements)
        {
            foreach (var stm in statements)
            {
                var opath = this.path;
                this.path = basePath.Concat(new[] { stm }).ToList();
                stm.Accept(this);
                parentOf[stm] = statements;
                this.path = opath;
            }
        }

        private void AnalyzeExp(List<CodeStatement> basePath, CodeExpression exp)
        {
            var visitor = new ExpLocalVarGenerator(this);
            exp.Accept(visitor);
        }

        private void Generate()
        {
            var paramNames = new HashSet<string?>(
                parameters
                .Select(p => p.ParameterName));
            foreach (var de in paths.Where(
                d => !paramNames.Contains(d.Key.Name)))
            {
                var id = de.Key;
                var defs = de.Value;
                if (defs.Count == 1)
                {
                    ReplaceWithDeclaration(id, defs[0], defs[0].Count - 1);
                }
                else
                {
                    var first = defs[0];
                    int iCommon = first.Count - 1;
                    foreach (var path in defs.Skip(1))
                    {
                        iCommon = FindCommon(first, path, iCommon);
                    }
                    ReplaceWithDeclaration(id, first, iCommon);
                }
            }
        }

        private int FindCommon(List<CodeStatement> a, List<CodeStatement> b, int iCommon)
        {
            iCommon = Math.Min(iCommon, a.Count - 1);
            iCommon = Math.Min(iCommon, b.Count - 1);
            int i;
            for (i = 0; i <= iCommon; ++i)
            {
                if (parentOf[a[i]] != parentOf[b[i]])
                    return i - 1;
                if (a[i] != b[i])
                    return i;
            }
            return i;
        }

        private void ReplaceWithDeclaration(CodeVariableReferenceExpression id, List<CodeStatement> path, int iCommon)
        {
            if (iCommon >= 0)
            {
                var codeStatement = path[iCommon];
                var stms = this.parentOf[codeStatement];
                var i = stms.IndexOf(codeStatement);
                if (i >= 0)
                {
                    if (codeStatement is CodeAssignStatement ass)
                    {
                        // An assignment of type 'name = <exp>'. If the value
                        // assigned is null, use object type 'object', otherwise
                        // use 'var'.
                        var dstType = ass.Source is CodePrimitiveExpression prim && prim.Value == null
                            ? "object"
                            : "var";
                        stms[i] = new CodeVariableDeclarationStatement(dstType, id.Name)
                        {
                            InitExpression = ass.Source
                        };
                        return;
                    }
                }
            }
            statements.Insert(
                0,
                new CodeVariableDeclarationStatement("object", id.Name));
        }

        private void EnsurePath(CodeVariableReferenceExpression id)
        {
            if (!this.paths.TryGetValue(id, out var paths))
            {
                paths = new List<List<CodeStatement>>();
                this.paths.Add(id, paths);
            }
            paths.Add(this.path);
        }

        public int VisitAssignment(CodeAssignStatement ass)
        {
            if (ass.Destination is CodeVariableReferenceExpression id)
            {
                if (this.globals.Contains(id.Name))
                    return 0;
                EnsurePath(id);
            }
            AnalyzeExp(this.path, ass.Source);
            return 0;
        }

        public int VisitBreak(CodeBreakStatement b)
        {
            return 0;
        }

        public int VisitComment(CodeCommentStatement codeCommentStatement)
        {
            return 0;
        }

        public int VisitContinue(CodeContinueStatement c)
        {
            return 0;
        }

        public int VisitForeach(CodeForeachStatement f)
        {
            AnalyzeExp(this.path, f.Collection);
            Analyze(this.path, f.Statements);
            return 0;
        }

        public int VisitIf(CodeConditionStatement cond)
        {
            AnalyzeExp(this.path, cond.Condition);
            Analyze(this.path, cond.TrueStatements);
            Analyze(this.path, cond.FalseStatements);
            return 0;
        }

        public int VisitLocalFunction(CodeLocalFunction _)
        {
            return 0;
        }

        public int VisitPostTestLoop(CodePostTestLoopStatement l)
        {
            AnalyzeExp(this.path, l.Test);
            Analyze(this.path, l.Body);
            return 0;
        }

        public int VisitPreTestLoop(CodePreTestLoopStatement l)
        {
            AnalyzeExp(this.path, l.Test);
            Analyze(this.path, l.Body);
            return 0;
        }

        public int VisitReturn(CodeMethodReturnStatement ret)
        {
            return 0;
        }

        public int VisitSideEffect(CodeExpressionStatement side)
        {
            return 0;
        }

        public int VisitThrow(CodeThrowExceptionStatement t)
        {
            return 0;
        }

        public int VisitTry(CodeTryCatchFinallyStatement t)
        {
            Analyze(this.path, t.TryStatements);
            foreach (var c in t.CatchClauses)
            {
                Analyze(this.path, c.Statements);
            }
            Analyze(this.path, t.FinallyStatements);
            return 0;
        }

        public int VisitUsing(CodeUsingStatement codeUsingStatement)
        {
            return 0;
        }

        public int VisitVariableDeclaration(CodeVariableDeclarationStatement decl)
        {
            return 0;
        }

        public int VisitYield(CodeYieldStatement y)
        {
            return 0;
        }

        internal class IdCmp : IEqualityComparer<CodeVariableReferenceExpression>
        {
            public bool Equals(CodeVariableReferenceExpression x, CodeVariableReferenceExpression y)
            {
                return x.Name == y.Name;
            }

            public int GetHashCode(CodeVariableReferenceExpression obj)
            {
                return obj.Name.GetHashCode();
            }
        }

        class ExpLocalVarGenerator : ICodeExpressionVisitor
        {
            private readonly LocalVariableGenerator outer;

            public ExpLocalVarGenerator(LocalVariableGenerator outer)
            {
                this.outer = outer;
            }

            public void VisitApplication(CodeApplicationExpression app)
            {
                foreach (var e in app.Arguments)
                {
                    e.Accept(this);
                }
            }

            public void VisitArrayIndexer(CodeArrayIndexerExpression aref)
            {
                aref.TargetObject.Accept(this);
                foreach (var i in aref.Indices)
                {
                    i.Accept(this);
                }
            }

            public void VisitArrayInitializer(CodeArrayCreateExpression arr)
            {
                foreach (var e in arr.Initializers)
                {
                    e.Accept(this);
                }
            }

            public void VisitAwait(CodeAwaitExpression awaitExp)
            {
                awaitExp.Expression.Accept(this);
            }

            public void VisitBase(CodeBaseReferenceExpression baseExp)
            {
            }

            public void VisitBinary(CodeBinaryOperatorExpression bin)
            {
                if (bin.Operator == CodeOperatorType.Assign && bin.Left is CodeVariableReferenceExpression id)
                {
                    if (outer.globals.Contains(id.Name))
                        return;
                    outer.EnsurePath(id);
                }
                else
                {
                    bin.Left.Accept(this);
                }
                bin.Right.Accept(this);
            }

            public void VisitCast(CodeCastExpression cast)
            {
                cast.Expression.Accept(this);
            }

            public void VisitCollectionInitializer(CodeCollectionInitializer i)
            {
                foreach (var e in i.Values)
                {
                    e.Accept(this);
                }
            }

            public void VisitCondition(CodeConditionExpression condition)
            {
                condition.Condition.Accept(this);
                condition.Consequent.Accept(this);
                condition.Alternative.Accept(this);
            }

            public void VisitDefaultExpression(CodeDefaultExpression defaultExp)
            {
            }

            public void VisitFieldReference(CodeFieldReferenceExpression field)
            {
                field.Expression.Accept(this);
            }

            public void VisitLambda(CodeLambdaExpression l)
            {
                l.Body.Accept(this);
            }

            public void VisitMethodReference(CodeMethodReferenceExpression m)
            {
                m.TargetObject.Accept(this);
            }

            public void VisitNamedArgument(CodeNamedArgument arg)
            {
            }

            public void VisitNumericLiteral(CodeNumericLiteral literal)
            {
            }

            public void VisitObjectCreation(CodeObjectCreateExpression c)
            {
                c.Initializer?.Accept(this);
                c.Initializers.ForEach(e => e.Accept(this));
            }

            public void VisitObjectInitializer(CodeObjectInitializer i)
            {
                i.MemberDeclarators.ForEach(d => d.Expression?.Accept(this));
            }

            public void VisitParameterDeclaration(CodeParameterDeclarationExpression param)
            {
                param.DefaultValue?.Accept(this);
            }

            public void VisitPrimitive(CodePrimitiveExpression p)
            {
            }

            public void VisitQueryExpression(CodeQueryExpression q)
            {
                foreach (var c in q.Clauses)
                {
                    switch (c)
                    {
                    case CodeFromClause f:
                        f.Identifier.Accept(this);
                        f.Collection.Accept(this);
                        break;
                    case CodeLetClause l:
                        l.Value.Accept(this);
                        break;
                    case CodeWhereClause w:
                        w.Condition.Accept(this);
                        break;
                    case CodeSelectClause s:
                        s.Projection.Accept(this);
                        break;
                    }
                }
            }

            public void VisitThisReference(CodeThisReferenceExpression t)
            {
            }

            public void VisitTypeReference(CodeTypeReferenceExpression t)
            {
            }

            public void VisitUnary(CodeUnaryOperatorExpression u)
            {
                u.Expression.Accept(this);
            }

            public void VisitValueTuple(CodeValueTupleExpression codeValueTupleExpression)
            {
                foreach (var v in codeValueTupleExpression.Expressions)
                {
                    v.Accept(this);
                }
            }

            public void VisitVariableReference(CodeVariableReferenceExpression var)
            {
            }
        }
    }
}


text:
package laika.parse.rst

import laika.tree.Elements._

/** Provides the elements of the document tree that are too specific to reStructuredText
 *  to be added to the generic tree model.
 *
 *  @author Jens Halm
 */
object Elements {

  /** A two-column table-like structure used for bibliographic fields or directive options.
   */
  case class FieldList (content: Seq[Field], options: Options = NoOpt) extends Block with ListContainer[FieldList]

  /** A single entry in a field list consisting of name and body.
   */
  case class Field (name: Seq[Span], content: Seq[Block], options: Options = NoOpt) extends ListItem with BlockContainer[Field]

  /** A classifier for a term in a definition list.
   */
  case class Classifier (content: Seq[Span], options: Options = NoOpt) extends Span with SpanContainer[Classifier]

  /** A list of command line options and descriptions.
   */
  case class OptionList (content: Seq[OptionListItem], options: Options = NoOpt) extends Block with ListContainer[OptionList]

  /** A single item in an option list. The content property serves as the description of the option.
   */
  case class OptionListItem (programOptions: Seq[ProgramOption], content: Seq[Block], options: Options = NoOpt) extends ListItem
                                                                                with BlockContainer[OptionListItem]

  /** A single option, including its name and all arguments, but not the description.
   */
  case class ProgramOption (name: String, argument: scala.Option[OptionArgument]) extends Element

  /** A single option argument.
   */
  case class OptionArgument (value: String, delimiter: String) extends Element

  /** A substitution definition with its span content that will be inserted
   *  wherever this substitution is referenced in flow content.
   */
  case class SubstitutionDefinition (name: String, content: Span, options: Options = NoOpt) extends Definition

  /** Refers to a substitution definition with the same name.
   *  This type of element will only temporarily be part of the document tree and replaced
   *  by the content of the substitution definition in a rewrite step.
   */
  case class SubstitutionReference (name: String, options: Options = NoOpt) extends Reference {
    val source = "|"+name+"|"
  }

  /** Represents an interactive Python session. Somewhat unlikely to be used in
   *  the context of this library, but included for the sake of completeness.
   */
  case class DoctestBlock (content: String, options: Options = NoOpt) extends Block with TextContainer

  /** Header decoration consisting of both an overline and an underline.
   */
  case class OverlineAndUnderline (char: Char) extends HeaderDecoration

  /** Header decoration consisting of an underline only.
   */
  case class Underline (char: Char) extends HeaderDecoration

  /** Temporary element to represent interpreted text with its associated role name.
   *  In a post-processing step this text will be replaced by the result of calling
   *  the corresponding role function.
   */
  case class InterpretedText (role: String, content: String, source: String, options: Options = NoOpt) extends Reference with TextContainer

  /** Temporary element to represent a customized text role that can be applied
   *  to spans of interpreted text. The `apply` function can then be applied
   *  to spans of interpreted text referring to the name of this role and passing
   *  the text as the argument to the function.
   */
  case class CustomizedTextRole (name: String, apply: String => Span, options: Options = NoOpt) extends Definition

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<ldswebml type="image" uri="/media-library/images/parenthood#father-son-discussion-306252" xml:lang="eng" locale="eng" status="publish">
  <search-meta>
      <uri-title its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">father-son-discussion-306252</uri-title>
      <source>father-son-discussion-306252</source>
      <publication-type its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">image</publication-type>
      <media-type its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">image</media-type>
      <publication value="ldsorg">LDS.org</publication>
      <publication-date value="2012-04-09">2012-04-09</publication-date>
      <title/>
      <description/>
      <collections>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">global-search</collection>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">media</collection>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">images</collection>
      </collections>
      <subjects>
          <subject>Fatherhood</subject>
          <subject>Sons</subject>
          <subject>Parenthood</subject>
          <subject>Discussion</subject>
          <subject>Counsel</subject>
          <subject>Advice</subject>
          <subject>Talking</subject>
      </subjects>
  </search-meta>
  <no-search>
      <path>http://media.ldscdn.org/images/media-library/parenthood/father-son-discussion-306252-gallery.jpg</path>
      <images>
          http://media.ldscdn.org/images/media-library/parenthood/father-son-discussion-306252-thumbnail.jpg
      </images>
          <download-urls>
              <download-url>
                  Mobile
                  <size>225 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/parenthood/father-son-discussion-306252-mobile.jpg</path>
              </download-url>
              <download-url>
                  Tablet
                  <size>254 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/parenthood/father-son-discussion-306252-tablet.jpg</path>
              </download-url>
              <download-url>
                  Print
                  <size>557 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/parenthood/father-son-discussion-306252-print.jpg</path>
              </download-url>
              <download-url>
                  Wallpaper
                  <size>1.1 MB</size>
                  <path>http://media.ldscdn.org/images/media-library/parenthood/father-son-discussion-306252-wallpaper.jpg</path>
              </download-url>
          </download-urls>
  </no-search>
<ldse-meta its:translate="no" xmlns="http://lds.org/code/lds-edit" xmlns:its="http://www.w3.org/2005/11/its"><document id="father-son-discussion-306252" locale="eng" uri="/media-library/images/parenthood#father-son-discussion-306252" status="publish" site="ldsorg" source="chq" words="123" tgp="0.4301"/><created username="lds-edit" userid=""/><last-modified date="2012-05-10T12:26:05.692556-06:00" username="lds-edit" userid=""/></ldse-meta></ldswebml>


text:
package building.decorative;

public class Torch {

}


text:
title: "Fed up of FUD against Novell, SUSE & openSUSE"
date: 2010-12-15
topics:
  - openSUSE
categories:
  - openSUSE
tags:
  - Community
  - Discussion
  - FUD
  - Rant
---
**tl;dr** – To all you doomsday FUD mongers about Novell/SUSE/openSUSE STFU & let us show you what we can and will do!!

For those living under a rock, yes Novell has agreed to be acquired. Welcome to the world of business, and especially in software this sort of thing is very common.

Now for some reason a whole heap of people seem to think that this spells doom for Novell, SUSE and openSUSE. Why?  I really can't answer that.  What I do know is that all their negative speculation is at best counter productive, at worst foolish and damaging.

As with any form of speculation there are no facts to back up what they reckon is going to happen – hence the speculation.  If there is enough negative talk, negative things will happen. Current customers will look at switching from Novell products whether they be SUSE based or not, purely based on all the negativity that is being generated.

No-one is giving Attachemate a chance to prove what they have openly said – Novell, SUSE and openSUSE's contribution to the wider community will continue and that it is business as usual.  If you look at when Oracle bought Sun they said sod all about OpenSolaris and the rest of Sun. This is different.  The new overlords are actually communicating – maybe not as much as we would like, but hey it's a bloody good step in the right direction.

The latest negative piece comes from the [451 Group][1]. Why the frig would Novell's purchase change their kernel contributions?  Why the frig would Novell's purchase change any of their current contributions to the vast array of projects including GNOME/KDE/Banshee/LibreOffice/Systemd and a whole heap of others?  Simple, it doesn't.

 [1]: http://blogs.the451group.com/opensource/2010/12/08/linux-kernel-solid-but-what-will-become-of-novell-contribution "451 Group FUD"

Don't get me wrong Novell has screwed up big time in the past, but we are working together as a community to learn from these mistakes.  All this negative noise is counter productive and just gets in the way.  If you want to see Novell, SUSE and openSUSE flourish hows about you roll your sleeves up and get stuck in?  If you don't want to chip in STFU and wait and see if something does happen.  Then you can berate us and tell us how and where we went wrong.


text:
XabenInstagramBundle
======================
Provides a sonata block to display latest Instagram feed on your website

Installation
------------

Download XabenInstagramBundle and its dependencies to the ``vendor`` directory. You
can use Composer for the automated process:

```console
php composer.phar require xaben/instagram-bundle --no-update

php composer.phar update
```
Next, be sure to enable the bundle in your AppKernel.php file:
```php
// app/AppKernel.php
public function registerBundles()
{
    return array(
        // ...
        new Xaben\InstagramBundle\XabenInstagramBundle(),
        // ...
    );
}
```
Now, install the assets from the bundle:

```console
php app/console assets:install web
```

Configuration
------------
Provide the necesarry configuration in `config.yml` add:
```yml
xaben_instagram:
    api_key: %instagram_api_id%
    user_id: {Your Instagram numeric user ID}
    user_name: {Your Instagram username}
    cache_service: doctrine_cache.providers.{Your cache service name}
```
Configure api key in `parameters.yml` add:
```yml
    instagram_api_id: {YOUR API ID}
```
For cache service use the Doctrine Cacher, to configure it:
```yml
doctrine_cache:
    providers:
        {Your cache service name}:
            type: {Your preffered cache type}
            namespace: {Your namespace}
```
Usage
-----
To display the feed drop the following block in the coresponding place (usually your layout), and the optional runtime configuration, by default the User ID from the configuration and 6 photos are diplayed with the supplied template:
```twig
{{ sonata_block_render(
    { 'type': 'xaben.instagram.block.instagram' },
    {
    'userId': 'the user ID to fetch the feed for',
    'limit': 12,
    'template': 'your custom template'
    }
  )
}}
```


text:
require 'set'
require 'digest/sha1'
require 'sass/cache_stores'
require 'sass/tree/node'
require 'sass/tree/root_node'
require 'sass/tree/rule_node'
require 'sass/tree/comment_node'
require 'sass/tree/prop_node'
require 'sass/tree/directive_node'
require 'sass/tree/media_node'
require 'sass/tree/supports_node'
require 'sass/tree/css_import_node'
require 'sass/tree/variable_node'
require 'sass/tree/mixin_def_node'
require 'sass/tree/mixin_node'
require 'sass/tree/trace_node'
require 'sass/tree/content_node'
require 'sass/tree/function_node'
require 'sass/tree/return_node'
require 'sass/tree/extend_node'
require 'sass/tree/if_node'
require 'sass/tree/while_node'
require 'sass/tree/for_node'
require 'sass/tree/each_node'
require 'sass/tree/debug_node'
require 'sass/tree/warn_node'
require 'sass/tree/import_node'
require 'sass/tree/charset_node'
require 'sass/tree/visitors/base'
require 'sass/tree/visitors/perform'
require 'sass/tree/visitors/cssize'
require 'sass/tree/visitors/extend'
require 'sass/tree/visitors/convert'
require 'sass/tree/visitors/to_css'
require 'sass/tree/visitors/deep_copy'
require 'sass/tree/visitors/set_options'
require 'sass/tree/visitors/check_nesting'
require 'sass/selector'
require 'sass/environment'
require 'sass/script'
require 'sass/scss'
require 'sass/error'
require 'sass/importers'
require 'sass/shared'
require 'sass/media'
require 'sass/supports'

module Sass

  # A Sass mixin or function.
  #
  # `name`: `String`
  # : The name of the mixin/function.
  #
  # `args`: `Array<(Script::Node, Script::Node)>`
  # : The arguments for the mixin/function.
  #   Each element is a tuple containing the variable node of the argument
  #   and the parse tree for the default value of the argument.
  #
  # `splat`: `Script::Node?`
  # : The variable node of the splat argument for this callable, or null.
  #
  # `environment`: {Sass::Environment}
  # : The environment in which the mixin/function was defined.
  #   This is captured so that the mixin/function can have access
  #   to local variables defined in its scope.
  #
  # `tree`: `Array<Tree::Node>`
  # : The parse tree for the mixin/function.
  #
  # `has_content`: `Boolean`
  # : Whether the callable accepts a content block.
  #
  # `type`: `String`
  # : The user-friendly name of the type of the callable.
  Callable = Struct.new(:name, :args, :splat, :environment, :tree, :has_content, :type)

  # This class handles the parsing and compilation of the Sass template.
  # Example usage:
  #
  #     template = File.load('stylesheets/sassy.sass')
  #     sass_engine = Sass::Engine.new(template)
  #     output = sass_engine.render
  #     puts output
  class Engine
    include Sass::Util

    # A line of Sass code.
    #
    # `text`: `String`
    # : The text in the line, without any whitespace at the beginning or end.
    #
    # `tabs`: `Fixnum`
    # : The level of indentation of the line.
    #
    # `index`: `Fixnum`
    # : The line number in the original document.
    #
    # `offset`: `Fixnum`
    # : The number of bytes in on the line that the text begins.
    #   This ends up being the number of bytes of leading whitespace.
    #
    # `filename`: `String`
    # : The name of the file in which this line appeared.
    #
    # `children`: `Array<Line>`
    # : The lines nested below this one.
    #
    # `comment_tab_str`: `String?`
    # : The prefix indentation for this comment, if it is a comment.
    class Line < Struct.new(:text, :tabs, :index, :offset, :filename, :children, :comment_tab_str)
      def comment?
        text[0] == COMMENT_CHAR && (text[1] == SASS_COMMENT_CHAR || text[1] == CSS_COMMENT_CHAR)
      end
    end

    # The character that begins a CSS property.
    PROPERTY_CHAR  = ?:

    # The character that designates the beginning of a comment,
    # either Sass or CSS.
    COMMENT_CHAR = ?/

    # The character that follows the general COMMENT_CHAR and designates a Sass comment,
    # which is not output as a CSS comment.
    SASS_COMMENT_CHAR = ?/

    # The character that indicates that a comment allows interpolation
    # and should be preserved even in `:compressed` mode.
    SASS_LOUD_COMMENT_CHAR = ?!

    # The character that follows the general COMMENT_CHAR and designates a CSS comment,
    # which is embedded in the CSS document.
    CSS_COMMENT_CHAR = ?*

    # The character used to denote a compiler directive.
    DIRECTIVE_CHAR = ?@

    # Designates a non-parsed rule.
    ESCAPE_CHAR    = ?\\

    # Designates block as mixin definition rather than CSS rules to output
    MIXIN_DEFINITION_CHAR = ?=

    # Includes named mixin declared using MIXIN_DEFINITION_CHAR
    MIXIN_INCLUDE_CHAR    = ?+

    # The regex that matches and extracts data from
    # properties of the form `:name prop`.
    PROPERTY_OLD = /^:([^\s=:"]+)\s*(?:\s+|$)(.*)/

    # The default options for Sass::Engine.
    # @api public
    DEFAULT_OPTIONS = {
      :style => :nested,
      :load_paths => ['.'],
      :cache => true,
      :cache_location => './.sass-cache',
      :syntax => :sass,
      :filesystem_importer => Sass::Importers::Filesystem
    }.freeze

    # Converts a Sass options hash into a standard form, filling in
    # default values and resolving aliases.
    #
    # @param options [{Symbol => Object}] The options hash;
    #   see {file:SASS_REFERENCE.md#sass_options the Sass options documentation}
    # @return [{Symbol => Object}] The normalized options hash.
    # @private
    def self.normalize_options(options)
      options = DEFAULT_OPTIONS.merge(options.reject {|k, v| v.nil?})

      # If the `:filename` option is passed in without an importer,
      # assume it's using the default filesystem importer.
      options[:importer] ||= options[:filesystem_importer].new(".") if options[:filename]

      # Tracks the original filename of the top-level Sass file
      options[:original_filename] ||= options[:filename]

      options[:cache_store] ||= Sass::CacheStores::Chain.new(
        Sass::CacheStores::Memory.new, Sass::CacheStores::Filesystem.new(options[:cache_location]))
      # Support both, because the docs said one and the other actually worked
      # for quite a long time.
      options[:line_comments] ||= options[:line_numbers]

      options[:load_paths] = (options[:load_paths] + Sass.load_paths).map do |p|
        next p unless p.is_a?(String) || (defined?(Pathname) && p.is_a?(Pathname))
        options[:filesystem_importer].new(p.to_s)
      end

      # Backwards compatibility
      options[:property_syntax] ||= options[:attribute_syntax]
      case options[:property_syntax]
      when :alternate; options[:property_syntax] = :new
      when :normal; options[:property_syntax] = :old
      end

      options
    end

    # Returns the {Sass::Engine} for the given file.
    # This is preferable to Sass::Engine.new when reading from a file
    # because it properly sets up the Engine's metadata,
    # enables parse-tree caching,
    # and infers the syntax from the filename.
    #
    # @param filename [String] The path to the Sass or SCSS file
    # @param options [{Symbol => Object}] The options hash;
    #   See {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
    # @return [Sass::Engine] The Engine for the given Sass or SCSS file.
    # @raise [Sass::SyntaxError] if there's an error in the document.
    def self.for_file(filename, options)
      had_syntax = options[:syntax]

      if had_syntax
        # Use what was explicitly specificed
      elsif filename =~ /\.scss$/
        options.merge!(:syntax => :scss)
      elsif filename =~ /\.sass$/
        options.merge!(:syntax => :sass)
      end

      Sass::Engine.new(File.read(filename), options.merge(:filename => filename))
    end

    # The options for the Sass engine.
    # See {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
    #
    # @return [{Symbol => Object}]
    attr_reader :options

    # Creates a new Engine. Note that Engine should only be used directly
    # when compiling in-memory Sass code.
    # If you're compiling a single Sass file from the filesystem,
    # use \{Sass::Engine.for\_file}.
    # If you're compiling multiple files from the filesystem,
    # use {Sass::Plugin}.
    #
    # @param template [String] The Sass template.
    #   This template can be encoded using any encoding
    #   that can be converted to Unicode.
    #   If the template contains an `@charset` declaration,
    #   that overrides the Ruby encoding
    #   (see {file:SASS_REFERENCE.md#encodings the encoding documentation})
    # @param options [{Symbol => Object}] An options hash.
    #   See {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
    # @see {Sass::Engine.for_file}
    # @see {Sass::Plugin}
    def initialize(template, options={})
      @options = self.class.normalize_options(options)
      @template = template
    end

    # Render the template to CSS.
    #
    # @return [String] The CSS
    # @raise [Sass::SyntaxError] if there's an error in the document
    # @raise [Encoding::UndefinedConversionError] if the source encoding
    #   cannot be converted to UTF-8
    # @raise [ArgumentError] if the document uses an unknown encoding with `@charset`
    def render
      return _render unless @options[:quiet]
      Sass::Util.silence_sass_warnings {_render}
    end
    alias_method :to_css, :render

    # Parses the document into its parse tree. Memoized.
    #
    # @return [Sass::Tree::Node] The root of the parse tree.
    # @raise [Sass::SyntaxError] if there's an error in the document
    def to_tree
      @tree ||= @options[:quiet] ?
        Sass::Util.silence_sass_warnings {_to_tree} :
        _to_tree
    end

    # Returns the original encoding of the document,
    # or `nil` under Ruby 1.8.
    #
    # @return [Encoding, nil]
    # @raise [Encoding::UndefinedConversionError] if the source encoding
    #   cannot be converted to UTF-8
    # @raise [ArgumentError] if the document uses an unknown encoding with `@charset`
    def source_encoding
      check_encoding!
      @original_encoding
    end

    # Gets a set of all the documents
    # that are (transitive) dependencies of this document,
    # not including the document itself.
    #
    # @return [[Sass::Engine]] The dependency documents.
    def dependencies
      _dependencies(Set.new, engines = Set.new)
      Sass::Util.array_minus(engines, [self])
    end

    # Helper for \{#dependencies}.
    #
    # @private
    def _dependencies(seen, engines)
      return if seen.include?(key = [@options[:filename], @options[:importer]])
      seen << key
      engines << self
      to_tree.grep(Tree::ImportNode) do |n|
        next if n.css_import?
        n.imported_file._dependencies(seen, engines)
      end
    end

    private

    def _render
      rendered = _to_tree.render
      return rendered if ruby1_8?
      begin
        # Try to convert the result to the original encoding,
        # but if that doesn't work fall back on UTF-8
        rendered = rendered.encode(source_encoding)
      rescue EncodingError
      end
      rendered.gsub(Regexp.new('\A@charset "(.*?)"'.encode(source_encoding)),
        "@charset \"#{source_encoding.name}\"".encode(source_encoding))
    end

    def _to_tree
      if (@options[:cache] || @options[:read_cache]) &&
          @options[:filename] && @options[:importer]
        key = sassc_key
        sha = Digest::SHA1.hexdigest(@template)

        if root = @options[:cache_store].retrieve(key, sha)
          root.options = @options
          return root
        end
      end

      check_encoding!

      if @options[:syntax] == :scss
        root = Sass::SCSS::Parser.new(@template, @options[:filename]).parse
      else
        root = Tree::RootNode.new(@template)
        append_children(root, tree(tabulate(@template)).first, true)
      end

      root.options = @options
      if @options[:cache] && key && sha
        begin
          old_options = root.options
          root.options = {}
          @options[:cache_store].store(key, sha, root)
        ensure
          root.options = old_options
        end
      end
      root
    rescue SyntaxError => e
      e.modify_backtrace(:filename => @options[:filename], :line => @line)
      e.sass_template = @template
      raise e
    end

    def sassc_key
      @options[:cache_store].key(*@options[:importer].key(@options[:filename], @options))
    end

    def check_encoding!
      return if @checked_encoding
      @checked_encoding = true
      @template, @original_encoding = check_sass_encoding(@template) do |msg, line|
        raise Sass::SyntaxError.new(msg, :line => line)
      end
    end

    def tabulate(string)
      tab_str = nil
      comment_tab_str = nil
      first = true
      lines = []
      string.gsub(/\r\n|\r|\n/, "\n").scan(/^[^\n]*?$/).each_with_index do |line, index|
        index += (@options[:line] || 1)
        if line.strip.empty?
          lines.last.text << "\n" if lines.last && lines.last.comment?
          next
        end

        line_tab_str = line[/^\s*/]
        unless line_tab_str.empty?
          if tab_str.nil?
            comment_tab_str ||= line_tab_str
            next if try_comment(line, lines.last, "", comment_tab_str, index)
            comment_tab_str = nil
          end

          tab_str ||= line_tab_str

          raise SyntaxError.new("Indenting at the beginning of the document is illegal.",
            :line => index) if first

          raise SyntaxError.new("Indentation can't use both tabs and spaces.",
            :line => index) if tab_str.include?(?\s) && tab_str.include?(?\t)
        end
        first &&= !tab_str.nil?
        if tab_str.nil?
          lines << Line.new(line.strip, 0, index, 0, @options[:filename], [])
          next
        end

        comment_tab_str ||= line_tab_str
        if try_comment(line, lines.last, tab_str * lines.last.tabs, comment_tab_str, index)
          next
        else
          comment_tab_str = nil
        end

        line_tabs = line_tab_str.scan(tab_str).size
        if tab_str * line_tabs != line_tab_str
          message = <<END.strip.gsub("\n", ' ')
Inconsistent indentation: #{Sass::Shared.human_indentation line_tab_str, true} used for indentation,
but the rest of the document was indented using #{Sass::Shared.human_indentation tab_str}.
END
          raise SyntaxError.new(message, :line => index)
        end

        lines << Line.new(line.strip, line_tabs, index, tab_str.size, @options[:filename], [])
      end
      lines
    end

    def try_comment(line, last, tab_str, comment_tab_str, index)
      return unless last && last.comment?
      # Nested comment stuff must be at least one whitespace char deeper
      # than the normal indentation
      return unless line =~ /^#{tab_str}\s/
      unless line =~ /^(?:#{comment_tab_str})(.*)$/
        raise SyntaxError.new(<<MSG.strip.gsub("\n", " "), :line => index)
Inconsistent indentation:
previous line was indented by #{Sass::Shared.human_indentation comment_tab_str},
but this line was indented by #{Sass::Shared.human_indentation line[/^\s*/]}.
MSG
      end

      last.comment_tab_str ||= comment_tab_str
      last.text << "\n" << line
      true
    end

    def tree(arr, i = 0)
      return [], i if arr[i].nil?

      base = arr[i].tabs
      nodes = []
      while (line = arr[i]) && line.tabs >= base
        if line.tabs > base
          raise SyntaxError.new("The line was indented #{line.tabs - base} levels deeper than the previous line.",
            :line => line.index) if line.tabs > base + 1

          nodes.last.children, i = tree(arr, i)
        else
          nodes << line
          i += 1
        end
      end
      return nodes, i
    end

    def build_tree(parent, line, root = false)
      @line = line.index
      node_or_nodes = parse_line(parent, line, root)

      Array(node_or_nodes).each do |node|
        # Node is a symbol if it's non-outputting, like a variable assignment
        next unless node.is_a? Tree::Node

        node.line = line.index
        node.filename = line.filename

        append_children(node, line.children, false)
      end

      node_or_nodes
    end

    def append_children(parent, children, root)
      continued_rule = nil
      continued_comment = nil
      children.each do |line|
        child = build_tree(parent, line, root)

        if child.is_a?(Tree::RuleNode)
          if child.continued? && child.children.empty?
            if continued_rule
              continued_rule.add_rules child
            else
              continued_rule = child
            end
            next
          elsif continued_rule
            continued_rule.add_rules child
            continued_rule.children = child.children
            continued_rule, child = nil, continued_rule
          end
        elsif continued_rule
          continued_rule = nil
        end

        if child.is_a?(Tree::CommentNode) && child.type == :silent
          if continued_comment &&
              child.line == continued_comment.line +
              continued_comment.lines + 1
            continued_comment.value += ["\n"] + child.value
            next
          end

          continued_comment = child
        end

        check_for_no_children(child)
        validate_and_append_child(parent, child, line, root)
      end

      parent
    end

    def validate_and_append_child(parent, child, line, root)
      case child
      when Array
        child.each {|c| validate_and_append_child(parent, c, line, root)}
      when Tree::Node
        parent << child
      end
    end

    def check_for_no_children(node)
      return unless node.is_a?(Tree::RuleNode) && node.children.empty?
      Sass::Util.sass_warn(<<WARNING.strip)
WARNING on line #{node.line}#{" of #{node.filename}" if node.filename}:
This selector doesn't have any properties and will not be rendered.
WARNING
    end

    def parse_line(parent, line, root)
      case line.text[0]
      when PROPERTY_CHAR
        if line.text[1] == PROPERTY_CHAR ||
            (@options[:property_syntax] == :new &&
             line.text =~ PROPERTY_OLD && $2.empty?)
          # Support CSS3-style pseudo-elements,
          # which begin with ::,
          # as well as pseudo-classes
          # if we're using the new property syntax
          Tree::RuleNode.new(parse_interp(line.text))
        else
          name, value = line.text.scan(PROPERTY_OLD)[0]
          raise SyntaxError.new("Invalid property: \"#{line.text}\".",
            :line => @line) if name.nil? || value.nil?
          parse_property(name, parse_interp(name), value, :old, line)
        end
      when ?$
        parse_variable(line)
      when COMMENT_CHAR
        parse_comment(line)
      when DIRECTIVE_CHAR
        parse_directive(parent, line, root)
      when ESCAPE_CHAR
        Tree::RuleNode.new(parse_interp(line.text[1..-1]))
      when MIXIN_DEFINITION_CHAR
        parse_mixin_definition(line)
      when MIXIN_INCLUDE_CHAR
        if line.text[1].nil? || line.text[1] == ?\s
          Tree::RuleNode.new(parse_interp(line.text))
        else
          parse_mixin_include(line, root)
        end
      else
        parse_property_or_rule(line)
      end
    end

    def parse_property_or_rule(line)
      scanner = Sass::Util::MultibyteStringScanner.new(line.text)
      hack_char = scanner.scan(/[:\*\.]|\#(?!\{)/)
      parser = Sass::SCSS::Parser.new(scanner, @options[:filename], @line)

      unless res = parser.parse_interp_ident
        return Tree::RuleNode.new(parse_interp(line.text))
      end
      res.unshift(hack_char) if hack_char
      if comment = scanner.scan(Sass::SCSS::RX::COMMENT)
        res << comment
      end

      name = line.text[0...scanner.pos]
      if scanner.scan(/\s*:(?:\s|$)/)
        parse_property(name, res, scanner.rest, :new, line)
      else
        res.pop if comment
        Tree::RuleNode.new(res + parse_interp(scanner.rest))
      end
    end

    def parse_property(name, parsed_name, value, prop, line)
      if value.strip.empty?
        expr = Sass::Script::String.new("")
      else
        expr = parse_script(value, :offset => line.offset + line.text.index(value))
      end
      node = Tree::PropNode.new(parse_interp(name), expr, prop)
      if value.strip.empty? && line.children.empty?
        raise SyntaxError.new(
          "Invalid property: \"#{node.declaration}\" (no value)." +
          node.pseudo_class_selector_message)
      end

      node
    end

    def parse_variable(line)
      name, value, default = line.text.scan(Script::MATCH)[0]
      raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath variable declarations.",
        :line => @line + 1) unless line.children.empty?
      raise SyntaxError.new("Invalid variable: \"#{line.text}\".",
        :line => @line) unless name && value

      expr = parse_script(value, :offset => line.offset + line.text.index(value))

      Tree::VariableNode.new(name, expr, default)
    end

    def parse_comment(line)
      if line.text[1] == CSS_COMMENT_CHAR || line.text[1] == SASS_COMMENT_CHAR
        silent = line.text[1] == SASS_COMMENT_CHAR
        loud = !silent && line.text[2] == SASS_LOUD_COMMENT_CHAR
        if silent
          value = [line.text]
        else
          value = self.class.parse_interp(line.text, line.index, line.offset, :filename => @filename)
          value[0].slice!(2) if loud # get rid of the "!"
        end
        value = with_extracted_values(value) do |str|
          str = str.gsub(/^#{line.comment_tab_str}/m, '')[2..-1] # get rid of // or /*
          format_comment_text(str, silent)
        end
        type = if silent then :silent elsif loud then :loud else :normal end
        Tree::CommentNode.new(value, type)
      else
        Tree::RuleNode.new(parse_interp(line.text))
      end
    end

    def parse_directive(parent, line, root)
      directive, whitespace, value = line.text[1..-1].split(/(\s+)/, 2)
      offset = directive.size + whitespace.size + 1 if whitespace

      # If value begins with url( or ",
      # it's a CSS @import rule and we don't want to touch it.
      case directive
      when 'import'
        parse_import(line, value, offset)
      when 'mixin'
        parse_mixin_definition(line)
      when 'content'
        parse_content_directive(line)
      when 'include'
        parse_mixin_include(line, root)
      when 'function'
        parse_function(line, root)
      when 'for'
        parse_for(line, root, value)
      when 'each'
        parse_each(line, root, value)
      when 'else'
        parse_else(parent, line, value)
      when 'while'
        raise SyntaxError.new("Invalid while directive '@while': expected expression.") unless value
        Tree::WhileNode.new(parse_script(value, :offset => offset))
      when 'if'
        raise SyntaxError.new("Invalid if directive '@if': expected expression.") unless value
        Tree::IfNode.new(parse_script(value, :offset => offset))
      when 'debug'
        raise SyntaxError.new("Invalid debug directive '@debug': expected expression.") unless value
        raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath debug directives.",
          :line => @line + 1) unless line.children.empty?
        offset = line.offset + line.text.index(value).to_i
        Tree::DebugNode.new(parse_script(value, :offset => offset))
      when 'extend'
        raise SyntaxError.new("Invalid extend directive '@extend': expected expression.") unless value
        raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath extend directives.",
          :line => @line + 1) unless line.children.empty?
        optional = !!value.gsub!(/\s+#{Sass::SCSS::RX::OPTIONAL}$/, '')
        offset = line.offset + line.text.index(value).to_i
        Tree::ExtendNode.new(parse_interp(value, offset), optional)
      when 'warn'
        raise SyntaxError.new("Invalid warn directive '@warn': expected expression.") unless value
        raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath warn directives.",
          :line => @line + 1) unless line.children.empty?
        offset = line.offset + line.text.index(value).to_i
        Tree::WarnNode.new(parse_script(value, :offset => offset))
      when 'return'
        raise SyntaxError.new("Invalid @return: expected expression.") unless value
        raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath return directives.",
          :line => @line + 1) unless line.children.empty?
        offset = line.offset + line.text.index(value).to_i
        Tree::ReturnNode.new(parse_script(value, :offset => offset))
      when 'charset'
        name = value && value[/\A(["'])(.*)\1\Z/, 2] #"
        raise SyntaxError.new("Invalid charset directive '@charset': expected string.") unless name
        raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath charset directives.",
          :line => @line + 1) unless line.children.empty?
        Tree::CharsetNode.new(name)
      when 'media'
        parser = Sass::SCSS::Parser.new(value, @options[:filename], @line)
        Tree::MediaNode.new(parser.parse_media_query_list.to_a)
      else
        unprefixed_directive = directive.gsub(/^-[a-z0-9]+-/i, '')
        if unprefixed_directive == 'supports'
          parser = Sass::SCSS::Parser.new(value, @options[:filename], @line)
          return Tree::SupportsNode.new(directive, parser.parse_supports_condition)
        end

        Tree::DirectiveNode.new(
          value.nil? ? ["@#{directive}"] : ["@#{directive} "] + parse_interp(value, offset))
      end
    end

    def parse_for(line, root, text)
      var, from_expr, to_name, to_expr = text.scan(/^([^\s]+)\s+from\s+(.+)\s+(to|through)\s+(.+)$/).first

      if var.nil? # scan failed, try to figure out why for error message
        if text !~ /^[^\s]+/
          expected = "variable name"
        elsif text !~ /^[^\s]+\s+from\s+.+/
          expected = "'from <expr>'"
        else
          expected = "'to <expr>' or 'through <expr>'"
        end
        raise SyntaxError.new("Invalid for directive '@for #{text}': expected #{expected}.")
      end
      raise SyntaxError.new("Invalid variable \"#{var}\".") unless var =~ Script::VALIDATE

      var = var[1..-1]
      parsed_from = parse_script(from_expr, :offset => line.offset + line.text.index(from_expr))
      parsed_to = parse_script(to_expr, :offset => line.offset + line.text.index(to_expr))
      Tree::ForNode.new(var, parsed_from, parsed_to, to_name == 'to')
    end

    def parse_each(line, root, text)
      var, list_expr = text.scan(/^([^\s]+)\s+in\s+(.+)$/).first

      if var.nil? # scan failed, try to figure out why for error message
        if text !~ /^[^\s]+/
          expected = "variable name"
        elsif text !~ /^[^\s]+\s+from\s+.+/
          expected = "'in <expr>'"
        end
        raise SyntaxError.new("Invalid for directive '@each #{text}': expected #{expected}.")
      end
      raise SyntaxError.new("Invalid variable \"#{var}\".") unless var =~ Script::VALIDATE

      var = var[1..-1]
      parsed_list = parse_script(list_expr, :offset => line.offset + line.text.index(list_expr))
      Tree::EachNode.new(var, parsed_list)
    end

    def parse_else(parent, line, text)
      previous = parent.children.last
      raise SyntaxError.new("@else must come after @if.") unless previous.is_a?(Tree::IfNode)

      if text
        if text !~ /^if\s+(.+)/
          raise SyntaxError.new("Invalid else directive '@else #{text}': expected 'if <expr>'.")
        end
        expr = parse_script($1, :offset => line.offset + line.text.index($1))
      end

      node = Tree::IfNode.new(expr)
      append_children(node, line.children, false)
      previous.add_else node
      nil
    end

    def parse_import(line, value, offset)
      raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath import directives.",
        :line => @line + 1) unless line.children.empty?

      scanner = Sass::Util::MultibyteStringScanner.new(value)
      values = []

      loop do
        unless node = parse_import_arg(scanner, offset + scanner.pos)
          raise SyntaxError.new("Invalid @import: expected file to import, was #{scanner.rest.inspect}",
            :line => @line)
        end
        values << node
        break unless scanner.scan(/,\s*/)
      end

      if scanner.scan(/;/)
        raise SyntaxError.new("Invalid @import: expected end of line, was \";\".",
          :line => @line)
      end

      return values
    end

    def parse_import_arg(scanner, offset)
      return if scanner.eos?

      if scanner.match?(/url\(/i)
        script_parser = Sass::Script::Parser.new(scanner, @line, offset, @options)
        str = script_parser.parse_string
        media_parser = Sass::SCSS::Parser.new(scanner, @options[:filename], @line)
        media = media_parser.parse_media_query_list
        return Tree::CssImportNode.new(str, media.to_a)
      end

      unless str = scanner.scan(Sass::SCSS::RX::STRING)
        return Tree::ImportNode.new(scanner.scan(/[^,;]+/))
      end

      val = scanner[1] || scanner[2]
      scanner.scan(/\s*/)
      if !scanner.match?(/[,;]|$/)
        media_parser = Sass::SCSS::Parser.new(scanner, @options[:filename], @line)
        media = media_parser.parse_media_query_list
        Tree::CssImportNode.new(str || uri, media.to_a)
      elsif val =~ /^(https?:)?\/\//
        Tree::CssImportNode.new("url(#{val})")
      else
        Tree::ImportNode.new(val)
      end
    end

    MIXIN_DEF_RE = /^(?:=|@mixin)\s*(#{Sass::SCSS::RX::IDENT})(.*)$/
    def parse_mixin_definition(line)
      name, arg_string = line.text.scan(MIXIN_DEF_RE).first
      raise SyntaxError.new("Invalid mixin \"#{line.text[1..-1]}\".") if name.nil?

      offset = line.offset + line.text.size - arg_string.size
      args, splat = Script::Parser.new(arg_string.strip, @line, offset, @options).
        parse_mixin_definition_arglist
      Tree::MixinDefNode.new(name, args, splat)
    end

    CONTENT_RE = /^@content\s*(.+)?$/
    def parse_content_directive(line)
      trailing = line.text.scan(CONTENT_RE).first.first
      raise SyntaxError.new("Invalid content directive. Trailing characters found: \"#{trailing}\".") unless trailing.nil?
      raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath @content directives.",
        :line => line.index + 1) unless line.children.empty?
      Tree::ContentNode.new
    end

    MIXIN_INCLUDE_RE = /^(?:\+|@include)\s*(#{Sass::SCSS::RX::IDENT})(.*)$/
    def parse_mixin_include(line, root)
      name, arg_string = line.text.scan(MIXIN_INCLUDE_RE).first
      raise SyntaxError.new("Invalid mixin include \"#{line.text}\".") if name.nil?

      offset = line.offset + line.text.size - arg_string.size
      args, keywords, splat = Script::Parser.new(arg_string.strip, @line, offset, @options).
        parse_mixin_include_arglist
      Tree::MixinNode.new(name, args, keywords, splat)
    end

    FUNCTION_RE = /^@function\s*(#{Sass::SCSS::RX::IDENT})(.*)$/
    def parse_function(line, root)
      name, arg_string = line.text.scan(FUNCTION_RE).first
      raise SyntaxError.new("Invalid function definition \"#{line.text}\".") if name.nil?

      offset = line.offset + line.text.size - arg_string.size
      args, splat = Script::Parser.new(arg_string.strip, @line, offset, @options).
        parse_function_definition_arglist
      Tree::FunctionNode.new(name, args, splat)
    end

    def parse_script(script, options = {})
      line = options[:line] || @line
      offset = options[:offset] || 0
      Script.parse(script, line, offset, @options)
    end

    def format_comment_text(text, silent)
      content = text.split("\n")

      if content.first && content.first.strip.empty?
        removed_first = true
        content.shift
      end

      return silent ? "//" : "/* */" if content.empty?
      content.last.gsub!(%r{ ?\*/ *$}, '')
      content.map! {|l| l.gsub!(/^\*( ?)/, '\1') || (l.empty? ? "" : " ") + l}
      content.first.gsub!(/^ /, '') unless removed_first
      if silent
        "//" + content.join("\n//")
      else
        # The #gsub fixes the case of a trailing */
        "/*" + content.join("\n *").gsub(/ \*\Z/, '') + " */"
      end
    end

    def parse_interp(text, offset = 0)
      self.class.parse_interp(text, @line, offset, :filename => @filename)
    end

    # It's important that this have strings (at least)
    # at the beginning, the end, and between each Script::Node.
    #
    # @private
    def self.parse_interp(text, line, offset, options)
      res = []
      rest = Sass::Shared.handle_interpolation text do |scan|
        escapes = scan[2].size
        res << scan.matched[0...-2 - escapes]
        if escapes % 2 == 1
          res << "\\" * (escapes - 1) << '#{'
        else
          res << "\\" * [0, escapes - 1].max
          res << Script::Parser.new(
            scan, line, offset + scan.pos - scan.matched_size, options).
            parse_interpolated
        end
      end
      res << rest
    end
  end
end


text:
package com.intellij.codeInspection.reference;

import com.intellij.psi.PsiElement;

/**
 * Callback which gets called while a reference graph is being built during a global
 * inspection run.
 *
 * @author anna
 * @since 6.0
 * @see com.intellij.codeInspection.GlobalInspectionTool#getAnnotator
 */
public abstract class RefGraphAnnotator {
  /**
   * Called before the references to the specified element have been collected.
   *
   * @param refElement the element the references to which are about to be collected.
   */
  public void onInitialize(RefElement refElement) {
  }

  /**
   * Called after the references to the specified element have been collected.
   *
   * @param refElement the element the references to which have been collected.
   */
  public void onReferencesBuild(RefElement refElement){
  }

  /**
   * Called when a reference to the specified element has been found.
   *
   * @param refWhat                        the referenced element.
   * @param refFrom                        the referencing element.
   * @param referencedFromClassInitializer if true, {@code refFrom} is a class and the reference
   *                                       has been found in its initializer block.
   */
  public void onMarkReferenced(RefElement refWhat,
                               RefElement refFrom,
                               boolean referencedFromClassInitializer) {
  }

  /**
   * Called when a reference to the specified element has been found.
   *
   * @param refWhat                        the referenced element.
   * @param refFrom                        the referencing element.
   * @param referencedFromClassInitializer if true, {@code refFrom} is a class and the reference
   *                                       has been found in its initializer block.
   * @param forReading                     used for reading
   * @param forWriting                     used for writing
   */
  public void onMarkReferenced(RefElement refWhat,
                               RefElement refFrom,
                               boolean referencedFromClassInitializer,
                               boolean forReading,
                               boolean forWriting) {
    onMarkReferenced(refWhat, refFrom, referencedFromClassInitializer);
  }

  /**
   * Called when 'what' element doesn't belong to the selected scope.
   * @param what                            the referenced element
   * @param from                            the referencing element
   * @param referencedFromClassInitializer if true, {@code refFrom} is a class and the reference
   *                                       has been found in its initializer block.
   */
  public void onMarkReferenced(PsiElement what,
                               PsiElement from,
                               boolean referencedFromClassInitializer) {}

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Language" content="en-gb">

<title>WHEN</title>

When some condition is true I add new
micro-behaviours and remove old ones.

	Begin micro-behaviour

WHEN

	Begin NetLogo code:

substitute-text-area-for condition true
when [condition]
  [add-behaviours
     list-of-micro-behaviours "Behaviours to add" []]

	End NetLogo code
Variants

Edit the condition (true) to the desired condition. Add micro-behaviours
	to the lists of behaviours to add when the condition is true.

Related Micro-behaviours

ADD-BEHAVIOURS -- Adds behaviours

ADD-BEHAVIOURS-TO -- Adds behaviours
immediately to a specified agent or set of agents

	ADD-BEHAVIOURS-TO-LINKS -- Adds
	micro-behaviours to links (rather than agents)

REMOVE-BEHAVIOURS -- Removes
	behaviours

REMOVE-BEHAVIOURS-FROM -- Removes
	specified behaviours from an agent or set of agents

REMOVE-ALL-BEHAVIOURS
-- Remove all behaviours

REMOVE-ALL-BEHAVIOURS-FROM -- Removes
	all behaviours from an agent or set of agents

DO-WITH-PROBABILITY -- Adds
	behaviours probabilistically

REPEATEDLY-DO-BEHAVIOURS --
	Adds behaviours repeatedly

DO-AFTER -- Delays the addition of a list of
	micro-behaviours

DO-AFTER-SETUP -- Delays the addition of a list of
micro-behaviours until setup has completed

DO-IF -- Runs actions if condition is true

DO-IF-ELSE -- Runs one set of actions if
condition is true and another set if condition is false

WHEN -- Adds and removes micro-behaviours the first
time that conditions are true

WHENEVER -- Adds and removes micro-behaviours
every time conditions are true

How this works

when is a construct added to NetLogo that is checked each time the
scheduler advanced the time and if true executes the actions once.

History

This was implemented by Ken Kahn.


text:
module MoneyTracking
  module Domain
    class ExpenseFactory < Struct.new(:store)
      def create(raw_expense)
        build(raw_expense).create
      end

      def build(raw_expense, id = nil)
        return ExpenseNotFound.new unless raw_expense
        return build(raw_expense.merge(id: id)) if id
        Expense.new(store, raw_expense)
      end
    end
  end
end


text:
package com.twitter.scalding.platform

import com.twitter.scalding._

import org.scalatest.{ Matchers, WordSpec }

class InAndOutJob(args: Args) extends Job(args) {
  Tsv("input").read.write(Tsv("output"))
}

object TinyJoinAndMergeJob {
  val peopleInput = TypedTsv[Int]("input1")
  val peopleData = List(1, 2, 3, 4)

  val messageInput = TypedTsv[Int]("input2")
  val messageData = List(1, 2, 3)

  val output = TypedTsv[(Int, Int)]("output")
  val outputData = List((1, 2), (2, 2), (3, 2), (4, 1))
}

class TinyJoinAndMergeJob(args: Args) extends Job(args) {
  import TinyJoinAndMergeJob._

  val people = peopleInput.read.mapTo(0 -> 'id) { v: Int => v }

  val messages = messageInput.read
    .mapTo(0 -> 'id) { v: Int => v }
    .joinWithTiny('id -> 'id, people)

  (messages ++ people).groupBy('id) { _.size('count) }.write(output)
}

object TsvNoCacheJob {
  val dataInput = TypedTsv[String]("fakeInput")
  val data = List("-0.2f -0.3f -0.5f", "-0.1f", "-0.5f")

  val throwAwayOutput = Tsv("output1")
  val typedThrowAwayOutput = TypedTsv[Float]("output1")
  val realOuput = Tsv("output2")
  val typedRealOutput = TypedTsv[Float]("output2")
  val outputData = List(-0.5f, -0.2f, -0.3f, -0.1f).sorted
}
class TsvNoCacheJob(args: Args) extends Job(args) {
  import TsvNoCacheJob._
  dataInput.read
    .flatMap(new cascading.tuple.Fields(Integer.valueOf(0)) -> 'word){ line: String => line.split("\\s") }
    .groupBy('word){ group => group.size }
    .mapTo('word -> 'num) { (w: String) => w.toFloat }
    .write(throwAwayOutput)
    .groupAll { _.sortBy('num) }
    .write(realOuput)
}

// Keeping all of the specifications in the same tests puts the result output all together at the end.
// This is useful given that the Hadoop MiniMRCluster and MiniDFSCluster spew a ton of logging.
class PlatformTests extends WordSpec with Matchers with HadoopSharedPlatformTest {
  org.apache.log4j.Logger.getLogger("org.apache.hadoop").setLevel(org.apache.log4j.Level.ERROR)
  org.apache.log4j.Logger.getLogger("org.mortbay").setLevel(org.apache.log4j.Level.ERROR)

  "An InAndOutTest" should {
    val inAndOut = Seq("a", "b", "c")

    "reading then writing shouldn't change the data" in {
      HadoopPlatformJobTest(new InAndOutJob(_), cluster)
        .source("input", inAndOut)
        .sink[String]("output") { _.toSet shouldBe (inAndOut.toSet) }
        .run
    }
  }

  "A TinyJoinAndMergeJob" should {
    import TinyJoinAndMergeJob._

    "merge and joinWithTiny shouldn't duplicate data" in {
      HadoopPlatformJobTest(new TinyJoinAndMergeJob(_), cluster)
        .source(peopleInput, peopleData)
        .source(messageInput, messageData)
        .sink(output) { _.toSet shouldBe (outputData.toSet) }
        .run
    }
  }

  "A TsvNoCacheJob" should {
    import TsvNoCacheJob._

    "Writing to a tsv in a flow shouldn't effect the output" in {
      HadoopPlatformJobTest(new TsvNoCacheJob(_), cluster)
        .source(dataInput, data)
        .sink(typedThrowAwayOutput) { _.toSet should have size 4 }
        .sink(typedRealOutput) { _.map{ f: Float => (f * 10).toInt }.toList shouldBe (outputData.map{ f: Float => (f * 10).toInt }.toList) }
        .run
    }
  }
}

object IterableSourceDistinctJob {
  val data = List("a", "b", "c")
}

class IterableSourceDistinctJob(args: Args) extends Job(args) {
  import IterableSourceDistinctJob._

  TypedPipe.from(data ++ data ++ data).distinct.write(TypedTsv("output"))
}

class IterableSourceDistinctIdentityJob(args: Args) extends Job(args) {
  import IterableSourceDistinctJob._

  TypedPipe.from(data ++ data ++ data).distinctBy(identity).write(TypedTsv("output"))
}

class NormalDistinctJob(args: Args) extends Job(args) {
  TypedPipe.from(TypedTsv[String]("input")).distinct.write(TypedTsv("output"))
}

class IterableSourceDistinctTest extends WordSpec with Matchers with HadoopPlatformTest {
  "A IterableSource" should {
    import IterableSourceDistinctJob._

    "distinct properly from normal data" in {
      HadoopPlatformJobTest(new NormalDistinctJob(_), cluster)
        .source[String]("input", data ++ data ++ data)
        .sink[String]("output") { _.toList shouldBe data }
        .run
    }

    "distinctBy(identity) properly from a list in memory" in {
      HadoopPlatformJobTest(new IterableSourceDistinctIdentityJob(_), cluster)
        .sink[String]("output") { _.toList shouldBe data }
        .run
    }

    "distinct properly from a list" in {
      HadoopPlatformJobTest(new IterableSourceDistinctJob(_), cluster)
        .sink[String]("output") { _.toList shouldBe data }
        .run
    }
  }
}

object MultipleGroupByJobData {
  val data: List[String] = {
    val rnd = new scala.util.Random(22)
    (0 until 20).map { _ => rnd.nextLong.toString }.toList
  }.distinct
}

class MultipleGroupByJob(args: Args) extends Job(args) {
  import com.twitter.scalding.serialization._
  import MultipleGroupByJobData._
  implicit val stringOrdSer = new StringOrderedSerialization()
  implicit val stringTup2OrdSer = new OrderedSerialization2(stringOrdSer, stringOrdSer)
  val otherStream = TypedPipe.from(data).map{ k => (k, k) }.group

  TypedPipe.from(data)
    .map{ k => (k, 1L) }
    .group[String, Long](implicitly, stringOrdSer)
    .sum
    .map {
      case (k, _) =>
        ((k, k), 1L)
    }
    .sumByKey[(String, String), Long](implicitly, stringTup2OrdSer, implicitly)
    .map(_._1._1)
    .map { t =>
      (t.toString, t)
    }
    .group
    .leftJoin(otherStream)
    .map(_._1)
    .write(TypedTsv("output"))

}

class MultipleGroupByJobTest extends WordSpec with Matchers with HadoopPlatformTest {
  "A grouped job" should {
    import MultipleGroupByJobData._

    "do some ops and not stamp on each other ordered serializations" in {
      HadoopPlatformJobTest(new MultipleGroupByJob(_), cluster)
        .source[String]("input", data)
        .sink[String]("output") { _.toSet shouldBe data.map(_.toString).toSet }
        .run
    }

  }
}


text:
package io.airlift.sample;

import io.airlift.event.client.NullEventClient;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import javax.ws.rs.core.Response;

import java.util.Collection;

import static com.google.common.collect.Lists.newArrayList;
import static io.airlift.testing.Assertions.assertInstanceOf;
import static org.testng.Assert.assertEquals;

@Test(singleThreaded = true)
public class TestPersonsResource
{
    private PersonsResource resource;
    private PersonStore store;

    @BeforeMethod
    public void setup()
    {
        store = new PersonStore(new StoreConfig(), new NullEventClient());
        resource = new PersonsResource(store);
    }

    @Test
    public void testEmpty()
    {
        Response response = resource.listAll();
        assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
        assertInstanceOf(response.getEntity(), Collection.class);
        assertEquals((Collection<?>) response.getEntity(), newArrayList());
    }

    @Test
    public void testListAll()
    {
        store.put("foo", new Person("foo@example.com", "Mr Foo"));
        store.put("bar", new Person("bar@example.com", "Mr Bar"));

        Response response = resource.listAll();
        assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
        assertInstanceOf(response.getEntity(), Collection.class);
        assertEquals((Collection<?>) response.getEntity(), newArrayList(
                new PersonRepresentation("foo@example.com", "Mr Foo", null),
                new PersonRepresentation("bar@example.com", "Mr Bar", null)
        ));
    }

}


text:
using System;
using System.Text.RegularExpressions;

namespace Lab5
{
    public class PhoneNumber
    {
        private string number;

        public PhoneNumber()
        {
            this.number = string.Empty;
        }
        public PhoneNumber(string number)
        {
            if (!IsPhoneNumber(number))
            {
                throw new InvalidPhoneNumberException("Phone number is invalid!");
            }
            this.number = number;
        }

        public static bool IsNullOrEmpty(PhoneNumber value)
        {
            if (value == null)
            {
                return true;
            }

            if (value.number == string.Empty)
            {
                return true;
            }

            return false;
        }
        public override string ToString()
        {
            return "(" + this.number.Substring(0, 3) + ") "
                + this.number.Substring(3, 3) + "-" + this.number.Substring(6, 2) + "-" + this.number.Substring(8, 2);
        }

        public string Number
        {
            get => this.number;
            set
            {
                if (!PhoneNumber.IsPhoneNumber(value))
                {
                    throw new InvalidPhoneNumberException("Phone number is invalid!");
                }
                this.number = value;
            }
        }

        static public bool IsPhoneNumber(string number)
        {
            if (number == null)
            {
                return false;
            }

            var phoneMask = new Regex("[^0-9]");

            if (phoneMask.IsMatch(number) || number.Length != 10)
            {
                return false;
            }

            return true;
        }
        public bool CheckNumberByCode(string code)
        {
            if (!(new Regex(@"\d{3}").IsMatch(code)) || code.Length != 3)
            {
                throw new Exception("Invalid phone template format!");
            }

            if (this.number.Substring(0, code.Length) != code)
            {
                return false;
            }

            return true;
        }
    }
}


text:
module ActiveModel
  class Serializer
    VERSION = '0.9.0.alpha1'
  end
end


text:
> Collects anonymous nodejs module version upgrade statistics

[![NPM][next-update-stats-icon] ][next-update-stats-url]

[![Build status][next-update-stats-ci-image] ][next-update-stats-ci-url]
[![dependencies][next-update-stats-dependencies-image] ][next-update-stats-dependencies-url]
[![devdependencies][next-update-stats-devdependencies-image] ][next-update-stats-devdependencies-url]
[![Circle CI](https://circleci.com/gh/bahmutov/next-update-stats.svg?style=svg) ](https://circleci.com/gh/bahmutov/next-update-stats)

[next-update-stats-icon]: https://nodei.co/npm/next-update-stats.png?downloads=true
[next-update-stats-url]: https://npmjs.org/package/next-update-stats
[next-update-stats-ci-image]: https://travis-ci.org/bahmutov/next-update-stats.png?branch=master
[next-update-stats-ci-url]: https://travis-ci.org/bahmutov/next-update-stats
[next-update-stats-dependencies-image]: https://david-dm.org/bahmutov/next-update-stats.png
[next-update-stats-dependencies-url]: https://david-dm.org/bahmutov/next-update-stats
[next-update-stats-devdependencies-image]: https://david-dm.org/bahmutov/next-update-stats/dev-status.png
[next-update-stats-devdependencies-url]: https://david-dm.org/bahmutov/next-update-stats#info=devDependencies

Small server keeping package upgrade version statistics to be used
as stand alone information, or with automatic update tool
[next-update](https://github.com/bahmutov/next-update)

In essense it keeps anonymous stats when upgrading public packages:

> Upgrading [lodash](https://npmjs.org/package/lodash)
from 1.0.0 to 2.0.0 breaks 200 times, is successful 300 times.

Allows you to judge how likely a successful update for your
project would be. When looking at the entire NPM universe,
only 25% of modules have working unit tests
(see [http://npmt.abru.pt/](http://npmt.abru.pt/)), and the rest
either have no tests, or failing ones. This project tries to
increase this number by making unit tests highly useful.

### Small print

Author: Gleb Bahmutov © 2014

* [@bahmutov](https://twitter.com/bahmutov)
* [glebbahmutov.com](http://glebbahmutov.com)
* [blog](http://glebbahmutov.com/blog/)

License: MIT - do anything with the code, but don't blame me if it does not work.

Spread the word: tweet, star on github, etc.

Support: if you find any problems with this module, email / tweet /
[open issue](https://github.com/bahmutov/next-update-stats/issues) on Github

## MIT License

Copyright (c) 2013 Gleb Bahmutov

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.


text:
'use strict';

/**
 * Controller for Entrytype
 **/
entrytypeModule.controller('EntrytypeCtrl', ['Entrytype',  '$scope', '$routeParams', '$http', '$location', '$cookies', 'MessageHandler', 'restURL', function(Entrytype, $scope, $routeParams, $http, $location, $cookies, MessageHandler, restURL) {
	    // edition mode
    $scope.mode = null;

	// list of entrytypes
    $scope.entrytypes = [];
	// entrytype to edit
    $scope.entrytype = null;

	// referencies entities
	$scope.items = {};

    /**
     * Load all referencies entities
     */
	$scope.loadAllReferencies = function() {
    };

    /**
     * Refresh entrytypes list
     */
    $scope.refreshEntrytypeList = function() {
    	try {
			$scope.entrytypes = [];
        	Entrytype.getAll().then(
				function(success) {
        	        $scope.entrytypes = success.data;
            	},
	            MessageHandler.manageError);
    	} catch(ex) {
    		MessageHandler.manageException(ex);
    	}
    }
    /**
     * Refresh entrytype
     */
    $scope.refreshEntrytype = function(id) {
    	try {
        	$scope.entrytype = null;
	        Entrytype.get(id).then(
				function(success) {
        	        $scope.entrytype = success.data;
            	},
	            MessageHandler.manageError);
    	  } catch(ex) {
        	MessageHandler.manageException(ex);
    	}
    }

    /**
     * Go to the entrytypes list page
     */
    $scope.goToEntrytypeList = function() {
        $scope.refreshEntrytypeList();
        $location.path('/entrytype');
    }
    /**
     * Go to the entrytype edit page
     */
    $scope.goToEntrytype = function(id) {
        $scope.refreshEntrytype(id);
        $location.path('/entrytype/'+id);
    }

    // Actions

    /**
     * Save entrytype
     */
    $scope.save = function() {
    	try {
			MessageHandler.cleanMessage();
			var save;
			if( $scope.mode === 'create' ) {
        		save = Entrytype.create;
			} else {
				save = Entrytype.update;
			}
			save($scope.entrytype).then(
    	        function(success) {
	                MessageHandler.addSuccess('save ok');
                	$scope.entrytype = success.data;
            	},
        	    MessageHandler.manageError);
    	} catch(ex) {
        	MessageHandler.manageException(ex);
    	}
    };
    /**
     * Delete entrytype
     */
    $scope.delete = function(id) {
	    try {
			MessageHandler.cleanMessage();
    	    Entrytype.delete(id).then(
				function(success) {
                	$scope.goToEntrytypeList();
            	},
                MessageHandler.manageError);
        } catch(ex) {
            MessageHandler.manageException(ex);
        }
    };

    // Main
	MessageHandler.cleanMessage();
    if( $location.path().endsWith('/new') ) {
        // Creation page
        $scope.entrytype = {};
        $scope.mode = 'create';
		$scope.loadAllReferencies();
        $scope.bookorderitem = null;
    } else if( $routeParams.id != null ) {
        // Edit page
		$scope.loadAllReferencies();
		$scope.refreshEntrytype($routeParams.id);
    } else {
        // List page
        $scope.refreshEntrytypeList();
    }

}]);