text:
package org.manufacturingoot.view;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.persistence.EntityManagerFactory;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.manufacturingoot.model.ManufacturingOrder;
import org.manufacturingoot.model.Product;
import org.manufacturingoot.model.ProductionDepartment;
import org.manufacturingoot.service.ManufacturingOrderService;
import org.manufacturingoot.service.PartService;
import org.manufacturingoot.service.ProductService;
import org.manufacturingoot.util.SessionUtil;

public class ProductForm extends javax.swing.JFrame {

    private ManufacturingOrder currentOrder;
    private Product currentItem;
    private EntityManagerFactory emf;
    private boolean updateData;

    private ManufacturingOrderService mos;

    public ProductForm(EntityManagerFactory emf, Product mo) {
        initComponents();
        this.emf = emf;
        currentItem = mo;
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        mos = new ManufacturingOrderService(emf);
        loadComboManufacturing();
        prepareForm();

        setLocationRelativeTo(null);
    }

    private void loadComboManufacturing() {
        for (ManufacturingOrder mo : mos.findManufacturingOrderEntities()) {
            comboManufacturing.addItem(mo);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        buttonSave = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        textId = new javax.swing.JTextField();
        comboManufacturing = new javax.swing.JComboBox();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        textName = new javax.swing.JTextField();
        textPrice = new javax.swing.JTextField();
        textWeight = new javax.swing.JTextField();
        textCost = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        buttonPart = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Work Schedule");

        jLabel2.setText("Manufacturing Order");

        jLabel4.setText("Weight");

        buttonSave.setText("Save");
        buttonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSaveActionPerformed(evt);
            }
        });

        jLabel6.setText("Id");

        textId.setEnabled(false);

        comboManufacturing.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboManufacturingActionPerformed(evt);
            }
        });

        jLabel7.setText("Name");

        jLabel8.setText("Price");

        textPrice.setText("0");

        textWeight.setText("0");

        textCost.setText("0");
        textCost.setEnabled(false);

        jLabel3.setText("Cost");

        buttonPart.setText("Set Parts");
        buttonPart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonPartActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(buttonSave))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel2)
                            .addComponent(jLabel6)
                            .addComponent(jLabel1)
                            .addComponent(jLabel7)
                            .addComponent(jLabel8)
                            .addComponent(jLabel3))
                        .addGap(16, 16, 16)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(textId)
                            .addComponent(comboManufacturing, 0, 300, Short.MAX_VALUE)
                            .addComponent(textName)
                            .addComponent(textPrice)
                            .addComponent(textWeight)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(textCost)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(buttonPart)))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(textId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(comboManufacturing, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(textName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(textPrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(textWeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textCost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(buttonPart))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
                .addComponent(buttonSave)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 456, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 254, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSaveActionPerformed
        if (textPrice.getText().equals("0")) {
            JOptionPane.showMessageDialog(null, "Harga tidak boleh 0");
            return;
        }

        ProductService ps = new ProductService(emf);

        if (currentItem != null) {
            loadForm();
            try {
                ps.edit(currentItem);
            } catch (Exception ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(null, "Gagal melakukan update");
            }
        } else {
            currentItem = new Product();
            loadForm();
            ps.create(currentItem);
        }

        WindowEvent event = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
        dispatchEvent(event);
    }//GEN-LAST:event_buttonSaveActionPerformed

    private void comboManufacturingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboManufacturingActionPerformed
        currentOrder = mos.findManufacturingOrderByColumn(
                "email", comboManufacturing.getSelectedItem().toString());
        System.out.println(currentOrder);
    }//GEN-LAST:event_comboManufacturingActionPerformed

    private void openForm() {
        ChoosePartPanel partPanel = new ChoosePartPanel(emf, currentItem);
        partPanel.setVisible(true);
        partPanel.addWindowListener(closeWindowAdapter());
    }

    private void buttonPartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonPartActionPerformed
        PartService partService = new PartService(emf);
        if (partService.getPartCount() > 0) {
            if (currentItem.getId() == null) {
                ProductService ps = new ProductService(emf);
                loadForm();
                ps.create(currentItem);
            }
            openForm();
        } else {
            JOptionPane.showMessageDialog(null, "Tidak ada part yang terdaftar");
        }
    }//GEN-LAST:event_buttonPartActionPerformed

    private void loadForm() {
        currentItem.setName(textName.getText());
        currentItem.setPrice(Double.parseDouble(textPrice.getText()));
        currentItem.setProductionCost(Double.parseDouble(textCost.getText()));
        currentItem.setWeight(Double.parseDouble(textWeight.getText()));
        currentItem.setOrder(currentOrder);
        currentItem.setCreatedBy((ProductionDepartment) SessionUtil.getSession());
    }

    private void prepareForm() {
        if (currentItem == null) {
            currentItem = new Product();
        } else {
            textId.setText(currentItem.getId().toString());
            textName.setText(currentItem.getName());
            textPrice.setText(currentItem.getPrice().toString());
            textCost.setText(currentItem.getProductionCost().toString());
            textWeight.setText(currentItem.getWeight().toString());
            comboManufacturing.setSelectedItem(currentItem.getOrder());
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonPart;
    private javax.swing.JButton buttonSave;
    private javax.swing.JComboBox comboManufacturing;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField textCost;
    private javax.swing.JTextField textId;
    private javax.swing.JTextField textName;
    private javax.swing.JTextField textPrice;
    private javax.swing.JTextField textWeight;
    // End of variables declaration//GEN-END:variables

    private WindowListener closeWindowAdapter() {
        return new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e); //To change body of generated methods, choose Tools | Templates.
                textCost.setText(currentItem.getProductionCost().toString());
                textPrice.setText(textCost.getText());
            }
        };
    }
}


text:
{% macro html5_date(date, format='%B %d, %Y', pubdate=True) -%}
    <time datetime="{{ date.isoformat() }}" {{ 'pubdate' if pubdate }}>
        {{- date.strftime(format) }}</time>
{%- endmacro %}

{% macro article_list(articles) %}
{% if articles %}

  {% for article in articles %}

{{ article.title }}

{{ html5_date(article.published) }}

      {{ article.summary|default|markdown|safe }}

Read more…

  {% endfor %}

{% endif %}
{% endmacro %}

redpajama_set_name: RedPajamaGithub


text:
package com.google.errorprone.refaster;

import static java.util.logging.Level.FINE;

import com.google.common.base.Optional;
import com.google.common.collect.ImmutableClassToInstanceMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Ordering;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.refaster.PlaceholderMethod.PlaceholderExpressionKey;
import com.google.errorprone.refaster.UTypeVar.TypeWithExpression;
import com.google.errorprone.refaster.annotation.NoAutoboxing;
import com.sun.source.tree.Tree.Kind;
import com.sun.tools.javac.code.Kinds.KindSelector;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.ForAll;
import com.sun.tools.javac.code.Type.MethodType;
import com.sun.tools.javac.code.TypeTag;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.comp.Attr;
import com.sun.tools.javac.comp.AttrContext;
import com.sun.tools.javac.comp.Enter;
import com.sun.tools.javac.comp.Env;
import com.sun.tools.javac.comp.Resolve;
import com.sun.tools.javac.tree.EndPosTable;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCCatch;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCExpressionStatement;
import com.sun.tools.javac.tree.JCTree.JCLambda;
import com.sun.tools.javac.tree.JCTree.JCLiteral;
import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
import com.sun.tools.javac.tree.JCTree.JCTry;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.tree.Pretty;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.JCDiagnostic;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.Position;
import com.sun.tools.javac.util.Warner;
import java.io.IOException;
import java.io.Serializable;
import java.io.UncheckedIOException;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.logging.Logger;
import javax.annotation.Nullable;

/**
 * Abstract superclass for templates that can be used to search and replace in a Java syntax tree.
 *
 * @author lowasser@google.com (Louis Wasserman)
 * @param <M> Type of a match for this template.
 */
public abstract class Template<M extends TemplateMatch> implements Serializable {
  private static final Logger logger = Logger.getLogger(Template.class.toString());

  public static final boolean AUTOBOXING_DEFAULT = true;

  public abstract ImmutableClassToInstanceMap<Annotation> annotations();

  public abstract ImmutableList<UTypeVar> templateTypeVariables();

  public abstract ImmutableMap<String, UType> expressionArgumentTypes();

  public abstract Iterable<M> match(JCTree tree, Context context);

  public abstract Fix replace(M match);

  Iterable<UTypeVar> typeVariables(Context context) {
    ImmutableList<UTypeVar> ruleTypeVars = context.get(RefasterRule.RULE_TYPE_VARS);
    return Iterables.concat(
        (ruleTypeVars == null) ? ImmutableList.<UTypeVar>of() : ruleTypeVars,
        templateTypeVariables());
  }

  boolean autoboxing() {
    return !annotations().containsKey(NoAutoboxing.class);
  }

  /**
   * Returns a list of the expected types to be matched. This consists of the argument types from
   * the @BeforeTemplate method, concatenated with the return types of expression placeholders,
   * sorted by the name of the placeholder method.
   *
   * @throws CouldNotResolveImportException if a referenced type could not be resolved
   */
  protected List<Type> expectedTypes(Inliner inliner) throws CouldNotResolveImportException {
    ArrayList<Type> result = new ArrayList<>();
    ImmutableList<UType> types = expressionArgumentTypes().values().asList();
    ImmutableList<String> argNames = expressionArgumentTypes().keySet().asList();
    for (int i = 0; i < argNames.size(); i++) {
      String argName = argNames.get(i);
      Optional<JCExpression> singleBinding =
          inliner.getOptionalBinding(new UFreeIdent.Key(argName));
      if (!singleBinding.isPresent()) {
        Optional<java.util.List<JCExpression>> exprs =
            inliner.getOptionalBinding(new URepeated.Key(argName));
        if (!exprs.isPresent() || exprs.get().isEmpty()) {
          // It is a repeated template variable and matches no expressions.
          continue;
        }
      }
      result.add(types.get(i).inline(inliner));
    }
    for (PlaceholderExpressionKey key :
        Ordering.natural()
            .immutableSortedCopy(
                Iterables.filter(inliner.bindings.keySet(), PlaceholderExpressionKey.class))) {
      Type type = key.method.returnType().inline(inliner);
      // Skip void placeholder expressions, because
      // a) if the expected type is void, any actual type is acceptable
      // b) these types are used as the argument types in a synthetic MethodType, and method
      //    argument types cannot be void
      if (!type.getTag().equals(TypeTag.VOID)) {
        result.add(type);
      }
    }
    return List.from(result);
  }

