example from http://perf4j.codehaus.org/devguide.html
505903
private static void method() {
//		StopWatch stopWatch = new LoggingStopWatch();
		Split split = SimonManager.getStopwatch("codeBlock2").start();

		try {
			// the code block being timed - this is just a dummy example
			long sleepTime = (long) (Math.random() * 1000L);
			Thread.sleep(sleepTime);
			if (sleepTime > 500L) {
				throw new Exception("Throwing exception");
			}

			split.stop("success");
//			stopWatch.stop("codeBlock2.success", "Sleep time was < 500 ms");
		} catch (Exception e) {
			split.stop("failure");
//			stopWatch.stop("codeBlock2.failure", "Exception was: " + e);
		}
	}
563216
function buildElementTag( def, code, varName ) {
    const attribs = extractAttribs( def );

    try {
        const arr = Object.keys( attribs.standard );
        code.requires[ "Tag" ] = "require('tfw.view').Tag";
        code.section.elements.define.push(
            "const " + varName + " = new Tag('" + def[ 0 ] + "'" +
            ( arr.length > 0 ? ', ' + JSON.stringify( arr ) : '' ) +
            ");" );

        const initAttribs = buildElementTagAttribsStandard( attribs.standard, code, varName );
        buildInitAttribsForTag( initAttribs, code, varName );
        buildElementEvents( attribs.special, code, varName );
        buildElementTagClassSwitcher( attribs.special, code, varName );
        buildElementTagAttribSwitcher( attribs.special, code, varName );
        buildElementTagStyle( attribs.special, code, varName );
        buildElementTagChildren( attribs.special, code, varName );
        buildElementTagOn( attribs.special, code, varName );
    } catch ( ex ) {
        throw ex + "\n...in tag \"" + varName + "\": " + limitJson( def );
    }
}
343544
function(page) {
            // Get all code texts
            umls = page.content.match(/```(uml|puml|plantuml)((.*[\r\n]+)+?)?```/igm);
            // Begin replace
            if (umls instanceof Array) {
                for (var i = 0, len = umls.length; i < len; i++) {
                    page.content = page.content.replace(
                        umls[i],
                        // Parameter parser for user argument to gitbook argument
                        umls[i].replace(/```(uml|puml|plantuml)[ \t]+{(.*)}/i,
                            function(match, p1, p2) {
                                var newStr = "";
                                var modeQuote = false;
                                var modeArray = false;
                                var modeChar = false;
                                var modeEqual = false;
                                // Trim left and right space
                                var str = p2.replace(/^\s+|\s+$/g,"");

                                // Build new str
                                for(var i = 0; i < str.length; i++){
                                    if (str.charAt(i) == "\"") {
                                        modeQuote = !modeQuote;
                                        modeChar = true;
                                        newStr += str.charAt(i);
                                        continue;
                                    }
                                    if (str.charAt(i) == "[") {
                                        modeArray = true;
                                        newStr += str.charAt(i);
                                        continue;
                                    }
                                    if (str.charAt(i) == "]") {
                                        modeArray = false;
                                        newStr += str.charAt(i);
                                        continue;
                                    }
                                    if (modeQuote || modeArray) {
                                        // In quote, keep all string
                                        newStr += str.charAt(i);
                                    } else {
                                        // Out of quote, process it
                                        if (str.charAt(i).match(/[A-Za-z0-9_]/)) {
                                            modeChar = true;
                                            newStr += str.charAt(i);
                                        } else if (str.charAt(i).match(/[=]/)) {
                                            modeEqual = true;
                                            modeChar = false;
                                            newStr += str.charAt(i);
                                        } else if (modeChar && modeEqual) {
                                            modeChar = false;
                                            modeEqual = false;
                                            newStr += ",";
                                        }
                                    }
                                }

                                newStr = newStr.replace(/,$/,"");

                                return "{% uml " + newStr + " %}";
                            })
                        .replace(/```(uml|puml|plantuml)/i, '{% uml %}')
                        .replace(/```/, '{% enduml %}'));
                }
            }
            return page;
        }
696397
@SuppressWarnings("checkstyle:all")
	protected StringConcatenationClient generateMembers(boolean forInterface, boolean forAppender) {
		final CodeElementExtractor.ElementDescription parameter = getCodeElementExtractor().getTypeParameter();
		return new StringConcatenationClient() {
			@Override
			protected void appendTo(TargetStringConcatenation it) {
				if (!forInterface && !forAppender) {
					it.append("\tprivate "); //$NON-NLS-1$
					it.append(EObject.class);
					it.append(" context;"); //$NON-NLS-1$
					it.newLineIfNotEmpty();
					it.newLine();
					it.append("\tprivate "); //$NON-NLS-1$
					it.append(parameter.getElementType());
					it.append(" parameter;"); //$NON-NLS-1$
					it.newLineIfNotEmpty();
					it.newLine();
					it.append("\t@"); //$NON-NLS-1$
					it.append(Inject.class);
					it.newLine();
					it.append("\t\tprivate "); //$NON-NLS-1$
					it.append(TypesFactory.class);
					it.append(" jvmTypesFactory;"); //$NON-NLS-1$
					it.newLineIfNotEmpty();
					it.newLine();
				} else {
					it.append("\t/** Find the reference to the type with the given name."); //$NON-NLS-1$
					it.newLine();
					it.append("\t * @param typeName the fully qualified name of the type"); //$NON-NLS-1$
					it.newLine();
					it.append("\t * @return the type reference."); //$NON-NLS-1$
					it.newLine();
					it.append("\t */"); //$NON-NLS-1$
					it.newLine();
					it.append("\t"); //$NON-NLS-1$
					if (!forInterface) {
						it.append("public "); //$NON-NLS-1$
					}
					it.append(JvmParameterizedTypeReference.class);
					it.append(" newTypeRef(String typeName)"); //$NON-NLS-1$
					if (forInterface) {
						it.append(";"); //$NON-NLS-1$
					} else {
						it.append(" {"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\treturn this.builder.newTypeRef(typeName);"); //$NON-NLS-1$
						it.newLine();
						it.append("\t}"); //$NON-NLS-1$
					}
					it.newLineIfNotEmpty();
					it.newLine();
					it.append("\t/** Find the reference to the type with the given name."); //$NON-NLS-1$
					it.newLine();
					it.append("\t * @param context the context for the type reference use"); //$NON-NLS-1$
					it.newLine();
					it.append("\t * @param typeName the fully qualified name of the type"); //$NON-NLS-1$
					it.newLine();
					it.append("\t * @return the type reference."); //$NON-NLS-1$
					it.newLine();
					it.append("\t */"); //$NON-NLS-1$
					it.newLine();
					it.append("\t"); //$NON-NLS-1$
					if (!forInterface) {
						it.append("public "); //$NON-NLS-1$
					}
					it.append(JvmParameterizedTypeReference.class);
					it.append(" newTypeRef("); //$NON-NLS-1$
					it.append(Notifier.class);
					it.append(" context, String typeName)"); //$NON-NLS-1$
					if (forInterface) {
						it.append(";"); //$NON-NLS-1$
					} else {
						it.append(" {"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\treturn this.builder.newTypeRef(context, typeName);"); //$NON-NLS-1$
						it.newLine();
						it.append("\t}"); //$NON-NLS-1$
					}
					it.newLineIfNotEmpty();
					it.newLine();
				}

				it.append("\t/** Initialize the type parameter."); //$NON-NLS-1$
				it.newLine();
				it.append("\t * <p>Caution: This initialization function does not add the type parameter in its container."); //$NON-NLS-1$
				it.newLine();
				it.append("\t * The container is responsible of adding the type parameter in its internal object."); //$NON-NLS-1$
				it.newLine();
				it.append("\t * @param name the name of the type parameter."); //$NON-NLS-1$
				it.newLine();
				it.append("\t * @param typeContext the provider of types or null."); //$NON-NLS-1$
				it.newLine();
				it.append("\t */"); //$NON-NLS-1$
				it.newLine();
				it.append("\t"); //$NON-NLS-1$
				if (!forInterface) {
					it.append("public "); //$NON-NLS-1$
				}
				it.append("void eInit("); //$NON-NLS-1$
				it.append(EObject.class);
				it.append(" context, String name, "); //$NON-NLS-1$
				it.append(IJvmTypeProvider.class);
				it.append(" typeContext)"); //$NON-NLS-1$
				if (forInterface) {
					it.append(";"); //$NON-NLS-1$
				} else {
					it.append(" {"); //$NON-NLS-1$
					it.newLine();
					if (forAppender) {
						it.append("\t\tthis.builder.eInit(context, name, typeContext);"); //$NON-NLS-1$
					} else {
						it.append("\t\tsetTypeResolutionContext(typeContext);"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\tthis.context = context;"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\tthis.parameter = this.jvmTypesFactory.create"); //$NON-NLS-1$
						it.append(Strings.toFirstUpper(parameter.getElementType().getSimpleName()));
						it.append("();"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\tthis.parameter.set"); //$NON-NLS-1$
						it.append(Strings.toFirstUpper(getCodeBuilderConfig().getParameterNameGrammarName()));
						it.append("(name);"); //$NON-NLS-1$
						it.newLine();
					}
					it.newLine();
					it.append("\t}"); //$NON-NLS-1$
				}
				it.newLineIfNotEmpty();
				it.newLine();
				if (forInterface) {
					it.append("\t/** Replies the context for type resolution."); //$NON-NLS-1$
					it.newLine();
					it.append("\t * @return the context or <code>null</code> if the Ecore object is the context."); //$NON-NLS-1$
					it.newLine();
					it.append("\t */"); //$NON-NLS-1$
					it.newLine();
					it.append("\t"); //$NON-NLS-1$
					it.append(IJvmTypeProvider.class);
					it.append(" getTypeResolutionContext();"); //$NON-NLS-1$
					it.newLineIfNotEmpty();
					it.newLine();
				} else if (forAppender) {
					it.append("\tpublic "); //$NON-NLS-1$
					it.append(IJvmTypeProvider.class);
					it.append(" getTypeResolutionContext() {"); //$NON-NLS-1$
					it.newLine();
					it.append("\t\treturn this.builder.getTypeResolutionContext();"); //$NON-NLS-1$
					it.newLine();
					it.append("\t}"); //$NON-NLS-1$
					it.newLineIfNotEmpty();
					it.newLine();
				}
				it.append("\t/** Replies the created parameter."); //$NON-NLS-1$
				it.newLine();
				it.append("\t *"); //$NON-NLS-1$
				it.newLine();
				it.append("\t * @return the parameter."); //$NON-NLS-1$
				it.newLine();
				it.append("\t */"); //$NON-NLS-1$
				it.newLine();
				it.append("\t@"); //$NON-NLS-1$
				it.append(Pure.class);
				it.newLine();
				it.append("\t"); //$NON-NLS-1$
				if (!forInterface) {
					it.append("public "); //$NON-NLS-1$
				}
				it.append(parameter.getElementType());
				it.append(" get"); //$NON-NLS-1$
				it.append(Strings.toFirstUpper(parameter.getElementType().getSimpleName()));
				it.append("()"); //$NON-NLS-1$
				if (forInterface) {
					it.append(";"); //$NON-NLS-1$
				} else {
					it.append(" {"); //$NON-NLS-1$
					it.newLine();
					if (forAppender) {
						it.append("\t\treturn this.builder.get"); //$NON-NLS-1$
						it.append(Strings.toFirstUpper(parameter.getElementType().getSimpleName()));
						it.append("();"); //$NON-NLS-1$
					} else {
						it.append("\t\treturn this.parameter;"); //$NON-NLS-1$
					}
					it.newLine();
					it.append("\t}"); //$NON-NLS-1$
				}
				it.newLineIfNotEmpty();
				it.newLine();
				it.append("\t/** Replies the resource to which the type parameter is attached."); //$NON-NLS-1$
				it.newLine();
				it.append("\t */"); //$NON-NLS-1$
				it.newLine();
				it.append("\t@"); //$NON-NLS-1$
				it.append(Pure.class);
				it.newLine();
				it.append("\t"); //$NON-NLS-1$
				if (!forInterface) {
					it.append("public "); //$NON-NLS-1$
				}
				it.append(Resource.class);
				it.append(" eResource()"); //$NON-NLS-1$
				if (forInterface) {
					it.append(";"); //$NON-NLS-1$
				} else {
					it.append(" {"); //$NON-NLS-1$
					it.newLine();
					it.append("\t\treturn get"); //$NON-NLS-1$
					it.append(Strings.toFirstUpper(parameter.getElementType().getSimpleName()));
					it.append("().eResource();"); //$NON-NLS-1$
					it.newLine();
					it.append("\t}"); //$NON-NLS-1$
				}
				it.newLineIfNotEmpty();
				it.newLine();
				if (!forAppender && !forInterface) {
					it.append("\t@"); //$NON-NLS-1$
					it.append(Override.class);
					it.newLine();
					it.append("\t@"); //$NON-NLS-1$
					it.append(Pure.class);
					it.newLine();
					it.append("\tpublic "); //$NON-NLS-1$
					it.append(String.class);
					it.append(" toString() {"); //$NON-NLS-1$
					it.newLine();
					it.append("\t\treturn "); //$NON-NLS-1$
					if (forAppender) {
						it.append("this.builder.toString();"); //$NON-NLS-1$
					} else {
						it.append(EmfFormatter.class);
						it.append(".objToStr(get"); //$NON-NLS-1$
						it.append(Strings.toFirstUpper(parameter.getElementType().getSimpleName()));
						it.append("());"); //$NON-NLS-1$
					}
					it.newLine();
					it.append("\t}"); //$NON-NLS-1$
					it.newLineIfNotEmpty();
					it.newLine();
				}
				if (forInterface) {
					it.append("\t/** Dispose the resource."); //$NON-NLS-1$
					it.newLine();
					it.append("\t */"); //$NON-NLS-1$
					it.newLine();
					it.append("\tvoid dispose();"); //$NON-NLS-1$
					it.newLineIfNotEmpty();
					it.newLine();
				} else if (forAppender) {
					it.append("\t/** Dispose the resource."); //$NON-NLS-1$
					it.newLine();
					it.append("\t */"); //$NON-NLS-1$
					it.newLine();
					it.append("\tpublic void dispose() {"); //$NON-NLS-1$
					it.newLine();
					it.append("\t\tthis.builder.dispose();"); //$NON-NLS-1$
					it.newLine();
					it.append("\t}"); //$NON-NLS-1$
					it.newLineIfNotEmpty();
					it.newLine();
				}

				it.append("\t/** Add upper type bounds."); //$NON-NLS-1$
				it.newLine();
				it.append("\t * @param type the type."); //$NON-NLS-1$
				it.newLine();
				it.append("\t */"); //$NON-NLS-1$
				it.newLine();
				it.append("\t"); //$NON-NLS-1$
				if (!forInterface) {
					it.append("public "); //$NON-NLS-1$
				}
				it.append("void addUpperConstraint(String type)"); //$NON-NLS-1$
				if (forInterface) {
					it.append(";"); //$NON-NLS-1$
				} else {
					it.append(" {"); //$NON-NLS-1$
					it.newLine();
					it.append("\t\t"); //$NON-NLS-1$
					if (forAppender) {
						it.append("this.builder.addUpperConstraint(type);"); //$NON-NLS-1$
					} else {
						it.append("final "); //$NON-NLS-1$
						it.append(JvmUpperBound.class);
						it.append(" constraint = this.jvmTypesFactory.createJvmUpperBound();"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\tconstraint.setTypeReference(newTypeRef(this.context, type));"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\tget"); //$NON-NLS-1$
						it.append(Strings.toFirstUpper(parameter.getElementType().getSimpleName()));
						it.append("().getConstraints().add(constraint);"); //$NON-NLS-1$
					}
					it.newLine();
					it.append("\t}"); //$NON-NLS-1$
				}
				it.newLineIfNotEmpty();
				it.newLine();

				it.append("\t/** Add lower type bounds."); //$NON-NLS-1$
				it.newLine();
				it.append("\t * @param type the type."); //$NON-NLS-1$
				it.newLine();
				it.append("\t */"); //$NON-NLS-1$
				it.newLine();
				it.append("\t"); //$NON-NLS-1$
				if (!forInterface) {
					it.append("public "); //$NON-NLS-1$
				}
				it.append("void addLowerConstraint(String type)"); //$NON-NLS-1$
				if (forInterface) {
					it.append(";"); //$NON-NLS-1$
				} else {
					it.append(" {"); //$NON-NLS-1$
					it.newLine();
					it.append("\t\t"); //$NON-NLS-1$
					if (forAppender) {
						it.append("this.builder.addLowerConstraint(type);"); //$NON-NLS-1$
					} else {
						it.append("final "); //$NON-NLS-1$
						it.append(JvmLowerBound.class);
						it.append(" constraint = this.jvmTypesFactory.createJvmLowerBound();"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\tconstraint.setTypeReference(newTypeRef(this.context, type));"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\tget"); //$NON-NLS-1$
						it.append(Strings.toFirstUpper(parameter.getElementType().getSimpleName()));
						it.append("().getConstraints().add(constraint);"); //$NON-NLS-1$
					}
					it.newLine();
					it.append("\t}"); //$NON-NLS-1$
				}
				it.newLineIfNotEmpty();
				it.newLine();
			}
		};
	}
98711
private static void generateCCMPoolHTML(String poolName, List<TraceEvent> events,
                                           TraceEventStatus status, FileWriter fw)
      throws Exception
   {
      writeString(fw, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"");
      writeEOL(fw);
      writeString(fw, "                      \"http://www.w3.org/TR/html4/loose.dtd\">");
      writeEOL(fw);

      writeString(fw, "<html>");
      writeEOL(fw);

      writeString(fw, "<head>");
      writeEOL(fw);

      writeString(fw, "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">");
      writeEOL(fw);

      writeString(fw, "<title>CCM: " + poolName + "</title>");
      writeEOL(fw);

      writeString(fw, "</head>");
      writeEOL(fw);

      writeString(fw, "<body style=\"background: #D7D7D7;\">");
      writeEOL(fw);

      writeString(fw, "<h1>CCM: " + poolName + "</h1>");
      writeEOL(fw);

      writeString(fw, "<table>");
      writeEOL(fw);

      writeString(fw, "<tr>");
      writeEOL(fw);

      writeString(fw, "<td><b>Status:</b></td><td><div style=\"color: ");

      writeString(fw, status.getColor());
      writeString(fw, ";\">");

      writeString(fw, status.getDescription());
      
      writeString(fw, "</div></td>");
      writeEOL(fw);

      writeString(fw, "</tr>");
      writeEOL(fw);

      writeString(fw, "</table>");
      writeEOL(fw);

      writeString(fw, "<p>");
      writeEOL(fw);

      writeString(fw, "<table>");
      writeEOL(fw);

      writeString(fw, "<tr>");
      writeEOL(fw);

      writeString(fw, "<td><b>Timestamp</b></td>");
      writeEOL(fw);

      writeString(fw, "<td><b>Thread</b></td>");
      writeEOL(fw);

      writeString(fw, "<td><b>ManagedConnectionPool</b></td>");
      writeEOL(fw);

      writeString(fw, "<td><b>Event</b></td>");
      writeEOL(fw);

      writeString(fw, "<td><b>ConnectionListener</b></td>");
      writeEOL(fw);

      writeString(fw, "<td><b>Connection</b></td>");
      writeEOL(fw);

      writeString(fw, "<td><b>Key</b></td>");
      writeEOL(fw);

      writeString(fw, "</tr>");
      writeEOL(fw);

      for (TraceEvent te : events)
      {
         writeString(fw, "<tr>");
         writeEOL(fw);

         writeString(fw, "<td>" + te.getTimestamp() + "</td>");
         writeEOL(fw);
      
         writeString(fw, "<td>" + te.getThreadId() + "</td>");
         writeEOL(fw);
      
         if (!"NONE".equals(te.getManagedConnectionPool()))
         {
            writeString(fw, "<td>" + te.getManagedConnectionPool() + "</td>");
         }
         else
         {
            writeString(fw, "<td></td>");
         }
         writeEOL(fw);
      
         writeString(fw, "<td>" + TraceEvent.asText(te) + "</td>");
         writeEOL(fw);
      
         if (!"NONE".equals(te.getConnectionListener()))
         {
            writeString(fw, "<td><a href=\"" + te.getConnectionListener() + "/index.html\">" +
                        te.getConnectionListener() + "</a></td>");
         }
         else
         {
            writeString(fw, "<td></td>");
         }
         writeEOL(fw);
      
         if (!"NONE".equals(te.getPayload1()))
         {
            writeString(fw, "<td>" + te.getPayload1() + "</td>");
         }
         else
         {
            writeString(fw, "<td></td>");
         }
         writeEOL(fw);
      
         writeString(fw, "<td>" + te.getPayload2() + "</td>");
         writeEOL(fw);
      
         writeString(fw, "</tr>");
         writeEOL(fw);
      }

      writeString(fw, "</table>");
      writeEOL(fw);

      writeString(fw, "<h2>Pool</h2>");
      writeEOL(fw);

      writeString(fw, "<a href=\"index.html\">Report</a>");
      writeEOL(fw);

      writeString(fw, "<h2>Lifecycle</h2>");
      writeEOL(fw);

      writeString(fw, "<a href=\"lifecycle.html\">Report</a>");
      writeEOL(fw);

      writeString(fw, "<p>");
      writeEOL(fw);

      writeString(fw, "<h2>Data</h2>");
      writeEOL(fw);

      writeString(fw, "<pre>");
      writeEOL(fw);

      for (TraceEvent te : events)
      {
         writeString(fw, TraceEventHelper.prettyPrint(te));
         writeEOL(fw);
      }

      writeString(fw, "</pre>");
      writeEOL(fw);

      writeString(fw, "<p>");
      writeEOL(fw);

      writeString(fw, "<a href=\"../index.html\">Back</a>");
      writeEOL(fw);

      writeString(fw, "</body>");
      writeEOL(fw);

      writeString(fw, "</html>");
      writeEOL(fw);
   }
995502
def lint_codebase
      finder = FileFinder.new(path, options)
      files = load_files(finder)
      files_count = files.count
      reports = files.map do |file|
        Todo.within(File.open(file), :config => @options).map do |todo|
          reporter = Reporter.new(todo,
                                  :judge => Judge.new(todo))
          reporter.report.tap do |report|
            print Rainbow(".").public_send(report.nil? ? :green : :red)
          end
        end
      end.flatten.compact
      if reports.any?
        puts
        reports.each do |report|
          puts report
        end
        puts "\nFound #{pluralize('problematic todo', reports.count)} in " \
          "#{pluralize('file', files_count)}"
        exit 1
      else
        puts "\nGreat job! No overdue todos in " \
             "#{pluralize('file', files_count)}"
        exit 0
      end
    end
545653
function parse(code) {
  var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];

  opts.allowHashBang = true;
  opts.sourceType = "module";
  opts.ecmaVersion = Infinity;
  opts.plugins = {
    jsx: true,
    flow: true
  };
  opts.features = {};

  for (var key in _transformation2["default"].pipeline.transformers) {
    opts.features[key] = true;
  }

  var ast = babylon.parse(code, opts);

  if (opts.onToken) {
    // istanbul ignore next

    var _opts$onToken;

    (_opts$onToken = opts.onToken).push.apply(_opts$onToken, ast.tokens);
  }

  if (opts.onComment) {
    // istanbul ignore next

    var _opts$onComment;

    (_opts$onComment = opts.onComment).push.apply(_opts$onComment, ast.comments);
  }

  return ast.program;
}
665954
private static void generateCCMHTML(List<TraceEvent> events, TraceEventStatus status, String path, FileWriter fw)
      throws Exception
   {
      writeString(fw, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"");
      writeEOL(fw);
      writeString(fw, "                      \"http://www.w3.org/TR/html4/loose.dtd\">");
      writeEOL(fw);

      writeString(fw, "<html>");
      writeEOL(fw);

      writeString(fw, "<head>");
      writeEOL(fw);

      writeString(fw, "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">");
      writeEOL(fw);

      writeString(fw, "<title>CachedConnectionManager</title>");
      writeEOL(fw);

      writeString(fw, "</head>");
      writeEOL(fw);

      writeString(fw, "<body style=\"background: #D7D7D7;\">");
      writeEOL(fw);

      writeString(fw, "<h1>CachedConnectionManager</h1>");
      writeEOL(fw);

      writeString(fw, "<table>");
      writeEOL(fw);

      writeString(fw, "<tr>");
      writeEOL(fw);

      writeString(fw, "<td><b>Status:</b></td><td><div style=\"color: ");
      writeString(fw, status.getColor());
      writeString(fw, ";\">");

      writeString(fw, status.getDescription());

      writeString(fw, "</div></td>");
      writeEOL(fw);
      
      writeString(fw, "</tr>");
      writeEOL(fw);

      writeString(fw, "</table>");
      writeEOL(fw);

      writeString(fw, "<p>");
      writeEOL(fw);

      writeString(fw, "<table>");
      writeEOL(fw);

      writeString(fw, "<tr>");
      writeEOL(fw);

      writeString(fw, "<td><b>Timestamp</b></td>");
      writeEOL(fw);

      writeString(fw, "<td><b>Thread</b></td>");
      writeEOL(fw);

      writeString(fw, "<td><b>Event</b></td>");
      writeEOL(fw);

      writeString(fw, "<td><b>Key</b></td>");
      writeEOL(fw);

      writeString(fw, "<td><b>Call stack</b></td>");
      writeEOL(fw);

      writeString(fw, "</tr>");
      writeEOL(fw);

      for (TraceEvent te : events)
      {
         writeString(fw, "<tr>");
         writeEOL(fw);

         writeString(fw, "<td>" + te.getTimestamp() + "</td>");
         writeEOL(fw);
      
         writeString(fw, "<td>" + te.getThreadId() + "</td>");
         writeEOL(fw);
      
         writeString(fw, "<td>" + TraceEvent.asText(te) + "</td>");
         writeEOL(fw);
      
         writeString(fw, "<td>" + te.getPayload1() + "</td>");
         writeEOL(fw);

         String callstack = te.getPayload1();
         if (te.getType() == TraceEvent.PUSH_CCM_CONTEXT)
         {
            callstack += "-push";
         }
         else
         {
            callstack += "-pop";
         }
         callstack += ".txt";
         
         writeString(fw, "<td><a href=\"" + callstack + "\">Link</a></td>");
         writeEOL(fw);

         FileWriter report = null;
         try
         {
            report = new FileWriter(path + "/" + callstack);
            writeString(report, TraceEventHelper.exceptionDescription(te.getPayload2()));
            writeEOL(report);
         }
         finally
         {
            if (report != null)
            {
               try
               {
                  report.flush();
                  report.close();
               }
               catch (Exception e)
               {
                  // Ignore
               }
            }
         }
         
         writeString(fw, "</tr>");
         writeEOL(fw);
      }

      writeString(fw, "</table>");
      writeEOL(fw);

      writeString(fw, "<p>");
      writeEOL(fw);

      writeString(fw, "<a href=\"../index.html\">Back</a>");
      writeEOL(fw);

      writeString(fw, "</body>");
      writeEOL(fw);

      writeString(fw, "</html>");
      writeEOL(fw);
   }
142421
private static String encodeExampleForUrl(Object example) {
        try {
            return URLEncoder.encode(String.valueOf(example), "UTF-8");
        } catch (UnsupportedEncodingException exception) {
            throw new RuntimeException(exception);
        }
    }
645309
function showHelp() {
  var hlp = [
    '',
    '  Usage: \x1B[1mjspp\x1B[0m [options] [file...]',
    '',
    '    Tiny C-style source file preprocessor for JavaScript, with duplicate',
    '    empty lines and comments remover.',
    '',
    '    If no file name are given, jspp reads from the standard input.',
    '',
    '  Options:',
    '',
    '    -D, --set       add a variable for use in expressions (e.g. -D NAME=value)',
    '                    type: string - e.g. -D "MODULE=1"',
    '    --header1       text to insert before the top level file.',
    '                    type: string - default: ' + JSON.stringify(defaults.header1),
    '    --headers       text to insert before each included file.',
    '                    type: string - default: ' + JSON.stringify(defaults.headers),
    '    --indent        indentation to add before each line of the included files.',
    '                    The format matches the regex /^\\d+\\s*[ts]?/, e.g. "1t", ',
    '                    where \'t\' means tabs and \'s\' spaces, default is spaces.',
    '                    Each level adds indentation.',
    '                    type: string - default: ' + JSON.stringify(defaults.indent),
    '    --eol-type      normalize end of lines to "unix", "win", or "mac" style',
    '                    type: string - default: ' + JSON.stringify(defaults.eolType),
    '    --empty-lines   how much empty lines keep in the output (-1: keep all)',
    '                    type: number - default: ' + JSON.stringify(defaults.emptyLines),
    '    -C, --comments  treatment of the comments, one of:',
    '                    "all": keep all, "none": remove all, "filter": apply filter',
    '                    type: string - default: ' + JSON.stringify(defaults.comments),
    '    -F, --filter    keep comments matching filter. "all" to apply all filters,',
    '                    or one or more of:',
    '                    ' + Object.keys(Options.filters).join(', '),
    '    --custom-filter string for create a regex as custom filter to apply with',
    '                    regex.test(). must return true to keep the comment.',
    '                    type: string - e.g. --custom-filter "\\\\\* @module"',
    '    -V, --version   print version to stdout and exits.',
    '    -h, --help      display this message.',
    '',
    '  Tips:',
    '    Use "^n" in the header1 and headers option values to insert line feeds.',
    '    You can preprocess files other than JavaScript using --comments all.',
    '',
    '',
    '  Clone the jspreproc repository at https://github.com/aMarCruz/jspreproc.git',
    '  run `npm i && npm t`, and find examples of use in spec/app-spec.js',
    ''
  ]
  console.log(hlp.join('\n'))
}
222605
function docmeify(htmldir, cb) {
  var outstreams =  [] 
    , pruneTransform = transformify(pruneHtml.bind(null, [ 'h1', 'h2', 'h3', 'header' ]));

  function getOutStream() {
    var s = new MutinyWritable();
    outstreams.push(s);
    return s;
  }

  function onend() {
    var apidocs = outstreams.map(function (x) { return x.apidoc }).join('');
    cb(null, apidocs);
  }
  
  log.verbose('docme', 'githubifying the jsdoc generated pages');

  mutiny(
      { getOutStream: getOutStream, transform: [ jsdocGithubify, pruneTransform ] }
    , { root: htmldir, fileFilter: '*.html' }
  )
  .on('error', cb)
  .on('data', function (d) { log.verbose('docme', 'Processed:\n', d); })
  .on('end', onend)
}
442259
@SuppressWarnings("checkstyle:all")
	protected StringConcatenationClient generateFieldsAndMethods(boolean forInterface, boolean forAppender) {
		TypeReference scriptInterface = getCodeElementExtractor().getLanguageScriptInterface();
		return new StringConcatenationClient() {
			@Override
			protected void appendTo(TargetStringConcatenation it) {
				// Fields
				if (!forInterface && !forAppender) {
					it.append("\tprivate "); //$NON-NLS-1$
					it.append(scriptInterface);
					it.append(" script;"); //$NON-NLS-1$
					it.newLineIfNotEmpty();
					it.newLine();
					it.append("\tprivate boolean isFinalized;"); //$NON-NLS-1$
					it.newLineIfNotEmpty();
					it.newLine();
				} else if (forAppender) {
					it.append("\tprivate "); //$NON-NLS-1$
					it.append(getScriptBuilderInterface());
					it.append(" builder;"); //$NON-NLS-1$
					it.newLineIfNotEmpty();
					it.newLine();
				}
				if (forInterface || forAppender) {
					it.append("\t/** Find the reference to the type with the given name."); //$NON-NLS-1$
					it.newLine();
					it.append("\t * @param typeName the fully qualified name of the type"); //$NON-NLS-1$
					it.newLine();
					it.append("\t * @return the type reference."); //$NON-NLS-1$
					it.newLine();
					it.append("\t */"); //$NON-NLS-1$
					it.newLine();
					it.append("\t"); //$NON-NLS-1$
					if (!forInterface) {
						it.append("public "); //$NON-NLS-1$
					}
					it.append(JvmParameterizedTypeReference.class);
					it.append(" newTypeRef(String typeName)"); //$NON-NLS-1$
					if (forInterface) {
						it.append(";"); //$NON-NLS-1$
					} else {
						it.append(" {"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\treturn this.builder.newTypeRef(typeName);"); //$NON-NLS-1$
						it.newLine();
						it.append("\t}"); //$NON-NLS-1$
					}
					it.newLineIfNotEmpty();
					it.newLine();
					it.append("\t/** Find the reference to the type with the given name."); //$NON-NLS-1$
					it.newLine();
					it.append("\t * @param context the context for the type reference use"); //$NON-NLS-1$
					it.newLine();
					it.append("\t * @param typeName the fully qualified name of the type"); //$NON-NLS-1$
					it.newLine();
					it.append("\t * @return the type reference."); //$NON-NLS-1$
					it.newLine();
					it.append("\t */"); //$NON-NLS-1$
					it.newLine();
					it.append("\t"); //$NON-NLS-1$
					if (!forInterface) {
						it.append("public "); //$NON-NLS-1$
					}
					it.append(JvmParameterizedTypeReference.class);
					it.append(" newTypeRef("); //$NON-NLS-1$
					it.append(Notifier.class);
					it.append(" context, String typeName)"); //$NON-NLS-1$
					if (forInterface) {
						it.append(";"); //$NON-NLS-1$
					} else {
						it.append(" {"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\treturn this.builder.newTypeRef(context, typeName);"); //$NON-NLS-1$
						it.newLine();
						it.append("\t}"); //$NON-NLS-1$
					}
					it.newLineIfNotEmpty();
					it.newLine();
				}
				if (forInterface) {
					it.append("\t/** Replies the context for type resolution."); //$NON-NLS-1$
					it.newLine();
					it.append("\t * @return the context or <code>null</code> if the Ecore object is the context."); //$NON-NLS-1$
					it.newLine();
					it.append("\t */"); //$NON-NLS-1$
					it.newLine();
					it.append("\t"); //$NON-NLS-1$
					it.append(IJvmTypeProvider.class);
					it.append(" getTypeResolutionContext();"); //$NON-NLS-1$
					it.newLineIfNotEmpty();
					it.newLine();
				} else if (forAppender) {
					it.append("\tpublic "); //$NON-NLS-1$
					it.append(IJvmTypeProvider.class);
					it.append(" getTypeResolutionContext() {"); //$NON-NLS-1$
					it.newLine();
					it.append("\t\treturn this.builder.getTypeResolutionContext();"); //$NON-NLS-1$
					it.newLine();
					it.append("\t}"); //$NON-NLS-1$
					it.newLineIfNotEmpty();
					it.newLine();
				}
				if (forAppender) {
					it.append("\tpublic "); //$NON-NLS-1$
					it.append(getScriptAppender().getSimpleName());
					it.append("("); //$NON-NLS-1$
					it.append(getScriptBuilderInterface());
					it.append(" builder) {"); //$NON-NLS-1$
					it.newLine();
					it.append("\t\tthis.builder = builder;"); //$NON-NLS-1$
					it.newLine();
					it.append("\t}"); //$NON-NLS-1$
					it.newLineIfNotEmpty();
					it.newLine();
					it.append("\tpublic void build("); //$NON-NLS-1$
					it.append(ISourceAppender.class);
					it.append(" appender) throws "); //$NON-NLS-1$
					it.append(IOException.class);
					it.append(" {"); //$NON-NLS-1$
					it.newLine();
					it.append("\t\tif (!isFinalized()) {"); //$NON-NLS-1$
					it.newLine();
					it.append("\t\t\tfinalizeScript();"); //$NON-NLS-1$
					it.newLine();
					it.append("\t\t}"); //$NON-NLS-1$
					it.newLine();
					it.append("\t\tbuild(this.builder.getScript(), appender);"); //$NON-NLS-1$
					it.newLine();
					it.append("\t}"); //$NON-NLS-1$
					it.newLineIfNotEmpty();
					it.newLine();
				}
				it.append("\t/** Create the internal " + getLanguageName() + " script."); //$NON-NLS-1$ //$NON-NLS-2$
				it.newLine();
				it.append("\t */"); //$NON-NLS-1$
				it.newLine();
				it.append("\t"); //$NON-NLS-1$
				if (!forInterface) {
					it.append("public "); //$NON-NLS-1$
				}
				it.append("void eInit("); //$NON-NLS-1$
				it.append(Resource.class);
				it.append(" resource, String packageName, "); //$NON-NLS-1$
				it.append(IJvmTypeProvider.class);
				it.append(" context)"); //$NON-NLS-1$
				if (forInterface) {
					it.append(";"); //$NON-NLS-1$
				} else {
					it.append(" {"); //$NON-NLS-1$
					it.newLine();
					if (forAppender) {
						it.append("\t\tthis.builder.eInit(resource, packageName, context);"); //$NON-NLS-1$
					} else {
						it.append("\t\tsetTypeResolutionContext(context);"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\tif (this.script == null) {"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t\tthis.script = "); //$NON-NLS-1$
						it.append(getXFactoryFor(scriptInterface));
						it.append(".eINSTANCE.create"); //$NON-NLS-1$
						it.append(Strings.toFirstUpper(scriptInterface.getSimpleName()));
						it.append("();"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t\t"); //$NON-NLS-1$
						it.append(EList.class);
						it.append("<"); //$NON-NLS-1$
						it.append(EObject.class);
						it.append("> content = resource.getContents();"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t\tif (!content.isEmpty()) {"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t\t\tcontent.clear();"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t\t}"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t\tcontent.add(this.script);"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t\tif (!"); //$NON-NLS-1$
						it.append(Strings.class);
						it.append(".isEmpty(packageName)) {"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t\t\tscript.setPackage(packageName);"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t\t}"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t}"); //$NON-NLS-1$
					}
					it.newLine();
					it.append("\t}"); //$NON-NLS-1$
				}
				it.newLineIfNotEmpty();
				it.newLine();
				it.append("\t/** Replies the " + getLanguageName() + " script."); //$NON-NLS-1$ //$NON-NLS-2$
				it.newLine();
				it.append("\t */"); //$NON-NLS-1$
				it.newLine();
				it.append("\t@"); //$NON-NLS-1$
				it.append(Pure.class);
				it.newLine();
				it.append("\t"); //$NON-NLS-1$
				if (!forInterface) {
					it.append("public "); //$NON-NLS-1$
				}
				it.append(scriptInterface);
				it.append(" getScript()"); //$NON-NLS-1$
				if (forInterface) {
					it.append(";"); //$NON-NLS-1$
				} else {
					it.append(" {"); //$NON-NLS-1$
					it.newLine();
					if (forAppender) {
						it.append("\t\treturn this.builder.getScript();"); //$NON-NLS-1$
					} else {
						it.append("\t\treturn this.script;"); //$NON-NLS-1$
					}
					it.newLine();
					it.append("\t}"); //$NON-NLS-1$
				}
				it.newLineIfNotEmpty();
				it.newLine();
				it.append("\t/** Replies the resource to which the script is attached."); //$NON-NLS-1$
				it.newLine();
				it.append("\t */"); //$NON-NLS-1$
				it.newLine();
				it.append("\t@"); //$NON-NLS-1$
				it.append(Pure.class);
				it.newLine();
				it.append("\t"); //$NON-NLS-1$
				if (!forInterface) {
					it.append("public "); //$NON-NLS-1$
				}
				it.append(Resource.class);
				it.append(" eResource()"); //$NON-NLS-1$
				if (forInterface) {
					it.append(";"); //$NON-NLS-1$
				} else {
					it.append(" {"); //$NON-NLS-1$
					it.newLine();
					it.append("\t\treturn getScript().eResource();"); //$NON-NLS-1$
					it.newLine();
					it.append("\t}"); //$NON-NLS-1$
				}
				it.newLineIfNotEmpty();
				it.newLine();
				it.append("\t/** Finalize the script."); //$NON-NLS-1$
				it.newLine();
				it.append("\t *"); //$NON-NLS-1$
				it.newLine();
				it.append("\t * <p>The finalization includes: <ul>"); //$NON-NLS-1$
				it.newLine();
				it.append("\t * <li>The import section is created.</li>"); //$NON-NLS-1$
				it.newLine();
				it.append("\t * </ul>"); //$NON-NLS-1$
				it.newLine();
				it.append("\t */"); //$NON-NLS-1$
				it.newLine();
				it.append("\t"); //$NON-NLS-1$
				if (!forInterface) {
					it.append("public "); //$NON-NLS-1$
				}
				it.append("void finalizeScript()"); //$NON-NLS-1$
				if (forInterface) {
					it.append(";"); //$NON-NLS-1$
				} else {
					it.append(" {"); //$NON-NLS-1$
					it.newLine();
					if (forAppender) {
						it.append("\t\tthis.builder.finalizeScript();"); //$NON-NLS-1$
					} else {
						it.append("\t\tif (this.isFinalized) {"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t\tthrow new "); //$NON-NLS-1$
						it.append(IllegalStateException.class);
						it.append("(\"already finalized\");"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t}"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\tthis.isFinalized = true;"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t"); //$NON-NLS-1$
						it.append(ImportManager.class);
						it.append(" concreteImports = new "); //$NON-NLS-1$
						it.append(ImportManager.class);
						it.append("(true);"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t"); //$NON-NLS-1$
						it.append(XImportSection.class);
						it.append(" importSection = getScript().getImportSection();"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\tif (importSection != null) {"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t\tfor ("); //$NON-NLS-1$
						it.append(XImportDeclaration.class);
						it.append(" decl : importSection.getImportDeclarations()) {"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t\t\tconcreteImports.addImportFor(decl.getImportedType());"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t\t}"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t}"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\tfor (String importName : getImportManager().getImports()) {"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t\t"); //$NON-NLS-1$
						it.append(JvmType.class);
						it.append(" type = findType(getScript(), importName).getType();"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t\tif (concreteImports.addImportFor(type) && type instanceof "); //$NON-NLS-1$
						it.append(JvmDeclaredType.class);
						it.append(") {"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t\t\t"); //$NON-NLS-1$
						it.append(XImportDeclaration.class);
						it.append(" declaration = "); //$NON-NLS-1$
						it.append(XtypeFactory.class);
						it.append(".eINSTANCE.createXImportDeclaration();"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t\t\tdeclaration.setImportedType(("); //$NON-NLS-1$
						it.append(JvmDeclaredType.class);
						it.append(") type);"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t\t\tif (importSection == null) {"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t\t\t\timportSection = "); //$NON-NLS-1$
						it.append(XtypeFactory.class);
						it.append(".eINSTANCE.createXImportSection();"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t\t\t\tgetScript().setImportSection(importSection);"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t\t\t}"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t\t\timportSection.getImportDeclarations().add(declaration);"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t\t}"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t}"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t"); //$NON-NLS-1$
						it.append(Resource.class);
						it.append(" resource = getScript().eResource();"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\tif (resource instanceof "); //$NON-NLS-1$
						it.append(DerivedStateAwareResource.class);
						it.append(") {"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t\t(("); //$NON-NLS-1$
						it.append(DerivedStateAwareResource.class);
						it.append(") resource).discardDerivedState();"); //$NON-NLS-1$
						it.newLine();
						it.append("\t\t}"); //$NON-NLS-1$
					}
					it.newLine();
					it.append("\t}"); //$NON-NLS-1$
				}
				it.newLineIfNotEmpty();
				it.newLine();
				it.append("\t/** Replies if the script was finalized."); //$NON-NLS-1$
				it.newLine();
				it.append("\t */"); //$NON-NLS-1$
				it.newLine();
				it.append("\t"); //$NON-NLS-1$
				if (!forInterface) {
					it.append("public "); //$NON-NLS-1$
				}
				it.append("boolean isFinalized()"); //$NON-NLS-1$
				if (forInterface) {
					it.append(";"); //$NON-NLS-1$
				} else {
					it.append(" {"); //$NON-NLS-1$
					it.newLine();
					if (forAppender) {
						it.append("\t\treturn this.builder.isFinalized();"); //$NON-NLS-1$
					} else {
						it.append("\t\treturn this.isFinalized;"); //$NON-NLS-1$
					}
					it.newLine();
					it.append("\t}"); //$NON-NLS-1$
				}
				it.newLineIfNotEmpty();
				it.newLine();
				if (!forInterface) {
					it.append("\t@"); //$NON-NLS-1$
					it.append(Override.class);
					it.newLine();
					it.append("\t@"); //$NON-NLS-1$
					it.append(Pure.class);
					it.newLine();
					it.append("\tpublic "); //$NON-NLS-1$
					it.append(String.class);
					it.append(" toString() {"); //$NON-NLS-1$
					it.newLine();
					it.append("\t\treturn "); //$NON-NLS-1$
					if (forAppender) {
						it.append("this.builder.toString();"); //$NON-NLS-1$
					} else {
						it.append(EmfFormatter.class);
						it.append(".objToStr(this.script);"); //$NON-NLS-1$
					}
					it.newLine();
					it.append("\t}"); //$NON-NLS-1$
					it.newLineIfNotEmpty();
					it.newLine();
				}
			}
		};
	}
716228
void generateClassCode(Definition def, String className, String subDir)
   {
      if (className == null || className.equals(""))
         return;

      try
      {
         String clazzName = this.getClass().getPackage().getName() + ".code." + className + "CodeGen";
         String javaFile =
               Definition.class.getMethod("get" + className + "Class").invoke(def, (Object[]) null) + ".java";
         FileWriter fw;
         if (subDir == null)
            fw = Utils.createSrcFile(javaFile, def.getRaPackage(), def.getOutputDir());
         else
            fw = Utils.createSrcFile(javaFile, def.getRaPackage() + "." + subDir, def.getOutputDir());

         Class<?> clazz = Class.forName(clazzName, true, Thread.currentThread().getContextClassLoader());
         AbstractCodeGen codeGen = (AbstractCodeGen) clazz.newInstance();

         codeGen.generate(def, fw);

         fw.flush();
         fw.close();
      }
      catch (Exception e)
      {
         e.printStackTrace();
      }
   }
503380
function createElementScript() {
  return gulp
    .src(`./${config.src.path}/${config.src.entrypoint}`)
    .pipe(
      modifyFile(content => {
        /**
         * Strip the imports and exports out of the parse code and return them.
         *
         * @param {Program} parsedCode
         *   The parsed code.
         * @returns {{imports:Map<number,Object>, exports:Map<number,Object>}}
         */
        const stripImportsAndExports = parsedCode => {
          // Get info about the code.
          const codeIndexesToRemove = [];
          const imports = new Map();
          const exports = new Map();
          for (const [nodeIndex, node] of parsedCode.body.entries()) {
            switch (node.type) {
              case 'ImportDeclaration':
                for (const specifiers of node.specifiers) {
                  let importedName;
                  if (specifiers.type === 'ImportDefaultSpecifier') {
                    importedName = specifiers.local.name;
                  } else if (specifiers.type === 'ImportSpecifier') {
                    importedName = specifiers.imported.name;
                  }

                  if (
                    importedName != null &&
                    importedName.toLowerCase().startsWith('catalyst')
                  ) {
                    imports.set(nodeIndex, node);
                    codeIndexesToRemove.push(nodeIndex);
                  } else {
                    throw new Error(
                      `Cannot automatically process import "${importedName}."`
                    );
                  }
                }
                break;

              case 'ExportDefaultDeclaration':
              case 'ExportNamedDeclaration':
                exports.set(nodeIndex, parsedCode.body[nodeIndex]);
                codeIndexesToRemove.push(nodeIndex);
                break;

              // Different type? Do nothing.
              default:
            }
          }

          // Remove imports and exports.
          parsedCode.body = parsedCode.body.filter(
            (e, i) => !codeIndexesToRemove.includes(i)
          );

          return {
            imports: imports,
            exports: exports
          };
        };

        /**
         * Replace catalyst element's imports with globally accessible object import.
         *
         * @param {Program} parsedCode
         *   The parsed code with the imports already stripped out.
         * @param {Map<number,Object>} imports
         *   The imports that have been stripped out of the parsed code.
         */
        const processImports = (parsedCode, imports) => {
          for (const [importDefIndex, importDef] of imports) {
            for (const specifier of Object.values(importDef.specifiers)) {
              const localName = specifier.local.name;
              const importedName = specifier.imported
                ? specifier.imported.name
                : localName;

              if (importedName.toLowerCase().startsWith('catalyst')) {
                parsedCode.body.splice(
                  importDefIndex,
                  0,
                  esprima.parseScript(
                    `let ${localName} = window.CatalystElements.${importedName};`
                  )
                );
              } else {
                throw new Error(
                  `Cannot automatically process import "${importedName}."`
                );
              }
            }
          }
        };

        /**
         * Replace exports with globally accessible object exports.
         *
         * @param {Program} parsedCode
         *   The parsed code with the exports already stripped out.
         * @param {Map<number,Object>} exports
         *   The exports that have been stripped out of the parsed code.
         */
        const processExports = (parsedCode, exports) => {
          const exportNamesUsed = [];

          // Replace exports with globally accessible object exports.
          for (const [exportDefIndex, exportDef] of exports) {
            if (exportDef.declaration === null) {
              for (const specifier of Object.values(exportDef.specifiers)) {
                const localName = specifier.local.name;
                const exportedName = specifier.imported
                  ? specifier.imported.name
                  : localName;

                if (!exportNamesUsed.includes(exportedName)) {
                  parsedCode.body.splice(
                    exportDefIndex,
                    0,
                    esprima.parseScript(
                      `window.CatalystElements.${exportedName} = ${localName};`
                    )
                  );
                  exportNamesUsed.push(exportedName);
                }
              }
            } else if (exportDef.declaration.type === 'Identifier') {
              if (!exportNamesUsed.includes(exportDef.declaration.name)) {
                parsedCode.body.splice(
                  exportDefIndex,
                  0,
                  esprima.parseScript(
                    `window.CatalystElements.${exportDef.declaration.name} = ${
                      exportDef.declaration.name
                    };`
                  )
                );
                exportNamesUsed.push(exportDef.declaration.name);
              }
            } else {
              console.error(
                `Cannot automatically process declaration in ${exportDef.type}.`
              );
            }
          }
        };

        // Parse the code.
        const parsedCode = esprima.parseModule(content);

        // Run functions defined above.
        const { imports, exports } = stripImportsAndExports(parsedCode);
        processImports(parsedCode, imports);
        processExports(parsedCode, exports);

        // Generate the updated code.
        return (
          'window.CatalystElements = window.CatalystElements || {};\n' +
          `${escodegen.generate(parsedCode)}`
        );
      })
    )
    .pipe(
      rename(path => {
        path.basename = config.element.tag;
        path.extname = `.script${path.extname}`;
      })
    )
    .pipe(gulp.dest(`./${config.temp.path}`));
}
21677
def codegen(cc):
    

    import inspect

    def format_desc(obj, indent):
        linelen = 75 - indent
        if isinstance(obj, six.string_types):
            raw = obj
        else:
            try:
                raw = obj.qualifiers['description'].value
            except KeyError:
                return ''
        txt = ''
        beg = 0
        end = 0
        while beg < len(raw):
            beg = end
            end += linelen
            while beg < len(raw) and raw[beg].isspace():
                beg = beg+1
            while end < len(raw) and end > beg and not raw[end].isspace():
                end = end-1
            if beg == end: # a long URL
                while end < len(raw) and not raw[end].isspace():
                    end += 1
            line = raw[beg:end]
            line = line.replace('\n', ' ')
            line = line.replace('\r', '')
            txt += '\n%s%s'% (''.ljust(indent), line)
        return txt

    #################
    def map_value(obj, val):
        rv = str(val)
        if 'ValueMap' not in obj.qualifiers:
            return rv
        if 'Values' not in obj.qualifiers:
            return rv
        vals = [str(x) for x in obj.qualifiers['Values'].value]
        maps = [str(x) for x in obj.qualifiers['ValueMap'].value]
        d = dict(zip(maps, vals))
        try:
            tmp = d[str(val)]
            rv = ''
            for ch in tmp:
                rv += ch.isalnum() and ch or '_'
        except KeyError:
            pass
        return rv

    #################
    def type_hint(obj, method_name=None):
        if hasattr(obj, 'type'):
            tx = obj.type
            if 'embeddedinstance' in obj.qualifiers:
                tx = "pywbem.CIMInstance(classname='%s', ...)" % \
                        obj.qualifiers['embeddedinstance'].value
            elif tx == 'reference':
                tx = "pywbem.CIMInstanceName(classname='%s', ...)" % \
                        obj.reference_class
        else:
            tx = obj.return_type
        if hasattr(obj, 'value') and obj.value is not None:
            defval = str(obj.value)
        else:
            defval = ''
        if not tx.startswith('pywbem.'):
            if tx == 'boolean':
                tx = 'bool(%s)' % defval
            elif tx == 'datetime':
                tx = 'pywbem.CIMDateTime()'
            elif tx == 'string':
                tx = "''"
            else:
                tx = 'pywbem.%s(%s)' % (tx.capitalize(), defval)
        if 'valuemap' in obj.qualifiers:
            if defval:
                defval = map_value(obj, defval)
            else:
                defval = '<VAL>'
            tx = 'self.Values.%s%s.%s' % \
                    (method_name and '%s.'%method_name or '',
                     obj.name, defval)
        if hasattr(obj, 'is_array') and obj.is_array:
            tx = '[%s,]' % tx
        return tx
    #################
    def type_str(obj, method_name=None):
        if hasattr(obj, 'type'):
            tx = obj.type
            if 'embeddedinstance' in obj.qualifiers:
                return "pywbem.CIMInstance(classname='%s', ...)" % \
                        obj.qualifiers['embeddedinstance'].value
            elif tx == 'reference':
                return "REF (pywbem.CIMInstanceName(classname='%s', ...)" % \
                        obj.reference_class
        else:
            tx = obj.return_type
        if tx == 'boolean':
            tx = 'bool'
        elif tx == 'datetime':
            tx = 'pywbem.CIMDateTime'
        elif tx == 'string':
            tx = 'unicode'
        else:
            tx = 'pywbem.%s' % tx.capitalize()
        if hasattr(obj, 'is_array') and obj.is_array:
            tx = '[%s,]' % tx
        if 'valuemap' in obj.qualifiers:
            tx += ' self.Values.%s%s' % \
                    (method_name and '%s.' % method_name or '', obj.name)
        return tx
    #################
    def is_required(obj):
        if 'required' in obj.qualifiers and obj.qualifiers['required'].value:
            return '(Required)'
        return ''
    #################
    def build_val_map(obj):
        vm = obj.qualifiers['valuemap'].value
        if 'values' in obj.qualifiers:
            vals = obj.qualifiers['values'].value
        else:
            vals = vm
        tmap = zip(vals, vm)
        map = []
        for t in tmap:
            nname = ''
            for ch in t[0]:
                if ch.isalnum():
                    nname += ch
                else:
                    nname += '_'
            if hasattr(obj, 'return_type'):
                tp = obj.return_type
            else:
                tp = obj.type
            if tp == 'string':
                val = "'%s'" % t[1]
            else:
                try:
                    int(t[1])
                    val = 'pywbem.%s(%s)' % (tp.capitalize(), t[1])
                except ValueError:
                    val = t[1]
                    nname = "# "+nname
            map.append((nname, val))
        return map

    valuemaps = {}

    for obj in cc.properties.values() + cc.methods.values():
        if 'valuemap' in obj.qualifiers:
            valuemaps[obj.name] = {'<vms>':build_val_map(obj)}

    for meth in cc.methods.values():
        for parm in meth.parameters.values():
            if 'valuemap' in parm.qualifiers:
                if meth.name not in valuemaps:
                    valuemaps[meth.name] = {}
                valuemaps[meth.name][parm.name] = build_val_map(parm)

    mappings = {'classname':cc.classname,
                'classname_l':cc.classname.lower()}
    isAssoc = 'association' in cc.qualifiers

    code = '''"""Python Provider for %(classname)s

Instruments the CIM class %(classname)s

"""

import pywbem

class %(classname)sProvider(pywbem.CIMProvider):
    """Instrument the CIM class %(classname)s \n''' % mappings
    code += format_desc(cc, 4)
    code += '''
    """'''


    args = inspect.getargspec(CIMProvider.get_instance)[0]
    args = ', '.join(args)
    code += '''

    def __init__ (self, env):
        logger = env.get_logger()
        logger.log_debug('Initializing provider %%s from %%s' \\
                %% (self.__class__.__name__, __file__))
        # If you will be filtering instances yourself according to
        # property_list, role, result_role, and result_class_name
        # parameters, set self.filter_results to False
        # self.filter_results = False

    def get_instance(%s):
        """%s"""

        logger = env.get_logger()
        logger.log_debug('Entering %%s.get_instance()' \\
                %% self.__class__.__name__)
        ''' % (args, CIMProvider.get_instance.__doc__)
    keyProps = [p for p in cc.properties.values() \
                if 'key' in p.qualifiers]
    code += '''
        ux = model.update_existing

        # TODO fetch system resource matching the following keys:'''
    for kp in keyProps:
        code += '''
        #   model['%s']''' % kp.name
    code += '\n'
    props = cc.properties.values()
    props.sort()
    for prop in props:
        if 'key' in prop.qualifiers:
            continue
        #line = "#ux(%s=%s) # TODO (type = %s) %s" % \
        #        (prop.name, type_hint(prop), type_str(prop), is_required(prop))
        line = "#ux(%s=%s) # TODO %s" % \
                (prop.name, type_hint(prop), is_required(prop))
        code += '''
        %s''' % line

    args = inspect.getargspec(CIMProvider.enum_instances)[0]
    args = ', '.join(args)
    code += '''
        return model

    def enum_instances(%s):
        """%s"""

        logger = env.get_logger()
        logger.log_debug('Entering %%s.enum_instances()' \\
                %% self.__class__.__name__)

        while False: # TODO more instances?
            # TODO fetch system resource
            # Key properties''' % (args, CIMProvider.enum_instances.__doc__)
    for kp in keyProps:
        if kp.name == 'CreationClassName':
            line = "model['%s'] = '%s'" % (kp.name, cc.classname)
        else:
            line = "#model['%s'] = # TODO (type = %s)" % \
                    (kp.name, type_str(kp))
        code += '''
            %s''' % line
    code += '''
            if keys_only:
                yield model
            else:
                try:
                    yield self.get_instance(env, model, cim_class)
                except pywbem.CIMError as exc:
                    num, msg = exc.args
                    if num not in (pywbem.CIM_ERR_NOT_FOUND,
                                   pywbem.CIM_ERR_ACCESS_DENIED):
                        raise\n'''

    args = inspect.getargspec(CIMProvider.set_instance)[0]
    args = ', '.join(args)
    code += '''
    def set_instance(%s):
        """%s"""

        logger = env.get_logger()
        logger.log_debug('Entering %%s.set_instance()' \\
                %% self.__class__.__name__)
        # TODO create or modify the instance
        raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED) # Remove to implement
        return instance''' % (args, CIMProvider.set_instance.__doc__)

    args = inspect.getargspec(CIMProvider.delete_instance)[0]
    args = ', '.join(args)
    code += '''

    def delete_instance(%s):
        """%s"""

        logger = env.get_logger()
        logger.log_debug('Entering %%s.delete_instance()' \\
                %% self.__class__.__name__)

        # TODO delete the resource
        raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED) # Remove to implement
        ''' % (args, CIMProvider.delete_instance.__doc__)

    for method in cc.methods.values():
        inParms = [p for p in method.parameters.values() if \
                    'in' in p.qualifiers and p.qualifiers['in'].value]
        outParms = [p for p in method.parameters.values() if \
                    'out' in p.qualifiers and p.qualifiers['out'].value]
        code += '''
    def cim_method_%s(self, env, object_name, method''' % method.name.lower()
        for p in inParms:
            code += ''',\n%sparam_%s''' % (''.rjust(len(method.name)+20),
                                           p.name.lower())
        code += '''):
        """Implements %s.%s()\n''' % (cc.classname, method.name)
        code += format_desc(method, 8)

        code += '''
        Keyword arguments:
        env -- Provider Environment (pycimmb.ProviderEnvironment)
        object_name -- A pywbem.CIMInstanceName or pywbem.CIMCLassName
            specifying the object on which the method %s()
            should be invoked.
        method -- A pywbem.CIMMethod representing the method meta-data''' \
                % method.name

        for p in inParms:
            code += '''
        param_%s --  The input parameter %s (type %s) %s''' \
                    % (p.name.lower(), p.name, type_str(p, method.name),
                       is_required(p))
            code += format_desc(p, 12)

        code += '''

        Returns a two-tuple containing the return value (type %s)
        and a dictionary with the out-parameters

        Output parameters:''' % type_str(method)

        if not outParms:
            code += ' none'
        else:
            for p in outParms:
                code += '''
        %s -- (type %s) %s''' % (p.name, type_str(p, method.name),
                                 is_required(p))
                code += format_desc(p, 12)

        code += '''

        Possible Errors:
        CIM_ERR_ACCESS_DENIED
        CIM_ERR_INVALID_PARAMETER (including missing, duplicate,
            unrecognized or otherwise incorrect parameters)
        CIM_ERR_NOT_FOUND (the target CIM Class or instance does not
            exist in the specified namespace)
        CIM_ERR_METHOD_NOT_AVAILABLE (the CIM Server is unable to honor
            the invocation request)
        CIM_ERR_FAILED (some other unspecified error occurred)

        """

        logger = env.get_logger()
        logger.log_debug('Entering %%s.cim_method_%s()' \\
                %% self.__class__.__name__)

        # TODO do something
        raise pywbem.CIMError(pywbem.CIM_ERR_METHOD_NOT_AVAILABLE) # Remove to implemented
        out_params = {}''' % method.name.lower()

        for p in outParms:
            code += '''
        #out_params['%s'] = %s # TODO''' % \
                (p.name.lower(), type_hint(p, method.name))

        code += '''
        rval = None # TODO (type %s)
        return (rval, out_params)
        ''' % type_str(method)

    if isAssoc:
        args = inspect.getargspec(CIMProvider.references)[0]
        args = format_desc(', '.join(args), 19).strip()
        code += '''
    def references(%s):
        """%s"""

        logger = env.get_logger()
        logger.log_debug('Entering %%s.references()' \\
                %% self.__class__.__name__)
        ch = env.get_cimom_handle()
        # This is a common pattern.  YMMV''' % \
                (args, CIMProvider.references.__doc__)
        refprops = []
        for prop in cc.properties.values():
            if prop.reference_class is not None:
                refprops.append((prop.name, prop.reference_class))
        for refprop in refprops:
            code += '''
        if (not role or role.lower() == '%(refpropnamel)s') and \\
           pywbem.is_subclass(ch, object_name.namespace,
                       sub=object_name.classname,
                       super='%(rolecname)s'):
            model['%(refpropname)s'] = object_name
            yield model # TODO: Add other REF properties.
                        # Yield association instances where
                        # object_name is %(refpropnamel)s.
                        # Only appropriate if object_name.classname
                        # is '%(rolecname)s' or a subclass.\n''' \
                               % {'refpropname':refprop[0],
                                  'refpropnamel':refprop[0].lower(),
                                  'rolecname':refprop[1]}

    if valuemaps:
        code += '''
    class Values(object):'''
        for group, maps in valuemaps.items():
            code += '''
        class %s(object):''' % group
            if '<vms>' in maps:
                for value, vm in maps['<vms>']:
                    if value in maps:
                        value = value+'_'
                    code += '''
            %s = %s''' % (value, vm)
            for pname, vms in maps.items():
                if pname == '<vms>':
                    continue
                code += '''
            class %s(object):''' % pname
                for value, vm in vms:
                    code += '''
                %s = %s''' % (value, vm)
            code += '\n'

    code += '''
## end of class %(classname)sProvider

def get_providers(env):
    %(classname_l)s_prov = %(classname)sProvider(env)
    return {'%(classname)s': %(classname_l)s_prov}
''' % mappings

    owtypes = ['1', 'Instance']
    pegtypes = ['2', 'Instance']
    if isAssoc:
        owtypes[0] += ',3'
        owtypes[1] += ', Associator'
        pegtypes[0] += ',3'
        pegtypes[1] += ', Associator'
    if cc.methods:
        owtypes[0] += ',6'
        owtypes[1] += ', Method'
        pegtypes[0] += ',5'
        pegtypes[1] += ', Method'
    mof = '''
// OpenWBEM Provider registration for %(classname)s
instance of OpenWBEM_PyProviderRegistration
{
    InstanceID = "<org:product:%(classname)s:unique_id>"; // TODO
    NamespaceNames = {"root/cimv2"}; // TODO
    ClassName = "%(classname)s";
    ProviderTypes = {%(owtypeNums)s};  // %(owtypeStrs)s
    ModulePath = "/usr/lib/pycim/%(classname)sProvider.py";  // TODO
};

// Pegasus Provider registration for %(classname)s
instance of PG_ProviderModule
{
    Name = "/usr/lib/pycim/%(classname)sProvider.py";
    InterfaceType = "Python";
    InterfaceVersion = "1.0.0";
    Location = "/usr/lib/pycim/%(classname)sProvider.py";
    UserContext = 2; // Requestor
    Vendor = "TODO"; // TODO
    Version = "1.0";
};
instance of PG_Provider
{
    Name = "%(classname)s";
    ProviderModuleName = "/usr/lib/pycim/%(classname)sProvider.py";
};
instance of PG_ProviderCapabilities
{
    CapabilityID = "%(classname)s";
    ProviderModuleName = "/usr/lib/pycim/%(classname)sProvider.py";
    ProviderName = "%(classname)s";
    ClassName = "%(classname)s";
    Namespaces = {"root/cimv2"}; // TODO
    ProviderType = {%(pegtypeNum)s}; // %(pegtypeStr)s
};\n''' % {'classname': cc.classname,
           'owtypeNums': owtypes[0],
           'owtypeStrs': owtypes[1],
           'pegtypeNum': pegtypes[0],
           'pegtypeStr': pegtypes[1]}


    return code, mof
5035
function getCodeMap(node) {
    const code_map = node.toStringWithSourceMap();

    // patch
    node.walkSourceContents(function (sourceFile, sourceContent) {
        if (!code_map.map._sources.has(sourceFile)) {
            code_map.map._sources.add(sourceFile);
        }
    });

    return code_map;
}
881187
function generateCodeDocs() {
  config.codeFiles.forEach(function (jsFile) {
    var jf = [jsFile];
    documentation(jf, {}, function (err, result) {
      documentation.formats.md(result, {}, function (err, md) {
        // Write to file
        fs.writeFile(path.resolve(__dirname, config.docFolder + "/" + jsFile + ".md"), md);
      });
    });
  });
}