  /**
   * Returns a list of the actual types to be matched. This consists of the types of the expressions
   * bound to the @BeforeTemplate method parameters, concatenated with the types of the expressions
   * bound to expression placeholders, sorted by the name of the placeholder method.
   */
  protected List<Type> actualTypes(Inliner inliner) throws CouldNotResolveImportException {
    ArrayList<Type> result = new ArrayList<>();
    ImmutableList<String> argNames = expressionArgumentTypes().keySet().asList();
    for (int i = 0; i < expressionArgumentTypes().size(); i++) {
      String argName = argNames.get(i);
      Optional<JCExpression> singleBinding =
          inliner.getOptionalBinding(new UFreeIdent.Key(argName));
      if (singleBinding.isPresent()) {
        result.add(singleBinding.get().type);
      } else {
        Optional<java.util.List<JCExpression>> exprs =
            inliner.getOptionalBinding(new URepeated.Key(argName));
        if (exprs.isPresent() && !exprs.get().isEmpty()) {
          Type[] exprTys = new Type[exprs.get().size()];
          for (int j = 0; j < exprs.get().size(); j++) {
            exprTys[j] = exprs.get().get(j).type;
          }
          // Get the least upper bound of the types of all expressions that the argument matches.
          // In the special case where exprs is empty, returns the "bottom" type, which is a
          // subtype of everything.
          result.add(inliner.types().lub(List.from(exprTys)));
        }
      }
    }
    for (PlaceholderExpressionKey key :
        Ordering.natural()
            .immutableSortedCopy(
                Iterables.filter(inliner.bindings.keySet(), PlaceholderExpressionKey.class))) {
      Type keyType = key.method.returnType().inline(inliner);
      // See comment in `expectedTypes` for why we skip void placeholder keys.
      if (!keyType.getTag().equals(TypeTag.VOID)) {
        result.add(inliner.getBinding(key).type);
      }
    }
    return List.from(result);
  }

  @Nullable
  protected Optional<Unifier> typecheck(
      Unifier unifier,
      Inliner inliner,
      Warner warner,
      List<Type> expectedTypes,
      List<Type> actualTypes) {
    try {
      ImmutableList<UTypeVar> freeTypeVars = freeTypeVars(unifier);
      infer(
          warner,
          inliner,
          inliner.<Type>inlineList(freeTypeVars),
          expectedTypes,
          inliner.symtab().voidType,
          actualTypes);

      for (UTypeVar var : freeTypeVars) {
        Type instantiationForVar =
            infer(
                warner,
                inliner,
                inliner.<Type>inlineList(freeTypeVars),
                expectedTypes,
                var.inline(inliner),
                actualTypes);
        unifier.putBinding(
            var.key(), TypeWithExpression.create(instantiationForVar.getReturnType()));
      }

      if (!checkBounds(unifier, inliner, warner)) {
        return Optional.absent();
      }
      return Optional.of(unifier);
    } catch (CouldNotResolveImportException e) {
      logger.log(FINE, "Failure to resolve an import", e);
      return Optional.absent();
    } catch (InferException e) {
      logger.log(FINE, "No valid instantiation found: " + e.getMessage());
      return Optional.absent();
    }
  }

  private boolean checkBounds(Unifier unifier, Inliner inliner, Warner warner)
      throws CouldNotResolveImportException {
    Types types = unifier.types();
    ListBuffer<Type> varsBuffer = new ListBuffer<>();
    ListBuffer<Type> bindingsBuffer = new ListBuffer<>();
    for (UTypeVar typeVar : typeVariables(unifier.getContext())) {
      varsBuffer.add(inliner.inlineAsVar(typeVar));
      bindingsBuffer.add(unifier.getBinding(typeVar.key()).type());
    }
    List<Type> vars = varsBuffer.toList();
    List<Type> bindings = bindingsBuffer.toList();
    for (UTypeVar typeVar : typeVariables(unifier.getContext())) {
      List<Type> bounds = types.getBounds(inliner.inlineAsVar(typeVar));
      bounds = types.subst(bounds, vars, bindings);
      if (!types.isSubtypeUnchecked(unifier.getBinding(typeVar.key()).type(), bounds, warner)) {
        logger.log(
            FINE,
            String.format("%s is not a subtype of %s", inliner.getBinding(typeVar.key()), bounds));
        return false;
      }
    }
    return true;
  }

  protected static Pretty pretty(Context context, Writer writer) {
    JCCompilationUnit unit = context.get(JCCompilationUnit.class);
    try {
      String unitContents = unit.getSourceFile().getCharContent(false).toString();
      return new Pretty(writer, true) {
        {
          // Work-around for b/22196513
          width = 0;
        }

        @Override
        public void visitAnnotation(JCAnnotation anno) {
          if (anno.getArguments().isEmpty()) {
            try {
              print("@");
              printExpr(anno.annotationType);
            } catch (IOException e) {
              // the supertype swallows exceptions too
              throw new RuntimeException(e);
            }
          } else {
            super.visitAnnotation(anno);
          }
        }

        @Override
        public void printExpr(JCTree tree, int prec) throws IOException {
          EndPosTable endPositions = unit.endPositions;
          /*
           * Modifiers, and specifically flags like final, appear to just need weird special
           * handling.
           *
           * Note: we can't use {@code TreeInfo.getEndPos()} or {@code JCTree.getEndPosition()}
           * here, because they will return the end position of an enclosing AST node for trees
           * whose real end positions aren't stored.
           */
          int endPos = endPositions.getEndPos(tree);
          boolean hasRealEndPosition = endPos != Position.NOPOS;
          if (tree.getKind() != Kind.MODIFIERS && hasRealEndPosition) {
            writer.append(unitContents.substring(tree.getStartPosition(), endPos));
          } else {
            super.printExpr(tree, prec);
          }
        }

        @Override
        public void visitApply(JCMethodInvocation tree) {
          JCExpression select = tree.getMethodSelect();
          if (select != null && select.toString().equals("Refaster.emitCommentBefore")) {
            String commentLiteral = (String) ((JCLiteral) tree.getArguments().get(0)).getValue();
            JCExpression expr = tree.getArguments().get(1);
            try {
              print("/* " + commentLiteral + " */ ");
            } catch (IOException e) {
              throw new RuntimeException(e);
            }
            expr.accept(this);
          } else {
            super.visitApply(tree);
          }
        }

        @Override
        public void printStat(JCTree tree) throws IOException {
          if (tree instanceof JCExpressionStatement
              && ((JCExpressionStatement) tree).getExpression() instanceof JCMethodInvocation) {
            JCMethodInvocation invocation =
                (JCMethodInvocation) ((JCExpressionStatement) tree).getExpression();
            JCExpression select = invocation.getMethodSelect();
            if (select != null && select.toString().equals("Refaster.emitComment")) {
              String commentLiteral =
                  (String) ((JCLiteral) invocation.getArguments().get(0)).getValue();
              print("// " + commentLiteral);
              return;
            }
          }
          super.printStat(tree);
        }

        // Don't print parentheses around single lambda parameters without an explicit type.
        @Override
        public void visitLambda(JCLambda lambda) {
          try {
            boolean exactlyOneParamWithNoType =
                lambda.params.size() == 1 && lambda.params.get(0).vartype == null;
            if (!exactlyOneParamWithNoType) {
              print("(");
            }
            boolean first = true;
            for (JCVariableDecl param : lambda.params) {
              if (!first) {
                print(",");
              }
              if (param.vartype != null) {
                if (!first) {
                  print(" ");
                }
                print(param.vartype + " ");
              }
              print(param.name);
              first = false;
            }
            if (!exactlyOneParamWithNoType) {
              print(")");
            }
            print("->");
            printExpr(lambda.body);
          } catch (IOException e) {
            throw new UncheckedIOException(e);
          }
        }

        @Override
        public void visitTry(JCTry tree) {
          if (tree.getResources().isEmpty()) {
            super.visitTry(tree);
            return;
          }
          try {
            print("try (");
            boolean first = true;
            for (JCTree resource : tree.getResources()) {
              if (!first) {
                print(";");
                println();
              }
              printExpr(resource);
              first = false;
            }
            print(")");
            printStat(tree.body);
            for (JCCatch catchStmt : tree.getCatches()) {
              printStat(catchStmt);
            }
            if (tree.getFinallyBlock() != null) {
              print(" finally ");
              printStat(tree.getFinallyBlock());
            }
          } catch (IOException e) {
            throw new RuntimeException(e);
          }
        }
      };
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  private static class InferException extends Exception {
    final Collection<JCDiagnostic> diagnostics;

    public InferException(Collection<JCDiagnostic> diagnostics) {
      this.diagnostics = diagnostics;
    }

    @Override
    public String getMessage() {
      return "Inference failed with the following error(s): " + diagnostics;
    }
  }

  /**
   * Returns the inferred method type of the template based on the given actual argument types.
   *
   * @throws InferException if no instances of the specified type variables would allow the {@code
   *     actualArgTypes} to match the {@code expectedArgTypes}
   */
  private Type infer(
      Warner warner,
      Inliner inliner,
      List<Type> freeTypeVariables,
      List<Type> expectedArgTypes,
      Type returnType,
      List<Type> actualArgTypes)
      throws InferException {
    Symtab symtab = inliner.symtab();

    Type methodType =
        new MethodType(expectedArgTypes, returnType, List.<Type>nil(), symtab.methodClass);
    if (!freeTypeVariables.isEmpty()) {
      methodType = new ForAll(freeTypeVariables, methodType);
    }

    Enter enter = inliner.enter();
    MethodSymbol methodSymbol =
        new MethodSymbol(0, inliner.asName("__m__"), methodType, symtab.unknownSymbol);

    Type site = symtab.methodClass.type;

    Env<AttrContext> env =
        enter.getTopLevelEnv(TreeMaker.instance(inliner.getContext()).TopLevel(List.<JCTree>nil()));

    // Set up the resolution phase:
    try {
      Field field = AttrContext.class.getDeclaredField("pendingResolutionPhase");
      field.setAccessible(true);
      field.set(env.info, newMethodResolutionPhase(autoboxing()));
    } catch (ReflectiveOperationException e) {
      throw new LinkageError(e.getMessage(), e);
    }

    Object resultInfo;
    try {
      Class<?> resultInfoClass = Class.forName("com.sun.tools.javac.comp.Attr$ResultInfo");
      Constructor<?> resultInfoCtor =
          resultInfoClass.getDeclaredConstructor(Attr.class, KindSelector.class, Type.class);
      resultInfoCtor.setAccessible(true);
      resultInfo =
          resultInfoCtor.newInstance(
              Attr.instance(inliner.getContext()), KindSelector.PCK, Type.noType);
    } catch (ReflectiveOperationException e) {
      throw new LinkageError(e.getMessage(), e);
    }

    // Type inference sometimes produces diagnostics, so we need to catch them to avoid interfering
    // with the enclosing compilation.
    Log.DeferredDiagnosticHandler handler =
        new Log.DeferredDiagnosticHandler(Log.instance(inliner.getContext()));
    try {
      MethodType result =
          callCheckMethod(warner, inliner, resultInfo, actualArgTypes, methodSymbol, site, env);
      if (!handler.getDiagnostics().isEmpty()) {
        throw new InferException(handler.getDiagnostics());
      }
      return result;
    } finally {
      Log.instance(inliner.getContext()).popDiagnosticHandler(handler);
    }
  }

  /** Reflectively instantiate the package-private {@code MethodResolutionPhase} enum. */
  @Nullable
  private static Object newMethodResolutionPhase(boolean autoboxing) {
    for (Class<?> c : Resolve.class.getDeclaredClasses()) {
      if (!c.getName().equals("com.sun.tools.javac.comp.Resolve$MethodResolutionPhase")) {
        continue;
      }
      for (Object e : c.getEnumConstants()) {
        if (e.toString().equals(autoboxing ? "BOX" : "BASIC")) {
          return e;
        }
      }
    }
    return null;
  }

  /**
   * Reflectively invoke Resolve.checkMethod(), which despite being package-private is apparently
   * the only useful entry-point into javac8's type inference implementation.
   */
  private MethodType callCheckMethod(
      Warner warner,
      Inliner inliner,
      Object resultInfo,
      List<Type> actualArgTypes,
      MethodSymbol methodSymbol,
      Type site,
      Env<AttrContext> env)
      throws InferException {
    try {
      Method checkMethod;
      checkMethod =
          Resolve.class.getDeclaredMethod(
              "checkMethod",
              Env.class,
              Type.class,
              Symbol.class,
              Class.forName(
                  "com.sun.tools.javac.comp.Attr$ResultInfo"), // ResultInfo is package-private
              List.class,
              List.class,
              Warner.class);
      checkMethod.setAccessible(true);
      return (MethodType)
          checkMethod.invoke(
              Resolve.instance(inliner.getContext()),
              env,
              site,
              methodSymbol,
              resultInfo,
              actualArgTypes,
              /* freeTypeVariables */ List.<Type>nil(),
              warner);
    } catch (InvocationTargetException e) {
      if (e.getCause() instanceof Resolve.InapplicableMethodException) {
        throw new InferException(
            ImmutableList.of(
                ((Resolve.InapplicableMethodException) e.getTargetException()).getDiagnostic()));
      }
      throw new LinkageError(e.getMessage(), e.getCause());
    } catch (ReflectiveOperationException e) {
      throw new LinkageError(e.getMessage(), e);
    }
  }

  /**
   * Returns a list of the elements of {@code typeVariables} that are <em>not</em> bound in the
   * specified {@link Unifier}.
   */
  private ImmutableList<UTypeVar> freeTypeVars(Unifier unifier) {
    ImmutableList.Builder<UTypeVar> builder = ImmutableList.builder();
    for (UTypeVar var : typeVariables(unifier.getContext())) {
      if (unifier.getBinding(var.key()) == null) {
        builder.add(var);
      }
    }
    return builder.build();
  }

  protected static Fix addImports(Inliner inliner, SuggestedFix.Builder fix) {
    for (String importToAdd : inliner.getImportsToAdd()) {
      fix.addImport(importToAdd);
    }
    for (String staticImportToAdd : inliner.getStaticImportsToAdd()) {
      fix.addStaticImport(staticImportToAdd);
    }
    return fix.build();
  }
}


text:
from pyspark import keyword_only, since
from pyspark.ml.util import *
from pyspark.ml.wrapper import JavaEstimator, JavaModel
from pyspark.ml.param.shared import *

__all__ = ["FPGrowth", "FPGrowthModel"]

class HasMinSupport(Params):
    """
    Mixin for param minSupport.
    """

    minSupport = Param(
        Params._dummy(),
        "minSupport",
        "Minimal support level of the frequent pattern. [0.0, 1.0]. " +
        "Any pattern that appears more than (minSupport * size-of-the-dataset) " +
        "times will be output in the frequent itemsets.",
        typeConverter=TypeConverters.toFloat)

    def setMinSupport(self, value):
        """
        Sets the value of :py:attr:`minSupport`.
        """
        return self._set(minSupport=value)

    def getMinSupport(self):
        """
        Gets the value of minSupport or its default value.
        """
        return self.getOrDefault(self.minSupport)

class HasNumPartitions(Params):
    """
    Mixin for param numPartitions: Number of partitions (at least 1) used by parallel FP-growth.
    """

    numPartitions = Param(
        Params._dummy(),
        "numPartitions",
        "Number of partitions (at least 1) used by parallel FP-growth. " +
        "By default the param is not set, " +
        "and partition number of the input dataset is used.",
        typeConverter=TypeConverters.toInt)

    def setNumPartitions(self, value):
        """
        Sets the value of :py:attr:`numPartitions`.
        """
        return self._set(numPartitions=value)

    def getNumPartitions(self):
        """
        Gets the value of :py:attr:`numPartitions` or its default value.
        """
        return self.getOrDefault(self.numPartitions)

class HasMinConfidence(Params):
    """
    Mixin for param minConfidence.
    """

    minConfidence = Param(
        Params._dummy(),
        "minConfidence",
        "Minimal confidence for generating Association Rule. [0.0, 1.0]. " +
        "minConfidence will not affect the mining for frequent itemsets, " +
        "but will affect the association rules generation.",
        typeConverter=TypeConverters.toFloat)

    def setMinConfidence(self, value):
        """
        Sets the value of :py:attr:`minConfidence`.
        """
        return self._set(minConfidence=value)

    def getMinConfidence(self):
        """
        Gets the value of minConfidence or its default value.
        """
        return self.getOrDefault(self.minConfidence)

class HasItemsCol(Params):
    """
    Mixin for param itemsCol: items column name.
    """

    itemsCol = Param(Params._dummy(), "itemsCol",
                     "items column name", typeConverter=TypeConverters.toString)

    def setItemsCol(self, value):
        """
        Sets the value of :py:attr:`itemsCol`.
        """
        return self._set(itemsCol=value)

    def getItemsCol(self):
        """
        Gets the value of itemsCol or its default value.
        """
        return self.getOrDefault(self.itemsCol)

class FPGrowthModel(JavaModel, JavaMLWritable, JavaMLReadable):
    """
    .. note:: Experimental

    Model fitted by FPGrowth.

    .. versionadded:: 2.2.0
    """
    @property
    @since("2.2.0")
    def freqItemsets(self):
        """
        DataFrame with two columns:
        * `items` - Itemset of the same type as the input column.
        * `freq`  - Frequency of the itemset (`LongType`).
        """
        return self._call_java("freqItemsets")

    @property
    @since("2.2.0")
    def associationRules(self):
        """
        Data with three columns:
        * `antecedent`  - Array of the same type as the input column.
        * `consequent`  - Array of the same type as the input column.
        * `confidence`  - Confidence for the rule (`DoubleType`).
        """
        return self._call_java("associationRules")

class FPGrowth(JavaEstimator, HasItemsCol, HasPredictionCol,
               HasMinSupport, HasNumPartitions, HasMinConfidence,
               JavaMLWritable, JavaMLReadable):

    """
    .. note:: Experimental

    A parallel FP-growth algorithm to mine frequent itemsets. The algorithm is described in
    Li et al., PFP: Parallel FP-Growth for Query Recommendation [LI2008]_.
    PFP distributes computation in such a way that each worker executes an
    independent group of mining tasks. The FP-Growth algorithm is described in
    Han et al., Mining frequent patterns without candidate generation [HAN2000]_

    .. [LI2008] http://dx.doi.org/10.1145/1454008.1454027
    .. [HAN2000] http://dx.doi.org/10.1145/335191.335372

    .. note:: null values in the feature column are ignored during fit().
    .. note:: Internally `transform` `collects` and `broadcasts` association rules.

    >>> from pyspark.sql.functions import split
    >>> data = (spark.read
    ...     .text("data/mllib/sample_fpgrowth.txt")
    ...     .select(split("value", "\s+").alias("items")))
    >>> data.show(truncate=False)
    +------------------------+
    |items                   |
    +------------------------+
    |[r, z, h, k, p]         |
    |[z, y, x, w, v, u, t, s]|
    |[s, x, o, n, r]         |
    |[x, z, y, m, t, s, q, e]|
    |[z]                     |
    |[x, z, y, r, q, t, p]   |
    +------------------------+
    >>> fp = FPGrowth(minSupport=0.2, minConfidence=0.7)
    >>> fpm = fp.fit(data)
    >>> fpm.freqItemsets.show(5)
    +---------+----+
    |    items|freq|
    +---------+----+
    |      [s]|   3|
    |   [s, x]|   3|
    |[s, x, z]|   2|
    |   [s, z]|   2|
    |      [r]|   3|
    +---------+----+
    only showing top 5 rows
    >>> fpm.associationRules.show(5)
    +----------+----------+----------+
    |antecedent|consequent|confidence|
    +----------+----------+----------+
    |    [t, s]|       [y]|       1.0|
    |    [t, s]|       [x]|       1.0|
    |    [t, s]|       [z]|       1.0|
    |       [p]|       [r]|       1.0|
    |       [p]|       [z]|       1.0|
    +----------+----------+----------+
    only showing top 5 rows
    >>> new_data = spark.createDataFrame([(["t", "s"], )], ["items"])
    >>> sorted(fpm.transform(new_data).first().prediction)
    ['x', 'y', 'z']

    .. versionadded:: 2.2.0
    """
    @keyword_only
    def __init__(self, minSupport=0.3, minConfidence=0.8, itemsCol="items",
                 predictionCol="prediction", numPartitions=None):
        """
        __init__(self, minSupport=0.3, minConfidence=0.8, itemsCol="items", \
                 predictionCol="prediction", numPartitions=None)
        """
        super(FPGrowth, self).__init__()
        self._java_obj = self._new_java_obj("org.apache.spark.ml.fpm.FPGrowth", self.uid)
        self._setDefault(minSupport=0.3, minConfidence=0.8,
                         itemsCol="items", predictionCol="prediction")
        kwargs = self._input_kwargs
        self.setParams(**kwargs)

    @keyword_only
    @since("2.2.0")
    def setParams(self, minSupport=0.3, minConfidence=0.8, itemsCol="items",
                  predictionCol="prediction", numPartitions=None):
        """
        setParams(self, minSupport=0.3, minConfidence=0.8, itemsCol="items", \
                  predictionCol="prediction", numPartitions=None)
        """
        kwargs = self._input_kwargs
        return self._set(**kwargs)

    def _create_model(self, java_model):
        return FPGrowthModel(java_model)


text:
The Kata is inspired by Calculating with Functions Kata for JavaScript.

The goal is to implement simple calculator which uses fluent syntax:

Calc.new.one.plus.two             # Should return 3
Calc.new.five.minus.six           # Should return -1
Calc.new.seven.times.two          # Should return 14
Calc.new.nine.divided_by.three     # Should return 3

There are only four operations that are supported (plus, minus, times, divided_by) and 10 digits (zero, one, two, three, four, five, six, seven, eight, nine).

Each calculation consists of one operation only.


text:
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using Microsoft.CSharp;

namespace TemplateProcessor
{
	public class TemplateException : Exception
	{
		public TemplateException(string message)
			: base(message)
		{

		}

		public TemplateException(string message, Exception innerException)
			: base(message, innerException)
		{

		}
	}

	public class Template<T>
	{
		#region Fields

		private static readonly CSharpCodeProvider codeProvider = new CSharpCodeProvider();

		private static int templateId;

		private readonly Assembly compiledAssembly;
		private readonly string className;
		private readonly MethodInfo generatorMethod;
		private readonly Encoding originalEncoding = Encoding.UTF8;

		private readonly HashSet<string> namespaces = new HashSet<string>
		{
			"System",
			"System.Collections.Generic",
			"System.Linq",
			"System.Text",
			"System.IO",
			"Microsoft.CSharp"
		};

		private readonly HashSet<string> assemblies = new HashSet<string>
		{
			"System.dll",
			"System.Core.dll",
			"System.Data.dll",
			"System.Data.DataSetExtensions.dll",
			"Microsoft.CSharp.dll",
			"TemplateProcessor.exe",   //Bit of a hack, 'this' assembly
		};

		#endregion

		#region Constructors

		public Template(string path, IEnumerable<string> namespaces = null, IEnumerable<string> additionalAssemblies = null)
			: this(File.OpenRead(path), path, namespaces, additionalAssemblies)
		{
		}

		public Template(Stream templateStream, string originalPath, IEnumerable<string> additionalNamespaces = null, IEnumerable<string> additionalAssemblies = null)
		{
			if (templateStream == null)
			{
				throw new ArgumentNullException("templateStream");
			}

			if (additionalNamespaces != null)
			{
				foreach (string name in additionalNamespaces)
				{
					namespaces.Add(name);
				}
			}

			if (additionalAssemblies != null)
			{
				foreach (string name in additionalAssemblies)
				{
					assemblies.Add(name);
				}
			}

			int id = Interlocked.Increment(ref templateId);

			className = string.Format("TemplateProcessor{0}", id);

			string codeString;

			using (MemoryStream codeStream = new MemoryStream())
				using (StreamWriter codeWriter = new StreamWriter(codeStream, Encoding.UTF8))
			{
				//Write out the usings

				foreach (string name in namespaces)
				{
					codeWriter.WriteLine("using {0};", name);
				}

				string contextTypeName = codeProvider.GetTypeOutput(new CodeTypeReference(typeof (T)));

				codeWriter.WriteLine("namespace TemplateProcessor");
				codeWriter.WriteLine("{");
				codeWriter.WriteLine("\tpublic class {0}", className);
				codeWriter.WriteLine("\t{"); //Class opening bracce
				codeWriter.Write("\t\tpublic string TemplatePath =");
				codeProvider.GenerateCodeFromExpression(new CodePrimitiveExpression(originalPath), codeWriter, null);
				codeWriter.WriteLine(";");
				codeWriter.Write("\t\tpublic {0} Context;", contextTypeName);

				codeWriter.WriteLine();

				foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(typeof (T)))
				{
					Write(codeWriter, propertyDescriptor);
				}

				codeWriter.Write("\t\tpublic void Generate({0} __context, StreamWriter __writer)", contextTypeName);
				codeWriter.WriteLine("\t\t{"); //Generate opening brace
				codeWriter.WriteLine("\t\t\tContext = __context;");

				foreach (TemplateElement element in GetTemplateElements(templateStream, originalPath))
				{
					Write(codeWriter, element);
				}

				codeWriter.WriteLine("\t\t}"); //Generate closing brace
				codeWriter.WriteLine("\t}"); //Class closing brace
				codeWriter.WriteLine("}"); //Namespace closing brace

				//Ensure that all the code has been written to the stream

				codeWriter.Flush();

				//Now put the cursor back to the start so we can read it

				codeStream.Seek(0, SeekOrigin.Begin);

				using (StreamReader reader = new StreamReader(codeStream))
				{
					codeString = reader.ReadToEnd();
				}
			}

			CompilerParameters compilerParameters = new CompilerParameters();

			compilerParameters.GenerateExecutable = false;
			compilerParameters.GenerateInMemory = true;

			compilerParameters.IncludeDebugInformation = true;

			foreach (string assembly in assemblies)
			{
				compilerParameters.ReferencedAssemblies.Add(assembly);
			}

			CompilerResults compilerResults = codeProvider.CompileAssemblyFromSource(compilerParameters, codeString);

			if (compilerResults.Errors.HasErrors)
			{
				StringBuilder errors = new StringBuilder();

				foreach (CompilerError error in compilerResults.Errors)
				{
					errors.AppendFormat("Line {0},{1}\t: {2}\n", error.Line, error.Column, error.ErrorText);
				}

				throw new TemplateException(errors.ToString());
			}

			compiledAssembly = compilerResults.CompiledAssembly;

			object generator = compiledAssembly.CreateInstance("TemplateProcessor." + className);

			if (generator == null)
			{
				throw new TemplateException("Failed to create instance compiled generator");
			}

			Type type = generator.GetType();

			generatorMethod = type.GetMethod("Generate");

			if (generatorMethod == null)
			{
				throw new TemplateException("Failed to get generator method");
			}
		}

		#endregion

		#region Public Members

		public void Generate(Stream outputStream, T context)
		{
			if (outputStream == null)
			{
				throw new ArgumentNullException("outputStream");
			}

			object generator = compiledAssembly.CreateInstance("TemplateProcessor." + className);

			if (generator == null)
			{
				throw new TemplateException("Failed to create instance compiled generator");
			}

			StreamWriter writer = new StreamWriter(outputStream, originalEncoding);

			try
			{
				generatorMethod.Invoke(generator, new object[] {context, writer});
			}
			catch (Exception e)
			{
				throw new TemplateException("Exception when running template", e);
			}

			writer.Flush();
		}

		public string Generate(T context)
		{
			using (MemoryStream stream = new MemoryStream())
			{
				Generate(stream, context);

				stream.Seek(0, SeekOrigin.Begin);

				using (StreamReader reader = new StreamReader(stream))
				{
					return reader.ReadToEnd();
				}
			}
		}

		#endregion

		#region Private Members

		private static void Write(TextWriter writer, TemplateElement element)
		{
			if (element.Type == TemplateElementType.StringFunction)
			{
				string identifier = element.Value.Trim();

				if (element.LineNumber != 0)
				{
					writer.WriteLine("#line {0} \"{1}\"", element.LineNumber, element.Filename);
				}
				writer.Write("\t\t\t__writer.Write(string.Format(\"{{0}}\",{0}));", identifier);
			}
			else if (element.Type == TemplateElementType.Code)
			{
				writer.Write(element.Value);
			}
			else
			{
				writer.WriteLine();

				if (element.LineNumber != 0)
				{
					writer.WriteLine("#line {0} \"{1}\"", element.LineNumber, element.Filename);
				}

				writer.Write("\t\t\t__writer.Write(");

				codeProvider.GenerateCodeFromExpression(new CodePrimitiveExpression(element.Value), writer, null);

				writer.WriteLine(");");
			}
		}

		private static IEnumerable<TemplateElement> GetTemplateElements(Stream templateStream, string filename)
		{
			Stack<LineTrackingStreamReader> readers = new Stack<LineTrackingStreamReader>();

			LineTrackingStreamReader reader;

			readers.Push(reader = new LineTrackingStreamReader(templateStream, filename));

			StringBuilder valueBuilder = new StringBuilder();

			TemplateElementType type = TemplateElementType.Text;

			while (reader != null)
			{
				int firstCharacter;
				int literalsOnLine = 0;

				while ((firstCharacter = reader.Read()) != -1)
				{
					if (type == TemplateElementType.Text && (firstCharacter == 0x0a || firstCharacter == 0x0d))
					{
						literalsOnLine = 0;
					}

					if (firstCharacter == FirstCharacter(type))
					{
						int secondCharacter = reader.Peek();

						if (type == TemplateElementType.Text && (secondCharacter == 0x0a || secondCharacter == 0x0d))
						{
							literalsOnLine = 0;
						}

						if (SecondCharacter((char)secondCharacter, type))
						{
							secondCharacter = reader.Read();    //Actually read it

							string value = valueBuilder.ToString();

							if (type == TemplateElementType.Directive)
							{
								value = value.Trim();

								value = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(filename), value));

								reader = new LineTrackingStreamReader(File.Open(value, FileMode.Open, FileAccess.Read), value);

								readers.Push(reader);

								type = TemplateElementType.Text;

								valueBuilder = new StringBuilder();

								continue;
							}

							yield return new TemplateElement(type, value, reader.Line, reader.Column, reader.Filename);

							type = NewType((char)secondCharacter, type);

							if (type == TemplateElementType.Text && literalsOnLine == 0)
							{
								int next = reader.Peek();

								//Gobble up end of line values after control command

								if (next == 0x0a || next == 0x0d)
								{
									reader.Read();

									next = reader.Peek();

									if (next == 0x0a || next == 0x0d)
									{
										reader.Read();
									}
								}
							}

							valueBuilder = new StringBuilder();

							continue;
						}
					}

					if (type == TemplateElementType.Text)
					{
						literalsOnLine = (firstCharacter == 0x0a || firstCharacter == 0x0d) ? 0 : literalsOnLine + 1;
					}

					valueBuilder.Append((char)firstCharacter);
				}

				readers.Pop();
				reader.BaseStream.Close();
				reader.Close();

				if (readers.Count > 0)
				{
					reader = readers.Peek();
				}
				else
				{
					reader = null;
				}
			}

			yield return new TemplateElement(type, valueBuilder.ToString(), 0, 0, filename);
		}

		private static TemplateElementType NewType(char secondCharacter, TemplateElementType type)
		{
			switch (type)
			{
				case TemplateElementType.Directive:
				case TemplateElementType.StringFunction:
				case TemplateElementType.Code:
				return TemplateElementType.Text;
				case TemplateElementType.Text:
				switch (secondCharacter)
				{
					case '@':
					return TemplateElementType.Code;
					case '!':
					return TemplateElementType.StringFunction;
					case '#':
					return TemplateElementType.Directive;
					default:
					throw new InvalidOperationException("Unknown type");
				}
			}

			throw new InvalidOperationException("Unknown type");
		}

		private static bool SecondCharacter(char secondCharacter, TemplateElementType type)
		{
			switch (type)
			{
				case TemplateElementType.Directive:
				case TemplateElementType.StringFunction:
				case TemplateElementType.Code:
				return secondCharacter == '>';
				case TemplateElementType.Text:
				return secondCharacter == '@' || secondCharacter == '!' || secondCharacter == '#';
			}

			throw new InvalidOperationException("Unknown type");
		}

		private static char FirstCharacter(TemplateElementType type)
		{
			switch (type)
			{
				case TemplateElementType.Code:
				return '@';
				case TemplateElementType.StringFunction:
				return '!';
				case TemplateElementType.Directive:
				return '#';
				case TemplateElementType.Text:
				return '<';
			}

			throw new InvalidOperationException("Unknown type");
		}

		private static void Write(StreamWriter writer, PropertyDescriptor propertyDescriptor)
		{
			writer.WriteLine(string.Format("\t\tprivate {0} {1} {{ get {{ return Context.{1}; }} }}",
			                               codeProvider.GetTypeOutput(new CodeTypeReference(propertyDescriptor.PropertyType)),
			                               propertyDescriptor.Name));
		}

		private class LineTrackingStreamReader : IDisposable
		{
			private readonly StreamReader reader;

			public string Filename { get; private set; }
			public int Line { get; private set; }
			public int Column { get; private set; }

			public LineTrackingStreamReader(Stream stream, string filename)
			{
				Filename = filename;
				Line = 0;
				Column = 0;

				reader = new StreamReader(stream);
			}

			public void Dispose()
			{
				reader.Dispose();
			}

			public void Close()
			{
				reader.Close();
			}

			public int Peek()
			{
				return reader.Peek();
			}

			public int Read()
			{
				int c = reader.Read();

				if (c == 0x0a)
				{
					++Line;
					Column = 0;
				}
				else
				{
					++Column;
				}

				return c;
			}

			public Stream BaseStream
			{
				get { return reader.BaseStream; }
			}
		}

		private enum TemplateElementType
		{
			Code,
			StringFunction,
			Text,
			Directive
		}

		private struct TemplateElement
		{
			private readonly TemplateElementType type;
			private readonly string value;
			private readonly int lineNumber;
			private readonly string filename;
			private readonly int columnNumber;

			public TemplateElement(TemplateElementType type, string value, int lineNumber, int columnNumber, string filename)
			{
				this.type = type;
				this.value = value;
				this.lineNumber = lineNumber;
				this.columnNumber = columnNumber;
				this.filename = filename;
			}

			public TemplateElementType Type
			{
				get { return type; }
			}

			public string Value
			{
				get { return value; }
			}

			public int LineNumber
			{
				get { return lineNumber; }
			}

			public int ColumnNumber
			{
				get { return columnNumber;}
			}

			public string Filename
			{
				get { return filename; }
			}
		}

		#endregion
	}
}


text:
/* global after */
/* global before */
/* global describe */
// /* global xdescribe */

'use strict'

var promisedHandlebars = require('../')
var promiseName = 'bluebird'
describe('promised-handlebars: ', function () {
  describe('using ' + promiseName, function () {
    before(function () {
      this.Handlebars = promisedHandlebars(require('handlebars'), { Promise: require('bluebird') })
    })
    after(function () {
      delete this.Handlebars
    })
    require('./default-suite')()
  })
})


text:
[![](https://img.shields.io/crates/v/gimli.svg) ![](https://img.shields.io/crates/d/gimli.svg)](https://crates.io/crates/gimli)
[![](https://docs.rs/gimli/badge.svg)](https://docs.rs/gimli/)
[![Build Status](https://github.com/gimli-rs/gimli/workflows/Rust/badge.svg)](https://github.com/gimli-rs/gimli/actions)
[![Coverage Status](https://coveralls.io/repos/github/gimli-rs/gimli/badge.svg?branch=master)](https://coveralls.io/github/gimli-rs/gimli?branch=master)

`gimli` is a blazing fast library for consuming the
[DWARF debugging format](https://dwarfstd.org/).

* **Zero copy:** everything is just a reference to the original input buffer. No
  copies of the input data get made.

* **Lazy:** you can iterate compilation units without parsing their
  contents. Parse only as many debugging information entry (DIE) trees as you
  iterate over. `gimli` also uses `DW_AT_sibling` references to avoid parsing a
  DIE's children to find its next sibling, when possible.

* **Cross-platform:** `gimli` makes no assumptions about what kind of object
  file you're working with. The flipside to that is that it's up to you to
  provide an ELF loader on Linux or Mach-O loader on macOS.

  * Unsure which object file parser to use? Try the cross-platform
  [`object`](https://github.com/gimli-rs/object) crate. See the
  [`examples/`](./examples) directory for usage with `gimli`.

## Install

Add this to your `Cargo.toml`:

```toml
[dependencies]
gimli = "0.26.2"
```

The minimum supported Rust version is 1.42.0.

## Documentation

* [Documentation on docs.rs](https://docs.rs/gimli/)

* Example programs:

  * [A simple `.debug_info` parser](./examples/simple.rs)

  * [A simple `.debug_line` parser](./examples/simple_line.rs)

  * [A `dwarfdump` clone](./examples/dwarfdump.rs)

  * [An `addr2line` clone](https://github.com/gimli-rs/addr2line)

  * [`ddbug`](https://github.com/gimli-rs/ddbug), a utility giving insight into
    code generation by making debugging information readable.

  * [`dwprod`](https://github.com/fitzgen/dwprod), a tiny utility to list the
    compilers used to create each compilation unit within a shared library or
    executable (via `DW_AT_producer`).

  * [`dwarf-validate`](./examples/dwarf-validate.rs), a program to validate the
    integrity of some DWARF and its references between sections and compilation
    units.

## License

Licensed under either of

  * Apache License, Version 2.0 ([`LICENSE-APACHE`](./LICENSE-APACHE) or https://www.apache.org/licenses/LICENSE-2.0)
  * MIT license ([`LICENSE-MIT`](./LICENSE-MIT) or https://opensource.org/licenses/MIT)

at your option.

## Contribution

See [CONTRIBUTING.md](./CONTRIBUTING.md) for hacking.

Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions.


text:
<?php
/**
 * The template for displaying 404 pages (Not Found)
 *
 * Methods for TimberHelper can be found in the /functions sub-directory
 *
 * @package  WordPress
 * @subpackage  Timber
 * @since    Timber 0.1
 */

$context = Timber::get_context();

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

$args = array(
	'post_type' => 'post',
	'posts_per_page' => 3,
	'paged' => $paged
);

$context['posts'] = Timber::get_posts($args);

Timber::render( '404.twig', $context );


text:
import { ErrorPageConfigs, ErrorPageConfig, SupportedBrowsers } from './ErrorPageConfig';

export interface IErrorPageConfigService {
    getErrorPageConfig(pageName: string): ErrorPageConfig;
    configs: ErrorPageConfigs;
}

export interface IErrorPageConfigProvider extends ng.IServiceProvider {
    setErrorPageConfig(pageName: string, config: ErrorPageConfig): void;
    setAllErrorPageConfigs(configs: ErrorPageConfigs): void;
    setSupportedBrowsers(browsers: SupportedBrowsers): void;
    configs: ErrorPageConfigs;
}


text:
{% extends "base.html" %}
{% load get_thumbnail %}

{% block style %}

{% endblock style %}

{% block content %}

Library

<form method="GET" action="">
<input type='text' name='q' placeholder='Search' value='{{ request.GET.q }}'>
<input type='submit' value='Search'/>
</form>

	Product
	Image

{% for instance in product_list %}

{{ instance.title }}

{% if instance|get_thumbnail:"micro" %}

	{% endif %}

	{% if instance.get_download %}
	Download
	{% else %}
	Coming Soon
	{% endif %}

{% empty %}

No products in library yet, please shop now.

{% endfor %}

{% endblock %}


text:
<?php if ( ! defined('BASEPATH') or !defined('SIMIAN_INSTALLER') ) exit('No direct script access allowed');

    function getDbFile()
    {
        if ( defined('DB_CONFIG_FILE') ) {
            $config_file = DB_CONFIG_FILE;
        } else {
            $config_files = configFileList();
            if ( count($config_files) != 1 ) {
                echo "unable to auto-determine config file, please specify DB_CONFIG_FILE in install.php";
                exit(1);
            }
            $config_file = $config_files[0];
        }
        return getcwd() . '/' . $config_file;
    }

    function dbGetConfig()
    {
        $db_session = $_SESSION['db_config'];

        $db_config = null;
        if ( $db_session != null ) {
            return $db_session;
        } else {
            global $defaultDB;
            return $defaultDB;
        }
        return $db_config;
    }

    function configGetDBValue($key) {
        $dbconf = dbGetConfig();
        if ( $key === "db_user" ) {
            return $dbconf['user'];
        } else if ( $key === "db_pass" ) {
            return $dbconf['password'];
        } else if ( $key === "db_host" ) {
            return $dbconf['host'];
        } else if ( $key === "db_name" ) {
            return $dbconf['db'];
        } else {
            return null;
        }
    }

    function dbConfigs()
    {
        $result = array();
        $dbconf = dbGetConfig();

        $result['db_user']['default'] = $dbconf['user'];
        $result['db_user']['string'] = "@@DB_USER@@";
        $result['db_pass']['default'] = $dbconf['password'];
        $result['db_pass']['string'] = "@@DB_PASSWORD@@";
        $result['db_name']['default'] = $dbconf['db'];
        $result['db_name']['string'] = "@@DB_NAME@@";
        $result['db_host']['default'] = $dbconf['host'];
        $result['db_host']['string'] = "@@DB_HOST@@";

        return $result;
    }

    function dbConfigValid()
    {
        $result = FALSE;

        $result['user'] = $_SESSION['db_config']['user'];
        $result['password'] = $_SESSION['db_config']['password'];
        $result['host'] = $_SESSION['db_config']['host'];
        $result['db'] = $_SESSION['db_config']['db'];

        if ( $user != null && $db != null ) {
            $result = TRUE;
        }
        return $result;
    }

    function dbProcessConfig()
    {
        $user = $_POST['user'];
        $password = $_POST['password'];
        $host = $_POST['host'];
        $db = $_POST['schema'];

        $result = array();
        if ( $user != null and $db != null ) {
            $result['user'] = $user;
            $result['db'] = $db;
            if ( $host != null ) {
                $result['host'] = $host;
            } else {
                $result['host'] = '127.0.0.1';
            }

            if ( $password != null ) {
                $result['password'] = $password;
            }
        }
        $_SESSION['db_config'] = $result;
        return $result;
    }

    function dbRequirementsMet()

    {
        if ( $_SESSION['db_version']['check'] === TRUE && $_SESSION['db_version']['db_check'] === TRUE ) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    function dbHandle()
    {
        if ( ! isset($_SESSION['db_config']) ) {
            return FALSE;
        }
        $user = $_SESSION['db_config']['user'];
        $password = $_SESSION['db_config']['password'];
        $host = $_SESSION['db_config']['host'];
        error_reporting(E_ERROR);
        $db = mysqli_init();
        $check = mysqli_real_connect($db, $host, $user, $password);
        error_reporting(E_WARNING);
        if ( $check === FALSE ) {
            userMessage("error", "DB Error - " . mysqli_connect_error($db));
            return FALSE;
        }
        return $db;
    }

    function dbVersionCheck()
    {
        $db = dbHandle();
        $result = array();
        $result['required'] = MYSQL_VERSION;
        if ( ! $db ) {
            unset($_SESSION['db_version']);
            $result['connect'] = FALSE;
        } else {
            $result['connect'] = TRUE;
            $result['current'] = mysqli_get_server_info($db);
            #i wonder if version_compare is fine to use on mysql version numbers?
            $mysql_check = version_compare(MYSQL_VERSION, $result['current']);
            if ( $mysql_check <= 0 ) {
                $result['check'] = TRUE;
            } else {
                $result['check'] = FALSE;
            }
            $result['db_check'] = dbSelect($db);
            mysqli_close($db);
        }
        if ( ! isset($_SESSION['db_version']) ) {
            $_SESSION['db_version'] = array();
        }
        $_SESSION['db_version'] = array_merge($_SESSION['db_version'], $result);
        return $result;
    }

    function dbSelect($db)
    {
        if ( ! isset($_SESSION['db_config']) ) {
            return FALSE;
        }
        if ( $db === FALSE ) {
            return FALSE;
        }
        $schema = $_SESSION['db_config']['db'];
        $check = mysqli_select_db($db, $schema);
        if ( $check === FALSE ) {
            userMessage("error", "Problem selecting database " . $schema . " - " . mysqli_error($db));
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function dbListRelevantTables($db)
    {
        global $dbCheckTables;
        $result = mysqli_query($db, "SHOW TABLES");
        if ( ! $result ) {
            return FALSE;
        }
        $table_list = array();
        $schema  = $_SESSION['db_config']['db'];
        $table_key = "Tables_in_$schema";
        while ( $table = mysqli_fetch_assoc($result) ) {
            if ( array_search($table[$table_key], $dbCheckTables) !== FALSE ) {
                array_push($table_list, $table[$table_key]);
            }
        }
        return $table_list;

    }

    function dbDoMigration($db) {
        global $dbSchemas;
        $dir = $dbSchemas[0];
        $schema = $_SESSION['db_config']['db'];
        $todo = 0;
        $mig_query = 'SELECT migrations.version FROM `migrations` WHERE migrations.schema = "' . $schema . '"';
        if (($result = mysqli_query($db, $mig_query)) != FALSE) {
	    if(mysqli_num_rows($result) != 0) {
		$row = mysqli_fetch_array($result, MYSQL_NUM);
                $todo = $row[0];
	    }
        } else {
            $mserr = mysqli_error($db);
            if ( mysqli_errno($db) != 0 ) {
                if (!strpos($mserr,"doesn't exist")) {
                    userMessage("error", "Problem checking migration version - " . mysqli_error($db) );
                    return FALSE;
                }
            }
        }

        if($handle = opendir($dir)) {
            while($file = readdir($handle)) {
                clearstatcache();
                if(is_file($dir . $file)) {
                    if(($delimpos = strpos($file,'-')) <= 0) continue;
                    $file_version = substr($file,0,$delimpos);
                    if ($file_version >= $todo) {
                        $updates[] = $dir . $file;
                    }
                }
            }
            closedir($handle);
	    $migoffset = 0;
            if(count($updates) != 0) {
                sort($updates);
                foreach($updates as $schemata) {
                    # omfg execute the sql already :p
                    dbQueriesFromFile($db,$schemata);
                    userMessage("info","Applying migration: " . $schemata);
		    $migoffset = $migoffset + 1;
		    $delim1 = strpos($schemata,'-')+1;
		    $tablespace = substr($schemata, $delim1, -4);
                }
		if($todo == 0) {
		    $mig_update_query = "INSERT INTO migrations (migrations.schema, migrations.description, migrations.version) VALUES ('" . $tablespace . "', '" . $schemata . "', " . $migoffset .")";
		} else {
		    $mig_update_query = 'UPDATE `migrations` set migrations.version = migrations.version + ' . $migoffset . ' WHERE migrations.schema == `' . $tablespace . '`';
		}
                if (($result = mysqli_query($db, $mig_update_query)) != TRUE) {
                    $mserr = mysqli_error($db);
                    userMessage("error", "Problem updating migration version for schema " . $schemata . " - " . mysqli_error($db) );
                    return FALSE;
                }
            } else {
                userMessage("info","No migrations to be performed.");
            }
        }
        return TRUE;
    }

    function dbFlush($db) {
        $done = FALSE;
        while ( ! $done ) {
            $result = mysqli_store_result($db);
            if ( mysqli_more_results($db) ) {
                if ( mysqli_errno($db) != 0 ) {
                    userMessage("warn", "DB Problem - " . mysqli_error($db) );
                }
                mysqli_next_result($db);
                if ( mysqli_errno($db) != 0 ) {
                    userMessage("warn", "DB Problem - " . mysqli_error($db) );
                }
            } else {
                $done = TRUE;
            }
        }
    }

    function dbQueriesFromFile($db, $file)
    {
        $contents = file($file);
        $current_query = '';
        foreach ( $contents as $line_num => $line ) {
            if (substr($line, 0, 2) != '--' && $line != '') {
                $current_query .= $line;
                if (substr(trim($line), -1, 1) == ';') {
                    $result = mysqli_query($db, $current_query);
                    if ( $result === FALSE || mysqli_errno($db) != 0 ) {
                        userMessage("error", "Problem loading schema $schema - " . mysqli_error($db) );
                        return FALSE;
                    }
                    dbFlush($db);
                    $current_query = '';
                }
            }
        }

    }

    function dbWrite()
    {
        if ( ! dbEnabled() ) {
            return TRUE;
        }
        global $dbSchemas, $dbFixtures;
        $db = dbHandle();
        if ( ! dbSelect($db) ) {
            return FALSE;
        }

        dbDoMigration($db);

        foreach ( $dbFixtures as $fixture ) {
            $result = mysqli_multi_query($db, file_get_contents($fixture) );
            if ( $result === FALSE || mysqli_errno($db) != 0 ) {
                userMessage("error", "Problem loading fixture $fixture - " . mysqli_error($db) );
                return FALSE;
            }
            dbFlush($db);
        }
        mysqli_close($db);
        return TRUE;
    }

    function dbEnabled()
    {
        $result = false;
        global $dbSchemas;
        if ( ! empty($dbSchemas) ) {
            $result = true;
        }
        return $result;
    }

?>


text:
- Added a troubleshooting section.
- Changed the **qradar-search-retrieve-command** *interval_in_seconds* default value to 30 seconds.
- Updated the Docker image to: *demisto/python3:3.10.5.31928*.


text:
import VueCoreImageUpload from './vue-core-image-upload.vue';
export default VueCoreImageUpload;


text:
package com.twu.biblioteca;

public class User {
    private String libraryNumber;
    private String password;
    private String name;
    private String emailid;
    private String phoneNumber;

    public User(String libraryNumber, String password, String name, String emailid, String phoneNumber) {
        this.libraryNumber = libraryNumber;
        this.password = password;
        this.name = name;
        this.emailid = emailid;
        this.phoneNumber = phoneNumber;
    }

    public String getLibraryNumber() {
        return libraryNumber;
    }
    public String getPassword() {
        return password;
    }

    public String getName() {
        return name;
    }

    public String getEmailid() {
        return emailid;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public String contactInformation() {
        return name + " | " + emailid + " | " + phoneNumber;
    }
}


text:
<!DOCTYPE html>

    <title>Title</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

Title


text:
/*
 * g_net_update.c
 *
 *  Created on:  2016.11
 *      Author: leo
 */
/********************** g_net update version 2.0 ***************************/
#include "config_info.h"
#include "log.h"
#include "epoll_connect.h"
#include "thread_pool.h"
#include "g_net_update.h"
#include "database_process.h"

#define	CONNECT_TO_SQL_SUCCESS							0
#define SERVER_TIMEOUT									60 * 1 //60S

static CONFIG_INFO config_info;
static int epoll_fd = -1; // the epoll fd
static int listen_fd = -1; // the socket fd socket create return
static pthread_t accep_thread_t;
static pthread_t send_thread_t;

static int current_connected_total = 0; // the connections number
static int exit_accept_flag = 0; // is exit the accept
static int exit_flag = 0; // is exit the epoll wait
static int port = 8111;

static void closesocket(int fd);
static void dumpInfo(unsigned char *info, int length);
pthread_mutex_t connect_total_count_mutex = PTHREAD_MUTEX_INITIALIZER;
static void connect_total_count_opration(BOOL add_or_subract, int value)
{
	pthread_mutex_lock(&connect_total_count_mutex);
	if (add_or_subract)
	{
		current_connected_total = current_connected_total + value;
	}
	else
	{
		current_connected_total = current_connected_total - value;
	}
	pthread_mutex_unlock(&connect_total_count_mutex);
}

static void signal_handler_reboot(int32_t theSignal)
{
	int i;
	int sockfd;
	char log_str_buf[LOG_STR_BUF_LEN];
	signal(SIGPIPE, SIG_IGN);
	if (SIGKILL == theSignal || SIGTERM == theSignal) //we can know when system excute child thread is end
	{
		snprintf(log_str_buf, LOG_STR_BUF_LEN, "receive kill signal exit the server.");
		LOG_INFO(LOG_LEVEL_FATAL, log_str_buf);
		if (listen_fd != -1)
		{
			closesocket(listen_fd);
			listen_fd = -1;
		}
		exit_flag = 1;
		exit_accept_flag = 1;
		for (i = 0; i < MAX_EVENTS; i++)
		{
			sockfd = get_fd_by_event_index(i);
			if (sockfd != -1)
			{
				closesocket(sockfd);
			}
		}
#if CONNECT_TO_SQL_SUCCESS
	sql_pool_destroy();
#endif
	}
	else if (SIGPIPE == theSignal)
	{
		LOG_INFO(LOG_LEVEL_INFO, "SIGPIPE received.\n");
	}
}

static void closesocket(int fd)
{
	shutdown(fd, SHUT_RDWR);
	close(fd);
}

static int set_non_blocking(int sock)
{
	int opts = -1;
	char log_str_buf[LOG_STR_BUF_LEN];

	opts = fcntl(sock, F_GETFL);
	if (opts < 0)
	{
		snprintf(log_str_buf, LOG_STR_BUF_LEN, "fcntl(sock=%d,GETFL).\n", sock);
		LOG_INFO(LOG_LEVEL_ERROR, log_str_buf);
		return (-1);
	}
	opts = opts | O_NONBLOCK;
	if (fcntl(sock, F_SETFL, opts) < 0)
	{
		snprintf(log_str_buf, LOG_STR_BUF_LEN, "fcntl(sock=%d,GETFL).\n", sock);
		LOG_INFO(LOG_LEVEL_ERROR, log_str_buf);
		return (-1);
	}
	return 1;
}

CONFIG_INFO *get_config_info(void)
{
	return &config_info;
}
/****************************** accept task ******************************************/
static void *accept_thread(void *arg)
{
	int connect_fd = -1;
	socklen_t clilen = 0;
	struct sockaddr_in serveraddr;
	struct sockaddr_in clientaddr;
	struct sockaddr cliaddr;
	struct epoll_event ev;
	int val = 1;
	int err = 0;
	int bufsize = 32 * 1024; //1024*2048;
	int epoll_connect_event_index = -1;
	char log_str_buf[LOG_STR_BUF_LEN] = {0};

	listen_fd = socket(AF_INET, SOCK_STREAM, 0);
	if (-1 == listen_fd) // INVALID_SOCKET
	{
		LOG_INFO(LOG_LEVEL_ERROR, "create socket error.\n");
		return NULL;
	}
	//set socket options
	err = setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
	if (0 != err)
	{
		LOG_INFO(LOG_LEVEL_ERROR, "setsockopt SO_REUSEADDR error.\n");
		return NULL;
	}
	err = setsockopt(listen_fd, SOL_SOCKET, SO_RCVBUF, (char*)(&bufsize), sizeof(int));
	if (0 != err)
	{
		LOG_INFO(LOG_LEVEL_ERROR, "setsockopt SO_RCVBUF error.\n");
		return NULL;
	}

	val = 2; //2 minitues
	err = setsockopt(listen_fd, IPPROTO_TCP, TCP_DEFER_ACCEPT, &val, sizeof(val));
	if (0 != err)
	{
		LOG_INFO(LOG_LEVEL_ERROR, "setsockopt TCP_DEFER_ACCEPT error.\n");
		return NULL;
	}

//	set_non_blocking(listen_fd);
	bzero(&serveraddr, sizeof(serveraddr));
	serveraddr.sin_addr.s_addr = INADDR_ANY;
	serveraddr.sin_port = htons(/*config_info.port*/port); //serveraddr.sin_port  = htons(SERVER_LISTEN_PORT);
	serveraddr.sin_family = AF_INET;
	if (-1 == bind(listen_fd, (struct sockaddr *)&serveraddr, sizeof(serveraddr))) // SOCKET_ERROR
	{
		snprintf(log_str_buf, LOG_STR_BUF_LEN, "bind config port %d error.\n", /*config_info.port*/port);
		LOG_INFO(LOG_LEVEL_ERROR, log_str_buf);
		printf("bind config port %d error.\n", /*config_info.port*/port);
		return NULL;
	}
	printf("bind config port %d success.\n", /*config_info.port*/port);

	listen(listen_fd, LISTENQ); // 4096
	clilen = sizeof(cliaddr);
	while (!exit_accept_flag)
	{
		if (current_connected_total < MAX_EVENTS) // effective
		{
			if ((connect_fd = accept(listen_fd, (struct sockaddr *)&clientaddr, &clilen)) < 0)
			{
				if ((errno != EAGAIN) && (errno != ECONNABORTED) && (errno != EPROTO) && (errno != EINTR))
				{
					snprintf(log_str_buf, LOG_STR_BUF_LEN, "accept error %d,%s.\n", errno, strerror(errno));
					LOG_INFO(LOG_LEVEL_ERROR, log_str_buf);
				}
				continue;
			}
		}
		else
		{
			sleep(1);
			snprintf(log_str_buf, LOG_STR_BUF_LEN, "current accept number achieve to maximum(%d) .\n", MAX_EVENTS);
			LOG_INFO(LOG_LEVEL_INDISPENSABLE, log_str_buf);
			continue;
		}
		epoll_connect_event_index = get_epoll_connect_free_event_index();
		// no free epoll event
		if (epoll_connect_event_index == -1) // no the free connect event
		{
			LOG_INFO(LOG_LEVEL_ERROR, "Not find free connect.\n");
			if (connect_fd != -1)
			{
				closesocket(connect_fd);
				connect_fd = -1;
			}
			continue;
		}
		// set connect fd non blocking
		if (set_non_blocking(connect_fd) < 0)
		{
			snprintf(log_str_buf, LOG_STR_BUF_LEN, "set non-blocking socket = %d error.\n", connect_fd);
			LOG_INFO(LOG_LEVEL_ERROR, log_str_buf);
			if (connect_fd != -1)
			{
				closesocket(connect_fd);
				connect_fd = -1;
			}
			continue;
		}
		err = setsockopt(connect_fd, SOL_SOCKET, SO_RCVBUF, (char *)(&bufsize), sizeof(int));
		if (0 != err)
		{
			snprintf(log_str_buf, LOG_STR_BUF_LEN, "set socket(%d) setsockopt SO_RCVBUF error.\n", connect_fd);
			LOG_INFO(LOG_LEVEL_ERROR, log_str_buf);
			if (connect_fd != -1)
			{
				closesocket(connect_fd);
				connect_fd = -1;
			}
			continue;
		}
		init_epoll_connect_by_index(epoll_connect_event_index, connect_fd, inet_ntoa(clientaddr.sin_addr));
		// add epoll event
		ev.data.fd = connect_fd;
		ev.events = EPOLLIN | EPOLLET; // set epoll event type
		if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, connect_fd, &ev) == -1)
		{
			snprintf(log_str_buf, LOG_STR_BUF_LEN, "EPOLL_CTL_ADD %d,%s.\n", errno, strerror(errno));
			LOG_INFO(LOG_LEVEL_ERROR, log_str_buf);
			if (connect_fd != -1)
			{
				closesocket(connect_fd);
				connect_fd = -1;
			}
			continue;
		}
		connect_total_count_opration(TRUE, 1);
		snprintf(log_str_buf, LOG_STR_BUF_LEN, "Epoll event[%d] *****connected from %s*****, fd:%d, current connect total = %d.\n", epoll_connect_event_index,
				        inet_ntoa(clientaddr.sin_addr), connect_fd, current_connected_total);
		LOG_INFO(LOG_LEVEL_INDISPENSABLE, log_str_buf);
	}
	if (-1 != listen_fd) // out the while then close the socket
	{
		closesocket(listen_fd);
		listen_fd = -1;
	}
	return NULL;
}

static int create_accept_task(void)
{
	return pthread_create(&accep_thread_t, NULL, accept_thread, NULL);
}
/*************************************************************************/

static int recv_buffer_from_fd(int socket_fd, char *recv_buffer, int *recv_length)
{
	int rev = -1;
	int one_time_need_read = 1024;
	int continue_read = 1;
	int total_recv_lenght = 0, one_time_recv_lenght = 0;
	while (continue_read)
	{
		one_time_recv_lenght = recv(socket_fd, &recv_buffer[total_recv_lenght], one_time_need_read, 0);
		if (one_time_recv_lenght > 0)
		{
			total_recv_lenght += one_time_recv_lenght;
		}

		if (one_time_recv_lenght < 0) // error
		{
//			if (errno == EAGAIN)
//			{
//				continue_read = 0;
//				break;
//			}
			continue_read = 0;
			rev = -1;
			break;
		}
		else if (one_time_recv_lenght >= 0 && one_time_recv_lenght < one_time_need_read) // read over
		{
			continue_read = 0;
			rev = 0;
			*recv_length = total_recv_lenght;
			break;
		}
		else
		{
			continue_read = 0;
			rev = -1;
			break;
		}
	}
	return rev;
}

static int send_buffer_to_fd(int socket, unsigned char *pucBuf, int iLen)
{
	int n;
	int nwrite;
	char log_str_buf[LOG_STR_BUF_LEN];

	n = iLen;

	while (n > 0)
	{
		nwrite = write(socket, pucBuf + iLen - n, n);
		if (nwrite < n)
		{
			if (nwrite == -1)
			{
				if (errno != EAGAIN)
				{
					snprintf(log_str_buf, LOG_STR_BUF_LEN, "Write.\n");
					LOG_INFO(LOG_LEVEL_ERROR, log_str_buf);
					return 0;
				}
				else
				{
					snprintf(log_str_buf, LOG_STR_BUF_LEN, "Write EAGAIN.\n");
					LOG_INFO(LOG_LEVEL_INFO, log_str_buf);
				}
			}
		}
		n -= nwrite;
	}
	return (iLen - n);
}

static void dumpInfo(unsigned char *info, int length)
{
	char log_str_buf[LOG_STR_BUF_LEN];
	int index = 0;
	int j = 0;
	char buffer[128] = {0};
	memset(buffer, 0, 128);
	for (index = 0; index < length; index++, j+=2)
	{
		sprintf(&buffer[j],"%02x",info[index]);
	}
	snprintf(log_str_buf, LOG_STR_BUF_LEN, "dump info length = %d, %s\n", length, buffer);
	LOG_INFO(LOG_LEVEL_INDISPENSABLE, log_str_buf);
}

void* respons_stb_info(thpool_job_funcion_parameter *parameter, int thread_index)
{
	char log_str_buf[LOG_STR_BUF_LEN];
	char send_buffer[1024] = "i have get you data";
	int sockfd = parameter->fd;
	printf("get buffer = %s\n", parameter->recv_buffer);
	printf("sockfd = %d\n", sockfd);
	send_buffer_to_fd(sockfd, send_buffer, strlen(send_buffer));
	// deal with you logic
	if (sockfd != -1)
	{
		int mactched_event_index = get_matched_event_index_by_fd(sockfd);
		connect_total_count_opration(FALSE, 1);
		snprintf(log_str_buf, LOG_STR_BUF_LEN, "send data to stb over then close the socket(%d), *****client addr(%s)***** , thread_index = %d.\n", sockfd, get_client_addr_by_index(mactched_event_index), thread_index);
		LOG_INFO(LOG_LEVEL_INDISPENSABLE, log_str_buf);
		free_event_by_index(mactched_event_index);
		closesocket(sockfd);
		sockfd = -1;
	}

}
/*******************************************************************/

int main(int argc, char *argv[])
{
	char log_file_name[128] = {0};
	char log_str_buf[LOG_STR_BUF_LEN];
	struct rlimit rl;
	thpool_t *thpool = NULL;
	time_t now;
	time_t prevTime, eventTime = 0;
	struct epoll_event ev, events[MAX_EVENTS];
	int epoll_events_number = 0;
	int index = 0;
	int connect_socket_fd_temp = -1;
	int delete_pool_job_number = 0;

	if (2 != argc)
	{
		printf("pleanse input the port\n");
		return 0;
	}
	port = atoi(argv[1]);
	// read config info
	if (read_config_info(&config_info) != 0)
	{
		printf("[%s %s %d] read_config_info fail.\n", __FILE__, __FUNCTION__, __LINE__);
		return -1;
	}
	print_config_info(config_info);

	signal(SIGCHLD, SIG_IGN); // Ignore the child to the end of the signal, preventing the zombie process(2015.7.17)

	// init log
	sprintf(log_file_name, "log_%d", port);
	// for distinguish between different ports
	set_log_file_name(log_file_name);
	if (log_init() != 0)
	{
		printf("init log error\n");
		return -1;
	}
	log_set_level(config_info.log_level);

	// create fork
	pid_t pidfd = fork();
	if (pidfd < 0)
	{
		snprintf(log_str_buf, LOG_STR_BUF_LEN, "fork failed! errorcode = %d[%s].\n", errno, strerror(errno));
		LOG_INFO(LOG_LEVEL_FATAL, log_str_buf);
		log_close();
		return (-1);
	}
	if (pidfd != 0)
	{
		LOG_INFO(LOG_LEVEL_INFO, "parent fork over.\n");
		exit(0);
	}
	setsid();
	LOG_INFO(LOG_LEVEL_INFO, "children fork start.\n");

	//set max number of open files(also for tcp connections)
	rl.rlim_cur = MAX_EVENTS;
	rl.rlim_max = MAX_EVENTS;
	setrlimit(RLIMIT_NOFILE, &rl);
	getrlimit(RLIMIT_NOFILE, &rl);
	fprintf(stderr, "cur:%d\n", (int)rl.rlim_cur);
	fprintf(stderr, "max:%d\n", (int)rl.rlim_max);
	snprintf(log_str_buf, LOG_STR_BUF_LEN, "information about rlimit cur:%d max:%d.\n", (int)rl.rlim_cur, (int)rl.rlim_max);
	LOG_INFO(LOG_LEVEL_INFO, log_str_buf);

	sleep(1);
	signal(SIGKILL, signal_handler_reboot); // register the signal
	signal(SIGTERM, signal_handler_reboot);
	signal(SIGPIPE, signal_handler_reboot);

	init_epoll_connect();
//	g_net_init_mysql(); // connect to the database
#if CONNECT_TO_SQL_SUCCESS
	if (0 != sql_pool_create(THREAD_POLL_SIZE))
	{
		LOG_INFO(LOG_LEVEL_FATAL, "mysql error.\n");
		log_close();
		return -1;
	}
#endif
	epoll_fd = epoll_create(MAX_FDS); // 1024
	if (0 >= epoll_fd)
	{
		LOG_INFO(LOG_LEVEL_FATAL, "epoll_create error.\n");
		log_close();
		return -1;
	}

	// crate thread pool
	thpool = thpool_init(THREAD_POLL_SIZE);
	if (NULL == thpool)
	{
		LOG_INFO(LOG_LEVEL_FATAL, "create thread pool error.\n");
		log_close();
		return -1;
	}
	LOG_INFO(LOG_LEVEL_INDISPENSABLE, "thpool_init success.\n");

	// accept the socket connect
	create_accept_task();

	time(&prevTime);
	eventTime = prevTime;
	while (!exit_flag)
	{
		time(&now);
		if (abs(now - eventTime) >= SERVER_TIMEOUT) //SERVER_TIMEOUT second detect one time delete the time out event
		{
			eventTime = now;
			for (index = 0; index < MAX_EVENTS; index++)
			{
				connect_socket_fd_temp = get_fd_by_event_index(index);
				if (connect_socket_fd_temp != -1)
				{
					if ((now - get_event_connect_time_by_index(index)) > SERVER_TIMEOUT)
					{
						snprintf(log_str_buf, LOG_STR_BUF_LEN, "Epoll event[%d] timeout closed and fd= %d.\n", index, connect_socket_fd_temp);
						LOG_INFO(LOG_LEVEL_INDISPENSABLE, log_str_buf);
						free_event_by_index(index);
						if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, connect_socket_fd_temp, &ev) == -1)
						{
							snprintf(log_str_buf, LOG_STR_BUF_LEN, "EPOLL_CTL_DEL %d,%s.\n", errno, strerror(errno));
							LOG_INFO(LOG_LEVEL_ERROR, log_str_buf);
						}
						connect_total_count_opration(FALSE, 1);
						closesocket(connect_socket_fd_temp);
						connect_socket_fd_temp = -1;
					}
				}
			}
			// delete the pool job time out job
			delete_pool_job_number = delete_timeout_job(thpool, SERVER_TIMEOUT);
			connect_total_count_opration(FALSE, delete_pool_job_number);
			snprintf(log_str_buf, LOG_STR_BUF_LEN, "pool queque delete job number = %d.\n", delete_pool_job_number);
			LOG_INFO(LOG_LEVEL_INDISPENSABLE, log_str_buf);
		}
		epoll_events_number = epoll_wait(epoll_fd, events, MAX_EVENTS, 2000); //2seconds
		for (index = 0; index < epoll_events_number; ++index) // deal with the event
		{
			connect_socket_fd_temp = events[index].data.fd; // get the socket fd
			// delete epoll event
			if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, events[index].data.fd, &ev) == -1)
			{
				snprintf(log_str_buf, LOG_STR_BUF_LEN, "EPOLL_CTL_DEL %d,%s.\n", errno, strerror(errno));
				LOG_INFO(LOG_LEVEL_ERROR, log_str_buf);
				events[index].data.fd = -1;
			}
			if (events[index].events & EPOLLIN) //have read event
			{
				int event_index = -1;
				int recv_length = 0;
				unsigned char recv_buffer[BUFFER_SIZE];

				if (connect_socket_fd_temp < 0)
				{
					connect_total_count_opration(FALSE, 1);
					snprintf(log_str_buf, LOG_STR_BUF_LEN, "Event[%d] read invalid handle.\n", index);
					LOG_INFO(LOG_LEVEL_ERROR, log_str_buf);
					continue;
				}
				event_index = get_matched_event_index_by_fd(connect_socket_fd_temp);
				snprintf(log_str_buf, LOG_STR_BUF_LEN, "Epoll get Event[%d] fd = %d.\n", event_index, connect_socket_fd_temp);
				LOG_INFO(LOG_LEVEL_INDISPENSABLE, log_str_buf);
				// no the event
				if (event_index < 0)
				{
					connect_total_count_opration(FALSE, 1);
					snprintf(log_str_buf, LOG_STR_BUF_LEN, "not find matched fd = %d.\n", connect_socket_fd_temp);
					LOG_INFO(LOG_LEVEL_ERROR, log_str_buf);
					free_event_by_index(event_index);
					if (connect_socket_fd_temp != -1)
					{
						closesocket(connect_socket_fd_temp);
						connect_socket_fd_temp = -1;
					}
					continue;
				}
				// receive the buffer from the socket fd
				if (0 == recv_buffer_from_fd(connect_socket_fd_temp, recv_buffer, &recv_length))
				{
					snprintf(log_str_buf, LOG_STR_BUF_LEN, "recv_length = %d, current fd = %d, current job queue job number = %d.\n",recv_length, connect_socket_fd_temp, get_jobqueue_number(thpool));
					LOG_INFO(LOG_LEVEL_INDISPENSABLE, log_str_buf);
					dumpInfo((unsigned char *)recv_buffer, recv_length);
					// receive buffer success then add the thread pool
					thpool_add_work(thpool, (void*)respons_stb_info, connect_socket_fd_temp, recv_buffer);
				}
				else
				{
					// receive buffer error
					connect_total_count_opration(FALSE, 1);
					snprintf(log_str_buf, LOG_STR_BUF_LEN, "Epoll event[%d] not read data, and the socket fd = %d.\n", event_index, connect_socket_fd_temp);
					LOG_INFO(LOG_LEVEL_INDISPENSABLE, log_str_buf);
					free_event_by_index(event_index);
					if (connect_socket_fd_temp != -1)
					{
						closesocket(connect_socket_fd_temp);
						connect_socket_fd_temp = -1;
					}
				}
			}
//			else if (events[index].events & EPOLLOUT) //have read event. Will not reach here
//			{
//				//;
//			}
			else
			{
				snprintf(log_str_buf, LOG_STR_BUF_LEN, "Unknown error! event.data.fd = %d.\n", events[index].data.fd);
				LOG_INFO(LOG_LEVEL_ERROR, log_str_buf);
				connect_total_count_opration(FALSE, 1);
				if (connect_socket_fd_temp < 0)
				{
					LOG_INFO(LOG_LEVEL_ERROR, "EPOLLOUT.\n");
					continue;
				}
				//close the socket
				free_event_by_index(get_matched_event_index_by_fd(connect_socket_fd_temp));
				if (connect_socket_fd_temp != -1)
				{
					closesocket(connect_socket_fd_temp);
					connect_socket_fd_temp = -1;
				}
			}
		}
	}
	log_close();
	if (listen_fd != -1)
	{
		closesocket(listen_fd);
		listen_fd = -1;
	}

#if CONNECT_TO_SQL_SUCCESS
	sql_pool_destroy();
#endif
	exit_accept_flag = 1;
	thpool_destroy(thpool);
	printf("[%s %s %d]Done...\n", __FILE__, __FUNCTION__, __LINE__);
	return 1;
}


text:
module Achievable
  module Achiever
    extend ActiveSupport::Concern
    include Achievable::AchieveManager

    included do
      has_many :achievements, :through => :achievings
      has_many :achievings, :dependent => :destroy, :as => :achiever
    end

    def achieve(name, options = {})
      condition = options[:condition] ? options[:condition] : ( lambda { |u| true } )
      if Achievable.resque_enable
        achieveit(name, &condition)
      else
        achieveit!(name, &condition)
      end
    end

    def achieveit!(name, &block)
      achievement = Achievement.find_by_name!(name)
      unless achieved?(achievement)
        achievement.achieve(self) if ( block_given? ? block.call(self) : true )
      end
    end

    def achieved?(achievement)
      if achievement.is_a? String
        achievement = Achievement.find_by_name!(achievement)
      end
      achievements.include?(achievement)
    end

  end # Achiever
end # Achievable


text:
<!doctype html>
<!-- This file is generated by build.py. -->
<title>object tall.jpg; overflow:hidden; -o-object-fit:none; -o-object-position:bottom </title>
<link rel="stylesheet" href="../../support/reftests.css">
<link rel='match' href='hidden_none_50_bottom-ref.html'>
<style>
 #test > * { overflow:hidden; -o-object-fit:none; -o-object-position:bottom  }
</style>
<div id="test">
 <object data="../../support/tall.jpg"></object>
</div>


text:
#ifndef DATA_HDF_HDF_REF_INFO
#define DATA_HDF_HDF_REF_INFO

#include "datastructures/saf/RefInfo.h"

class HDFRefInfoGroup {
 public:
  HDFGroup refInfoGroup;
  HDFArray<string> fullNameArray;
  HDFArray<uint32_t> idArray;
  HDFArray<uint32_t> lengthArray;
  HDFArray<string> md5Array;

  bool Create(HDFGroup &parent) {
    parent.AddGroup("RefInfo");
    if (refInfoGroup.Initialize(parent.group, "RefInfo") == 0) { return 0; }

    fullNameArray.Create(refInfoGroup, "FullName");
    idArray.Create(refInfoGroup, "ID");
    lengthArray.Create(refInfoGroup, "Length");
    md5Array.Create(refInfoGroup, "MD5");
    return true;
  }

  void AddRefInfo(string &fullName, unsigned int id, unsigned int length, string md5) {
    fullNameArray.Write(&fullName, 1);
    idArray.Write(&id, 1);
    lengthArray.Write(&length, 1);
    md5Array.Write(&md5, 1);
  }

  int Initialize(HDFGroup &parentGroup) {
    if (refInfoGroup.Initialize(parentGroup.group, "RefInfo") == 0) { return 0; }
    if (fullNameArray.Initialize(refInfoGroup, "FullName") == 0) { return 0;}
    if (idArray.Initialize(refInfoGroup,"ID") == 0) { return 0;}
    if (lengthArray.Initialize(refInfoGroup, "Length") == 0) { return 0;}
    if (md5Array.Initialize(refInfoGroup, "MD5") == 0) { return 0;}
    return 1;
  }

  ~HDFRefInfoGroup() {
    refInfoGroup.Close();
  }

  void Read(RefInfo &refInfo) {
    UInt nRow = fullNameArray.size();
    refInfo.fullName.resize(nRow);
    refInfo.id.resize(nRow);
    refInfo.length.resize(nRow);
    refInfo.md5.resize(nRow);
    /*
    if (refInfo.fullName.size() != refInfo.id.size() or
        refInfo.id.size() != refInfo.length.size() or
        refInfo.length.size() != refInfo.md5.size()) {
      cout << "Error with the RefInfo group in a cmp.h5 file.  The datasets " << endl
           << "are of different lengths but should be the same." << endl;
      exit(1);
    }
    */
    int i;
    for (i = 0; i < refInfo.fullName.size();i++) {
      fullNameArray.Read(i,i+1,&refInfo.fullName[i]);
    }
    for (i = 0; i < refInfo.md5.size(); i++) {
      md5Array.Read(i, i+1, &refInfo.md5[i]);
    }
    lengthArray.Read(0, refInfo.length.size(), &refInfo.length[0]);
    idArray.Read(0, refInfo.id.size(), &refInfo.id[0]);
  }
};

#endif


text:
package fr.lteconsulting.pomexplorer.javac;

import fr.lteconsulting.pomexplorer.ILogger;
import fr.lteconsulting.pomexplorer.Project;
import fr.lteconsulting.pomexplorer.Tools;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;

import java.io.File;
import java.nio.file.Paths;

public class JavaSourceAnalyzer
{
    private ClassUsageExtractorVisitor usageExtractor = new ClassUsageExtractorVisitor();

    private int nbDirectoryTraversed = 0;

    private int nbFilesParsed = 0;

    public void analyzeProject(Project project, boolean logFqns, ILogger log)
    {
        analyzeDirectory(Paths.get(project.getPomFile().getParent(), "src").toString(), logFqns, log);
    }

    public void analyzeDirectory(String directory, boolean logFqns, ILogger log)
    {
        log.html("processing parsing java directory : " + directory + "
");
        log.html("warning : the analyzed fqns may contain false positives, because the java parsing is not fine tuned yet.
"
                + "Also it does not detect references made to inner classes (that can be fixed) and through reflection (cannot be fixed), like Class.forName(...) calls.
" + "Feel free to submit a pull request !
");

        processFile(new File(directory));

        log.html("finished : " + nbDirectoryTraversed + " directories traversed, " + nbFilesParsed + " java files parsed
");

        if (logFqns)
        {
            log.html("referenced fqns :
");
            usageExtractor.getQualifiedNames().stream().filter(s -> s != null).forEachOrdered(fqn -> log.html(fqn + "
"));
        }
    }

    public ClassUsageExtractorVisitor getUsageExtractor()
    {
        return usageExtractor;
    }

    private void processFile(File file)
    {
        if (file == null)
            return;

        if (file.isDirectory())
        {
            nbDirectoryTraversed++;
            for (File f : file.listFiles())
                processFile(f);
        }
        else if (file.getName().endsWith(".java"))
        {
            nbFilesParsed++;
            System.out.println("parsing " + file.getAbsolutePath());
            processJavaFile(file);
        }
    }

    private void processJavaFile(File file)
    {
        String content = Tools.readFile(file);
        if (content == null)
        {
            System.out.println("Cannot read file " + file.getAbsolutePath());
            return;
        }

        ASTParser parser = ASTParser.newParser(AST.JLS8);
        parser.setSource(content.toCharArray());
        parser.setKind(ASTParser.K_COMPILATION_UNIT);

        CompilationUnit cu = (CompilationUnit) parser.createAST(null);

        usageExtractor.setParsedFile(file.getAbsolutePath());
        cu.accept(usageExtractor);
    }
}


text:
package org.optaplanner.quarkus.jackson.it;

import io.quarkus.test.junit.NativeImageTest;

/**
 * Test various OptaPlanner operations running in native mode
 */
@NativeImageTest
public class OptaPlannerTestResourceIT extends OptaPlannerTestResourceTest {

}