text:
package org.diirt.datasource.sample.graphene;

import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.image.BufferedImage;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.diirt.graphene.InterpolationScheme;
import org.diirt.graphene.LineGraph2DRendererUpdate;
import org.diirt.datasource.PVReader;
import org.diirt.datasource.PVManager;
import org.diirt.datasource.PVReaderListener;
import org.diirt.vtype.ValueUtil;
import org.diirt.datasource.PVReaderEvent;
import org.diirt.datasource.graphene.Graph2DResult;
import org.diirt.datasource.graphene.LineGraph2DExpression;
import static org.diirt.datasource.graphene.ExpressionLanguage.*;
import static org.diirt.datasource.formula.ExpressionLanguage.*;
import org.diirt.datasource.sample.SetupUtil;
import static org.diirt.util.concurrent.Executors.swingEDT;
import static org.diirt.util.time.TimeDuration.*;

/**
 *
 * @author carcassi
 */
public class LineGraphSample extends javax.swing.JFrame {

    /**
     * Creates new form MockWaterfallPlot
     */
    public LineGraphSample() {
        initComponents();
        plotView.addComponentListener(new ComponentAdapter() {

            @Override
            public void componentResized(ComponentEvent e) {

                if (plot != null) {
                    plot.update(new LineGraph2DRendererUpdate().imageHeight(plotView.getHeight()).imageWidth(plotView.getWidth()));
                }
            }
        });
    }
    private PVReader<Graph2DResult> pv;
    private LineGraph2DExpression plot;

    /**
     * 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() {

        jLabel1 = new javax.swing.JLabel();
        dataFormulaField = new javax.swing.JTextField();
        lastError = new javax.swing.JTextField();
        plotView = new org.diirt.datasource.sample.ImagePanel();
        jLabel2 = new javax.swing.JLabel();
        xColumnField = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        yColumnField = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        tooltipColumnField = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Data Formula:");

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

        lastError.setEditable(false);

        javax.swing.GroupLayout plotViewLayout = new javax.swing.GroupLayout(plotView);
        plotView.setLayout(plotViewLayout);
        plotViewLayout.setHorizontalGroup(
            plotViewLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 497, Short.MAX_VALUE)
        );
        plotViewLayout.setVerticalGroup(
            plotViewLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 197, Short.MAX_VALUE)
        );

        jLabel2.setText("X Column:");

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

        jLabel3.setText("Y Column:");

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

        jLabel4.setText("Tooltip Column:");

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

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(dataFormulaField)
                        .addGap(12, 12, 12))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(plotView, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lastError))
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(xColumnField)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(yColumnField)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(tooltipColumnField)
                        .addContainerGap())))
            .addComponent(jSeparator1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(dataFormulaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(xColumnField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(yColumnField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(tooltipColumnField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(plotView, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lastError, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

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

    private void dataFormulaFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dataFormulaFieldActionPerformed
        if (pv != null) {
            pv.close();
            plotView.setImage(null);
            plot = null;
        }

        if (dataFormulaField.getText() == null || dataFormulaField.getText().trim().isEmpty()) {
            return;
        }

        if (plot == null) {
            plot = lineGraphOf(formula(dataFormulaField.getText()),
                    formulaArg(xColumnField.getText()),
                    formulaArg(yColumnField.getText()),
                    formulaArg(tooltipColumnField.getText()));
        }

        plot.update(new LineGraph2DRendererUpdate().imageHeight(plotView.getHeight()).imageWidth(plotView.getWidth()).interpolation(InterpolationScheme.LINEAR));
        pv = PVManager.read(plot)
                .notifyOn(swingEDT())
                .readListener(new PVReaderListener<Graph2DResult>() {

                    @Override
                    public void pvChanged(PVReaderEvent<Graph2DResult> event) {
                        setLastError(pv.lastException());
                        if (pv.getValue() != null) {
                            BufferedImage image = ValueUtil.toImage(pv.getValue().getImage());
                            plotView.setImage(image);
                        }
                    }
                })
                .maxRate(ofHertz(50));
    }//GEN-LAST:event_dataFormulaFieldActionPerformed

    private void yColumnFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_yColumnFieldActionPerformed
        dataFormulaFieldActionPerformed(evt);
    }//GEN-LAST:event_yColumnFieldActionPerformed

    private void tooltipColumnFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tooltipColumnFieldActionPerformed
        dataFormulaFieldActionPerformed(evt);
    }//GEN-LAST:event_tooltipColumnFieldActionPerformed

    private void xColumnFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_xColumnFieldActionPerformed
        dataFormulaFieldActionPerformed(evt);
    }//GEN-LAST:event_xColumnFieldActionPerformed

    private void setLastError(Exception ex) {
        if (ex != null) {
            lastError.setText(ex.getMessage());
            ex.printStackTrace();
            Logger.getLogger(LineGraphSample.class.getName()).log(Level.WARNING, "Error", ex);
        } else {
            lastError.setText("");
        }
    }
    final BufferedImage finalBuffer = new BufferedImage(100, 100, BufferedImage.TYPE_3BYTE_BGR);

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        SetupUtil.defaultCASetupForSwing();
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new LineGraphSample().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField dataFormulaField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField lastError;
    private org.diirt.datasource.sample.ImagePanel plotView;
    private javax.swing.JTextField tooltipColumnField;
    private javax.swing.JTextField xColumnField;
    private javax.swing.JTextField yColumnField;
    // End of variables declaration//GEN-END:variables
}


text:
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2017 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0

package com.google.appinventor.client.editor.simple.components.utils;

import com.google.appinventor.client.ComponentsTranslation;
import com.google.appinventor.client.editor.simple.components.MockForm;
import com.google.appinventor.client.editor.simple.components.MockComponent;
import com.google.appinventor.client.editor.youngandroid.YaFormEditor;
import com.google.appinventor.client.editor.youngandroid.palette.YoungAndroidPalettePanel;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidAccelerometerSensitivityChoicePropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidAlignmentChoicePropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidAssetSelectorPropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidBooleanPropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidButtonShapeChoicePropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidChartLineTypeChoicePropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidChartPointShapeChoicePropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidColorChoicePropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidComponentSelectorPropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidDataColumnSelectorProperty;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidDefaultURLPropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidFloatRangePropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidFontTypefaceChoicePropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidGeoJSONPropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidGeographicPointPropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidHorizontalAlignmentChoicePropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidIntegerRangePropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidLegoEv3ColorSensorModeChoicePropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidLegoEv3GyroSensorModeChoicePropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidLegoEv3SensorPortChoicePropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidLegoEv3UltrasonicSensorModeChoicePropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidLegoNxtSensorPortChoicePropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidLengthPropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidMapScaleUnitsPropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidMapTypePropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidNavigationMethodChoicePropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidScreenAnimationChoicePropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidScreenOrientationChoicePropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidSensorDistIntervalChoicePropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidSensorTimeIntervalChoicePropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidSizingChoicePropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidTextReceivingPropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidThemeChoicePropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidToastLengthChoicePropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidVerticalAlignmentChoicePropertyEditor;
import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidChartTypeChoicePropertyEditor;
import com.google.appinventor.client.properties.BadPropertyEditorException;
import com.google.appinventor.client.properties.Property;
import com.google.appinventor.client.widgets.properties.ChoicePropertyEditor;
import com.google.appinventor.client.widgets.properties.CountryChoicePropertyEditor;
import com.google.appinventor.client.widgets.properties.EditableProperties;
import com.google.appinventor.client.widgets.properties.EditableProperty;
import com.google.appinventor.client.widgets.properties.FloatPropertyEditor;
import com.google.appinventor.client.widgets.properties.IntegerPropertyEditor;
import com.google.appinventor.client.widgets.properties.SemanticWebPropertyEditor;
import com.google.appinventor.client.widgets.properties.SubsetJSONPropertyEditor;
import com.google.appinventor.client.widgets.properties.LanguageChoicePropertyEditor;
import com.google.appinventor.client.widgets.properties.NonNegativeFloatPropertyEditor;
import com.google.appinventor.client.widgets.properties.NonNegativeIntegerPropertyEditor;
import com.google.appinventor.client.widgets.properties.PropertyEditor;
import com.google.appinventor.client.widgets.properties.ScalingChoicePropertyEditor;
import com.google.appinventor.client.widgets.properties.StringPropertyEditor;
import com.google.appinventor.client.widgets.properties.TextAreaPropertyEditor;
import com.google.appinventor.client.widgets.properties.TextPropertyEditor;
import com.google.appinventor.components.common.PropertyTypeConstants;
import com.google.appinventor.shared.simple.ComponentDatabaseInterface;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;

/**
 * Provides utility functions for dealing with the UI for component properties.
 *
 * These functions are called by descendants of MockComponent with its protected
 * field "properties" as an argument. This EditableProperties object is populated
 * by {@link YoungAndroidPalettePanel#configureComponent(MockComponent)}, which
 * calls {@link MockComponent#addProperty(String, String, String, PropertyEditor)}
 * for each of the MockComponent's properties. The addProperty method in turn calls
 * {@link EditableProperties#addProperty(String, String, String, PropertyEditor, int)},
 * adding the property to "properties".
 *
 * @author hal@mit.edu (Hal Abelson)
 */
public class PropertiesUtil {
  // Construct a HashSet of acceptable Chart Data Source components
  private static final HashSet<String> CHART_DATA_SOURCES = new HashSet<String>() {{
    add("DataFile");
    add("TinyDB");
    add("CloudDB");
    add("AccelerometerSensor");
    add("BluetoothClient");
    add("Web");
    add("GyroscopeSensor");
    add("OrientationSensor");
    add("ProximitySensor");
    add("Pedometer");
    add("LocationSensor");
  }};

  /**
   * Prevent instantiation.
   */
  private PropertiesUtil() {
  }

  /**
   * Populate properties of a MockComponent, given a list of property definitons
   * @param mockComponent
   * @param propertyDefintions
   */
  public static void populateProperties(MockComponent mockComponent, List<ComponentDatabaseInterface.PropertyDefinition> propertyDefintions,
                                        YaFormEditor editor) {

    String componentType = mockComponent.getType();
    // Configure properties
    for (ComponentDatabaseInterface.PropertyDefinition property : propertyDefintions) {
      mockComponent.addProperty(property.getName(), property.getDefaultValue(),
          ComponentsTranslation.getPropertyName(property.getCaption()),
          ComponentsTranslation.getPropertyName(property.getCategory()),
          ComponentsTranslation.getPropertyName(property.getDescription()),
          property.getEditorType(), property.getEditorArgs(),
          PropertiesUtil.createPropertyEditor(property.getEditorType(), property.getDefaultValue(), editor, property.getEditorArgs()));
      /*OdeLog.log("Property Caption: " + property.getCaption() + ", "
          + TranslationComponentProperty.getName(property.getCaption()));*/
    }

  }

  // Use individual methods for each property since we can't write the generic
  // getExstingPropertyEditor due to type safety issues - see below.

  /**
   * Retrieves the property editor for Horizontal Alignment.
   *
   * @param  properties
   * @return the property editor for Horizontal Alignment
   * @throws BadPropertyEditorException
   */
  public static  YoungAndroidHorizontalAlignmentChoicePropertyEditor
  getHAlignmentEditor(EditableProperties properties)
      throws BadPropertyEditorException {

    PropertyEditor propEditor = null;

    // Get the property with the specified name from the properties
    // object. This works because an EditableProperties contains a
    // TreeMap<String, T extends Property> that maps a property's name to its instance.
    Property prop = properties.getProperty(MockForm.PROPERTY_NAME_HORIZONTAL_ALIGNMENT);

    if (prop != null) {
      if (prop instanceof EditableProperty) {
        // Cast prop to an EditableProperty and get its editor
        propEditor = ((EditableProperty) prop).getEditor();

        // Make sure we have the right editor
        if (propEditor != null) {
          if (! (propEditor instanceof YoungAndroidHorizontalAlignmentChoicePropertyEditor))
            throw new BadPropertyEditorException("Bad property editor");
        }
      }
    }

    // Cast propEditor to the appropriate type
    return (YoungAndroidHorizontalAlignmentChoicePropertyEditor)propEditor;
  }

  /**
   * Retrieves the property editor for Vertical Alignment.
   * Note that this is almost identical to {@link #getHAlignmentEditor(EditableProperties)}
   * in terms of implementation.
   *
   * @param  properties
   * @return the property editor for Vertical Alignment
   * @throws BadPropertyEditorException
   */
  public static  YoungAndroidVerticalAlignmentChoicePropertyEditor
  getVAlignmentEditor(EditableProperties properties)
      throws BadPropertyEditorException {

    PropertyEditor propEditor = null;
    Property prop = properties.getProperty(MockForm.PROPERTY_NAME_VERTICAL_ALIGNMENT);
    if (prop != null) {
      if (prop instanceof EditableProperty) {
        propEditor = ((EditableProperty) prop).getEditor();
        if (propEditor != null) {
          if (! (propEditor instanceof YoungAndroidVerticalAlignmentChoicePropertyEditor))
            throw new BadPropertyEditorException("Bad property editor");
        }
      }
    }
    return (YoungAndroidVerticalAlignmentChoicePropertyEditor)propEditor;
  }

  /*
   * Creates a new property editor.
   */
  public static PropertyEditor createPropertyEditor(String editorType, String defaultValue, YaFormEditor editor, String[] editorArgs) {
    if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_HORIZONTAL_ALIGNMENT)) {
      return new YoungAndroidHorizontalAlignmentChoicePropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_VERTICAL_ALIGNMENT)) {
      return new YoungAndroidVerticalAlignmentChoicePropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_ASSET)) {
      return new YoungAndroidAssetSelectorPropertyEditor(editor);
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_BLUETOOTHCLIENT)) {
      return new YoungAndroidComponentSelectorPropertyEditor(editor,
          // Pass the set of component types that will be shown in the property editor,
          // in this case, just "BluetoothClient".
          Collections.singleton("BluetoothClient"));
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_BOOLEAN)) {
      return new YoungAndroidBooleanPropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_BUTTON_SHAPE)) {
      return new YoungAndroidButtonShapeChoicePropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_COLOR)) {
      return new YoungAndroidColorChoicePropertyEditor(defaultValue);
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_COMPONENT)) {
      return new YoungAndroidComponentSelectorPropertyEditor(editor);
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_FLOAT)) {
      return new FloatPropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_GEOGRAPHIC_POINT)) {
      return new YoungAndroidGeographicPointPropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_GEOJSON_TYPE)) {
      return new YoungAndroidGeoJSONPropertyEditor(editor);
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_SUBSET_JSON)) {
      return new SubsetJSONPropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_INTEGER)) {
      return new IntegerPropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_LATITUDE)) {
      return new YoungAndroidFloatRangePropertyEditor(-90, 90);
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_LEGO_EV3_SENSOR_PORT)) {
      return new YoungAndroidLegoEv3SensorPortChoicePropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_LEGO_EV3_COLOR_SENSOR_MODE)) {
      return new YoungAndroidLegoEv3ColorSensorModeChoicePropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_LEGO_EV3_ULTRASONIC_SENSOR_MODE)) {
      return new YoungAndroidLegoEv3UltrasonicSensorModeChoicePropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_LEGO_EV3_GYRO_SENSOR_MODE)) {
      return new YoungAndroidLegoEv3GyroSensorModeChoicePropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_CHOICES)) {
      return new ChoicePropertyEditor(editorArgs);
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_LEGO_NXT_SENSOR_PORT)) {
      return new YoungAndroidLegoNxtSensorPortChoicePropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_LEGO_NXT_GENERATED_COLOR)) {
      return new YoungAndroidColorChoicePropertyEditor(
          YoungAndroidColorChoicePropertyEditor.NXT_GENERATED_COLORS, defaultValue);
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_LENGTH)) {
      return new YoungAndroidLengthPropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_LONGITUDE)) {
      return new YoungAndroidFloatRangePropertyEditor(-180, 180);
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_MAP_TYPE)) {
      return new YoungAndroidMapTypePropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_MAP_UNIT_SYSTEM)) {
      return new YoungAndroidMapScaleUnitsPropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_MAP_ZOOM)) {
      return new YoungAndroidIntegerRangePropertyEditor(1, 18);
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_NAVIGATION_METHOD)) {
      return new YoungAndroidNavigationMethodChoicePropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_NON_NEGATIVE_FLOAT)) {
      return new NonNegativeFloatPropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_NON_NEGATIVE_INTEGER)) {
      return new NonNegativeIntegerPropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_SCREEN_ORIENTATION)) {
      return new YoungAndroidScreenOrientationChoicePropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_SCREEN_ANIMATION)) {
      return new YoungAndroidScreenAnimationChoicePropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_SENSOR_DIST_INTERVAL)) {
      return new YoungAndroidSensorDistIntervalChoicePropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_SENSOR_TIME_INTERVAL)) {
      return new YoungAndroidSensorTimeIntervalChoicePropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_STRING)) {
      return new StringPropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_TEXTALIGNMENT)) {
      return new YoungAndroidAlignmentChoicePropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_TEXTAREA)) {
      return new TextAreaPropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_THEME)) {
      return new YoungAndroidThemeChoicePropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_TOAST_LENGTH)) {
      return new YoungAndroidToastLengthChoicePropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_TYPEFACE)) {
      return new YoungAndroidFontTypefaceChoicePropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_VISIBILITY)) {
      return new YoungAndroidBooleanPropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_TEXT_RECEIVING)) {
      return new YoungAndroidTextReceivingPropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_ACCELEROMETER_SENSITIVITY)) {
      return new YoungAndroidAccelerometerSensitivityChoicePropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_TEXT_TO_SPEECH_COUNTRIES)) {
      return new CountryChoicePropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_TEXT_TO_SPEECH_LANGUAGES)) {
      return new LanguageChoicePropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_SIZING)) {
      return new YoungAndroidSizingChoicePropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_SCALING)) {
      return new ScalingChoicePropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_FIREBASE_URL)) {
      return new YoungAndroidDefaultURLPropertyEditor("DEFAULT");
    } else if (editorType.startsWith(PropertyTypeConstants.PROPERTY_TYPE_COMPONENT + ":")) {
      String type = editorType.substring(PropertyTypeConstants.PROPERTY_TYPE_COMPONENT.length() + 2);
      type = type.substring(type.lastIndexOf('.') + 1);
      return new YoungAndroidComponentSelectorPropertyEditor(editor, Collections.singleton(type));
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_CONCEPT_URI)) {
      return new SemanticWebPropertyEditor(SemanticWebPropertyEditor.SemanticWebSearchType.CONCEPT_URI);
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_PROPERTY_URI)) {
      return new SemanticWebPropertyEditor(SemanticWebPropertyEditor.SemanticWebSearchType.PROPERTY_URI);
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_CHART_TYPE)) {
      return new YoungAndroidChartTypeChoicePropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_DATA_FILE_COLUMN)) {
      return new YoungAndroidDataColumnSelectorProperty(editor);
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_CHART_DATA_SOURCE)) {
      return new YoungAndroidComponentSelectorPropertyEditor(editor, CHART_DATA_SOURCES);
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_CHART_PIE_RADIUS)) {
      return new YoungAndroidIntegerRangePropertyEditor(0, 100);
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_CHART_POINT_SHAPE)) {
      return new YoungAndroidChartPointShapeChoicePropertyEditor();
    } else if (editorType.equals(PropertyTypeConstants.PROPERTY_TYPE_CHART_LINE_TYPE)) {
      return new YoungAndroidChartLineTypeChoicePropertyEditor();
    } else {
      return new TextPropertyEditor();
    }
  }

  // TODO(hal):  The individual property methods above should be replaced by a single generic
  // method getExistingPropertyEditor that
  // retrieves the property editor for the named property and checks its type.  Here's how the
  // code should go.  While this compiles in Java, it sadly
  // does not compile in GWT, which has not yet implemented type-safe generic casting.
  // Sigh.  Well, maybe someday.

// /**
//  * Returns the existing property editor for the given name.
//  *
//  * @throws IllegalStateException  if no such property editor exists, or if
//  * the editor does not have the required class
//  * @param name  property name
//  * @param C the required class of class of the property editor
//  */

// public <T extends PropertyEditor>T getExistingPropertyEditor(String name, Class<T> C)
//     throws BadPropertyEditorException {
//   PropertyEditor propEditor= null;
//   Property prop = getProperty(name);
//   if (! (prop == null)) {
//     if (prop instanceof EditableProperty) {
//       propEditor = ((EditableProperty) prop).getEditor();
//       if (! (propEditor == null)) {
//         if (! (C.isAssignableFrom(propEditor.getClass()))) {
//           throw new BadPropertyEditorException("Bad property editor");
//         }
//       }
//     }
//   }
//   return C.cast(propEditor);
// }

}

redpajama_set_name: RedPajamaGithub


text:
This repository contains the definition of the Code Climate Engine specification. This includes technical details about how to implement a static analysis engine compatible with the Code Climate ecosystem of tools, including the ability to run it locally as well as on [CodeClimate.com](https://codeclimate.com/). See [SPEC.md](SPEC.md) for the actual specification.

## What is a Code Climate Engine?

A _Code Climate Engine_ is a static analysis module. Static analysis refers to the
act of deriving data from code without actually executing it. Code Climate Engines
have been created to produce data about code quality, security, style, performance and bug risk across a variety of programming languages.

### What is the Code Climate Engine spec?

The Code Climate Engine spec describes a simple contract that must be followed to
ensure compatability with the rest of the tools in the Code Climate static analysis
ecosystem. It defines several aspects of Engine operation including input, outputs, packaging, as well as performance and security restrictions.

## What is the promise of the Code Climate Engine spec?

Defining a simple specification that any static analysis tool can easily conform
to makes it possible to integrate them all into a clear, unified workflow for developers. Engines can be run locally at any time on developers' laptops on the command line, but can also be set up to run on CodeClimate.com (which is free for open source) automatically after every commit and Pull Request.

## What are some implementations of the spec?

The most mature implementations of the spec are:

* codeclimate-rubocop
* codeclimate-govet
* codeclimate-golint
* codeclimate-gofmt
* codeclimate-watson
* codecliamte-rubymotion
* codecliamte-coffeelint
* codeclimate-csslint

## Working with the spec

To get started implementing an Engine, first install the **[Code Climate CLI](https://github.com/codeclimate/codeclimate)**. Once that is installed, build your Engine as a Docker image (see the Packaging section of the SPEC). When you are ready to test it locally, run:

    $ codeclimate analyze --dev

The `--dev` flag will allow you to use the CLI with docker images that are in your local registry but not yet officially released.


text:
namespace llvm {

class raw_ostream;

namespace pdb {

class PDBSymbolCompiland : public PDBSymbol {
public:
  PDBSymbolCompiland(const IPDBSession &PDBSession,
                     std::unique_ptr<IPDBRawSymbol> CompilandSymbol);

  DECLARE_PDB_SYMBOL_CONCRETE_TYPE(PDB_SymType::Compiland)

  void dump(PDBSymDumper &Dumper) const override;

  FORWARD_SYMBOL_METHOD(isEditAndContinueEnabled)
  FORWARD_SYMBOL_METHOD(getLexicalParentId)
  FORWARD_SYMBOL_METHOD(getLibraryName)
  FORWARD_SYMBOL_METHOD(getName)

  std::string getSourceFileName() const;
};
}
}

#endif // LLVM_DEBUGINFO_PDB_PDBSYMBOLCOMPILAND_H


text:
var urlUtils      = hammerhead.utils.url;
var nativeMethods = hammerhead.nativeMethods;
var StyleSandbox  = hammerhead.sandboxes.StyleSandbox;
var styleSandbox  = hammerhead.sandbox.style;
var browserUtils  = hammerhead.utils.browser;

function getNativeStylePropValue (el, prop) {
    var nativeStyle = nativeMethods.htmlElementStyleGetter.call(el);

    return nativeMethods.styleGetPropertyValue.call(nativeStyle, prop);
}

function setNativeStyleProp (el, prop, value) {
    var nativeStyle = nativeMethods.htmlElementStyleGetter.call(el);

    return nativeMethods.styleSetProperty.call(nativeStyle, prop, value);
}

test('set the "style" property', function () {
    var div = document.createElement('div');
    var url = '/image.jpg';

    div.style = 'background-image:url("' + url + '")';

    var actualBackgroundImageValue   = removeDoubleQuotes(getNativeStylePropValue(div, 'background-image'));
    var expectedBackgroundImageValue = nativeMethods.htmlElementStyleSetter
        ? removeDoubleQuotes('url("' + urlUtils.getProxyUrl(url) + '")')
        : '';

    strictEqual(actualBackgroundImageValue, expectedBackgroundImageValue);
});

test('set the "style" attribute', function () {
    var div                         = document.createElement('div');
    var proxiedBackgroundImageValue = 'url("' + urlUtils.getProxyUrl('index.png') + '")';

    div.setAttribute('style', 'background-image: url(index.png);');

    var actualBackgroundImageValue = removeDoubleQuotes(getNativeStylePropValue(div, 'background-image'));

    strictEqual(actualBackgroundImageValue, removeDoubleQuotes(proxiedBackgroundImageValue));

    var getAttributeResult = 'background-image: url("' + urlUtils.resolveUrlAsDest('index.png') + '");';

    if (!browserUtils.isIE11)
        getAttributeResult = removeDoubleQuotes(getAttributeResult);

    strictEqual(div.getAttribute('style'), getAttributeResult);
});

test('cssText', function () {
    var div      = document.createElement('div');
    var url      = '/image.png';
    var proxyUrl = urlUtils.getProxyUrl(url);

    div.style.cssText = 'background-image:url("' + url + '")';

    var actualBackgroundImageValue   = removeDoubleQuotes(getNativeStylePropValue(div, 'background-image'));
    var expectedBackgroundImageValue = removeDoubleQuotes('url("' + proxyUrl + '")');

    strictEqual(actualBackgroundImageValue, expectedBackgroundImageValue);
    strictEqual(div.style.cssText.indexOf(proxyUrl), -1);
});

test('insertRule', function () {
    var style    = document.createElement('style');
    var url      = '/image.png';
    var proxyUrl = urlUtils.getProxyUrl(url);

    document.head.appendChild(style);

    var actualRuleIndex = document.styleSheets[0].insertRule('div { background-image: url("' + url + '"); }');
    var actualRules = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
    var actualRule = removeDoubleQuotes(actualRules[0].cssText);

    strictEqual(actualRuleIndex, 0);
    strictEqual(actualRule, removeDoubleQuotes('div { background-image: url("' + proxyUrl + '")' + '; }'));
});

test('url properties', function () {
    var div      = document.createElement('div');
    var url      = 'http://some.domain.com/image.png';
    var proxyUrl = urlUtils.getProxyUrl(url);
    var value    = 'url(' + url + ')';

    styleSandbox.URL_PROPS.forEach(function (prop) {
        // NOTE: If we setup `borderImage` property then it affects a `borderImageSource` property.
        var affectedProp       = prop === 'borderImage' ? 'borderImageSource' : prop;
        var dashedProp         = StyleSandbox._convertToDashed(prop);
        var dashedAffectedProp = StyleSandbox._convertToDashed(affectedProp);

        setNativeStyleProp(div, dashedProp, value);

        var nativeValue  = getNativeStylePropValue(div, dashedAffectedProp);
        var proxiedValue = nativeValue && nativeValue.replace(url, proxyUrl);

        div.style.removeProperty(dashedProp);

        div.style[prop] = value;

        strictEqual(div.style[affectedProp], nativeValue, prop + ' dest');
        strictEqual(getNativeStylePropValue(div, dashedAffectedProp), proxiedValue, prop + ' proxy');

        if (prop !== dashedProp) {
            div.style.removeProperty(dashedProp);

            div.style[dashedProp] = value;

            strictEqual(div.style[dashedAffectedProp], nativeValue, dashedProp + ' dest');
            strictEqual(getNativeStylePropValue(div, dashedAffectedProp), proxiedValue, dashedProp + ' proxy');
        }
    });
});

test('getPropertyValue, setProperty, getPropertyValue (GH-1212)', function () {
    var div      = document.createElement('div');
    var url      = 'http://some.domain.com/image.png';
    var proxyUrl = urlUtils.getProxyUrl(url);

    div.style.setProperty('background', 'url(' + url + ')', '');

    ok(getNativeStylePropValue(div, 'background').indexOf(proxyUrl) !== -1);
    ok(div.style.getPropertyValue('background').indexOf(proxyUrl) === -1);
    ok(div.style.getPropertyValue('background').indexOf(url) !== -1);

    var oldValue = div.style.removeProperty('background');

    ok(oldValue.indexOf(proxyUrl) === -1);

    div.style.setProperty('background', null);

    ok(!div.style.background);
    ok(!div.style.getPropertyValue('background'));
    ok(!div.style.removeProperty('background'));
});

test('wrappers of native functions should return the correct string representations', function () {
    window.checkStringRepresentation(window.CSSStyleSheet.prototype.insertRule, nativeMethods.styleInsertRule,
        'CSSStyleSheet.prototype.insertRule');
    window.checkStringRepresentation(window.CSSStyleDeclaration.prototype.getPropertyValue,
        nativeMethods.styleGetPropertyValue,
        'CSSStyleDeclaration.prototype.getPropertyValue');
    window.checkStringRepresentation(window.CSSStyleDeclaration.prototype.setProperty, nativeMethods.styleSetProperty,
        'CSSStyleDeclaration.prototype.setProperty');
    window.checkStringRepresentation(window.CSSStyleDeclaration.prototype.removeProperty,
        nativeMethods.styleRemoveProperty,
        'CSSStyleDeclaration.prototype.removeProperty');
});

module('regression');

test('the getAttribute function should return cleaned style (GH-1922)', function () {
    var div = document.createElement('div');

    div.setAttribute('style', 'background-color: red;');

    strictEqual(div.getAttribute('style'), 'background-color: red;');

    div.style.backgroundColor = 'green';

    strictEqual(div.getAttribute('style'), 'background-color: green;');

    div.style.display = 'none';

    strictEqual(div.getAttribute('style'), browserUtils.isIE
        ? 'display: none; background-color: green;'
        : 'background-color: green; display: none;');
});

test('the appendData function should append processed text (TC-3830)', function () {
    const style    = document.createElement('style');
    const textNode = document.createTextNode('');

    style.appendChild(textNode);

    textNode.appendData('\n.class:hover{}\n');

    strictEqual(textNode.data, '\n.class[data-hammerhead-hovered]{}\n');
});

test('the appendData function does not break if there is no parent element (TC-3830)', function () {
    const textNode = document.createTextNode('');

    textNode.appendData('\n.class:hover{}\n');

    strictEqual(textNode.data, '\n.class:hover{}\n');
});

test('override properties in the CSSStyleDeclaration.prototype (GH-7166)', function () {
    return createTestIframe({ src: getSameDomainPageUrl('../../data/style-sandbox/index.html') })
        .then(function (iframe) {
            var iframeDocument = iframe.contentDocument;
            var item           = iframeDocument.querySelector('div');

            strictEqual(removeDoubleQuotes(item.style.backgroundImage), 'url(https://domain.com/test.svg)');
            strictEqual(removeDoubleQuotes(item.style.backgroundImage), 'url(https://domain.com/test.svg)');
        });
});


text:
(function(){

  angular
    .module('app')
    .controller('ListController', [
      'sitesService', '$scope',
      ListController
    ]);

  function ListController(sitesService, $scope) {

    self = this;

    self.siteData = [];

    sitesService
      .loadAllItems()
      .then(function(siteData) {
        self.siteData = [].concat(siteData);
      });
  }

})();


text:
package com.pratamawijaya.examplematerialnavdrawerneokre.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.pratamawijaya.examplematerialnavdrawerneokre.R;

/**
 * Created by pratama on 3/2/15.
 */
public class NewsFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.fragment_news, container, false);
        return v;

    }
}


text:
using Piranha.Extend.Fields;

namespace Piranha.Extend.Blocks;

/// <summary>
/// Single column text block.
/// </summary>
[BlockType(Name = "Text", Category = "Content", Icon = "fas fa-font", Component = "text-block")]
public class TextBlock : Block, ISearchable, ITranslatable
{
    /// <summary>
    /// Gets/sets the text body.
    /// </summary>
    public TextField Body { get; set; }

    /// <summary>
    /// Gets the title of the block when used in a block group.
    /// </summary>
    /// <returns>The title</returns>
    public override string GetTitle()
    {
        if (Body?.Value != null)
        {
            return Body.Value;
        }
        return "Empty";
    }

    /// <summary>
    /// Gets the content that should be indexed for searching.
    /// </summary>
    public string GetIndexedContent()
    {
        return !string.IsNullOrEmpty(Body.Value) ? Body.Value : "";
    }

    /// <summary>
    /// Implicitly converts the Text block to a string.
    /// </summary>
    /// <param name="block">The block</param>
    public static implicit operator string(TextBlock block)
    {
        return block.Body?.Value;
    }
}


text:
<?php

declare(strict_types=1);

namespace App\Repository;

use App\Classes\IndexableCourse;
use App\Classes\IndexableSession;
use App\Entity\Course;
use App\Entity\Session;
use App\Traits\ManagerRepository;
use DateTime;
use Doctrine\DBAL\DBALException;
use Doctrine\ORM\AbstractQuery;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\QueryBuilder;
use App\Entity\DTO\CourseDTO;
use Doctrine\Persistence\ManagerRegistry;
use Exception;

use function array_values;
use function array_keys;

class CourseRepository extends ServiceEntityRepository implements
    DTORepositoryInterface,
    RepositoryInterface
{
    use ManagerRepository;

    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Course::class);
    }

    /**
     * Find and hydrate as DTOs
     */
    public function findDTOsBy(array $criteria, array $orderBy = null, $limit = null, $offset = null): array
    {
        if (array_key_exists('startDate', $criteria)) {
            $criteria['startDate'] = new DateTime($criteria['startDate']);
        }
        if (array_key_exists('endDate', $criteria)) {
            $criteria['endDate'] = new DateTime($criteria['endDate']);
        }
        $qb = $this->_em->createQueryBuilder()->select('x')->distinct()->from(Course::class, 'x');
        $this->attachCriteriaToQueryBuilder($qb, $criteria, $orderBy, $limit, $offset);

        $dtos = [];
        foreach ($qb->getQuery()->getResult(AbstractQuery::HYDRATE_ARRAY) as $arr) {
            $dtos[$arr['id']] = new CourseDTO(
                $arr['id'],
                $arr['title'],
                $arr['level'],
                $arr['year'],
                $arr['startDate'],
                $arr['endDate'],
                $arr['externalId'],
                $arr['locked'],
                $arr['archived'],
                $arr['publishedAsTbd'],
                $arr['published']
            );
        }
        return $this->attachAssociationsToDTOs($dtos);
    }

    public function getYears(): array
    {
        $dql = 'SELECT DISTINCT c.year FROM App\Entity\Course c ORDER BY c.year ASC';
        $results = $this->getEntityManager()->createQuery($dql)->getArrayResult();

        $return = [];
        foreach ($results as $arr) {
            $return[] = $arr['year'];
        }

        return $return;
    }

    /**
     * Get all the IDs
     */
    public function getIds(): array
    {
        $qb = $this->_em->createQueryBuilder();
        $qb->addSelect('x.id')->from(Course::class, 'x');

        return array_map(fn(array $arr) => $arr['id'], $qb->getQuery()->getScalarResult());
    }

    /**
     * Finds all courses associated with a given user.
     * A user can be associated as either course director, learner or instructor with a given course.
     *
     * @param int $userId
     * @param array|null $orderBy
     * @param null $limit
     * @param null $offset
     * @return CourseDTO[]
     * @throws Exception
     */
    public function findByUserId(
        $userId,
        array $criteria,
        array $orderBy = null,
        $limit = null,
        $offset = null
    ) {
        $rows = $this->findMyCourses($userId, $criteria, $orderBy, $limit, $offset);

        $courseDTOs = [];
        foreach ($rows as $arr) {
            $courseDTOs[$arr['course_id']] = new CourseDTO(
                (int) $arr['course_id'],
                $arr['title'],
                (int) $arr['course_level'],
                (int) $arr['year'],
                new DateTime($arr['start_date']),
                new DateTime($arr['end_date']),
                $arr['external_id'],
                (bool) $arr['locked'],
                (bool) $arr['archived'],
                (bool) $arr['published_as_tbd'],
                (bool) $arr['published']
            );
        }

        return $this->attachAssociationsToDTOs($courseDTOs);
    }

    protected function findMyCourses(
        int $userId,
        array $criteria,
        array $orderBy = null,
        ?int $limit = null,
        ?int $offset = null
    ): array {
        $meta = $this->_em->getClassMetadata(Course::class);

        if (empty($orderBy)) {
            $orderBy = ['id' => 'ASC'];
        }

        $sql = <<<EOL
SELECT * FROM (
  SELECT c.* FROM course c
    JOIN course_director cd ON cd.course_id = c.course_id
    JOIN user u ON u.user_id = cd.user_id
    WHERE u.user_id = :user_id
  UNION
  SELECT c.* FROM course c
    JOIN `session` s ON s.course_id = c.course_id
    JOIN offering o ON o.session_id = s.session_id
    JOIN offering_x_learner oxl ON oxl.offering_id = o.offering_id
    JOIN user u ON u.user_id = oxl.user_id
    WHERE u.user_id = :user_id
  UNION
  SELECT c.* FROM course c
    JOIN `session` s ON s.course_id = c.course_id
    JOIN offering o ON o.session_id = s.session_id
    JOIN offering_x_group oxg ON oxg.offering_id = o.offering_id
    JOIN `group` g ON g.group_id = oxg.group_id
    JOIN group_x_user gxu ON gxu.group_id = g.group_id
    JOIN user u ON u.user_id = gxu.user_id
    WHERE u.user_id = :user_id
  UNION
  SELECT c.* FROM course c
    JOIN `session` s ON s.course_id = c.course_id
    JOIN ilm_session_facet ilm ON ilm.session_id = s.session_id
    JOIN ilm_session_facet_x_learner ilmxl ON ilmxl.ilm_session_facet_id = ilm.ilm_session_facet_id
    JOIN user u ON u.user_id = ilmxl.user_id
    WHERE u.user_id = :user_id
  UNION
  SELECT c.* FROM course c
    JOIN `session` s ON s.course_id = c.course_id
    JOIN ilm_session_facet ilm ON ilm.session_id = s.session_id
    JOIN ilm_session_facet_x_group ilmxg ON ilmxg.ilm_session_facet_id = ilm.ilm_session_facet_id
    JOIN `group` g ON g.group_id = ilmxg.group_id
    JOIN group_x_user gxu ON gxu.group_id = g.group_id
    JOIN user u ON u.user_id = gxu.user_id
    WHERE u.user_id = :user_id
  UNION
  SELECT c.* FROM course c
    JOIN `session` s ON s.course_id = c.course_id
    JOIN offering o ON o.session_id = s.session_id
    JOIN offering_x_instructor oxi ON oxi.offering_id = o.offering_id
    JOIN user u ON u.user_id = oxi.user_id
    WHERE u.user_id = :user_id
  UNION
  SELECT c.* FROM course c
    JOIN `session` s ON s.course_id = c.course_id
    JOIN offering o ON o.session_id = s.session_id
    JOIN offering_x_instructor_group oxig ON oxig.offering_id = o.offering_id
    JOIN instructor_group ig ON ig.instructor_group_id = oxig.instructor_group_id
    JOIN instructor_group_x_user igxu ON igxu.instructor_group_id = ig.instructor_group_id
    JOIN user u ON u.user_id = igxu.user_id
    WHERE u.user_id = :user_id
  UNION
  SELECT c.* FROM course c
    JOIN `session` s ON s.course_id = c.course_id
    JOIN ilm_session_facet ilm ON ilm.session_id = s.session_id
    JOIN ilm_session_facet_x_instructor ilmxi ON ilmxi.ilm_session_facet_id = ilm.ilm_session_facet_id
    JOIN user u ON u.user_id = ilmxi.user_id
    WHERE u.user_id = :user_id
  UNION
  SELECT c.* FROM course c
    JOIN `session` s ON s.course_id = c.course_id
    JOIN ilm_session_facet ilm ON ilm.session_id = s.session_id
    JOIN ilm_session_facet_x_instructor_group ilmxig ON ilmxig.ilm_session_facet_id = ilm.ilm_session_facet_id
    JOIN instructor_group ig ON ig.instructor_group_id = ilmxig.instructor_group_id
    JOIN instructor_group_x_user igxu ON igxu.instructor_group_id = ig.instructor_group_id
    JOIN user u ON u.user_id = igxu.user_id
    WHERE u.user_id = :user_id
  UNION
  SELECT c.* FROM course c
    JOIN course_administrator ca ON c.course_id = ca.course_id
    JOIN user u ON u.user_id = ca.user_id
    WHERE u.user_id = :user_id
) AS my_courses
EOL;

        $params = [];
        $i = 0;
        $sqlFragments = [];
        foreach ($criteria as $name => $value) {
            $i++;
            if (!$meta->hasField($name)) {
                throw new Exception(sprintf('"%s" is not a property of the Course entity.', $name));
            }

            $column = $meta->getColumnName($name);
            $label = ':param' . $i;
            if (is_array($value)) {
                $labels = array_map(fn($j) => "${label}_${j}", range(0, count($value) - 1));
                $params[$name] = $labels;
                $sqlFragments[] = "{$column} IN (" . implode(', ', $labels) . ")";
            } else {
                $params[$name] = $label;
                $sqlFragments[] = "{$column} = {$label}";
            }
        }
        if ($sqlFragments !== []) {
            $sql .= ' WHERE ' . implode(' AND ', $sqlFragments);
        }

        if (is_array($orderBy)) {
            $sqlFragments = [];
            foreach ($orderBy as $sort => $order) {
                if (!$meta->hasField($sort)) {
                    throw new Exception(sprintf('"%s" is not a property of the Course entity.', $sort));
                }
                $column = $meta->getColumnName($sort);
                $sqlFragments[] = "{$column} " . ('desc' === strtolower($order) ? 'DESC' : 'ASC');
            }
            $sql .= ' ORDER BY ';
            $sql .= implode(', ', $sqlFragments);
        }

        if (isset($limit)) {
            $sql .= ' LIMIT :limit';
        }

        if (isset($offset)) {
            $sql .= ' OFFSET :offset';
        }

        $conn = $this->getEntityManager()->getConnection();
        $stmt = $conn->prepare($sql);
        $stmt->bindValue(":user_id", (int) $userId);
        foreach ($params as $field => $label) {
            $value = $criteria[$field];
            if (is_array($label)) {
                $arr = array_combine($label, $value);
                foreach ($arr as $label => $value) {
                    $stmt->bindValue($label, $value);
                }
            } else {
                $stmt->bindValue($label, $value);
            }
        }

        if (isset($limit)) {
            $stmt->bindValue(":limit", (int) $limit);
        }
        if (isset($offset)) {
            $stmt->bindValue(":offset", (int) $offset);
        }
        $result = $stmt->execute();
        $rows = $result->fetchAllAssociative();
        $result->free();
        return $rows;
    }

    protected function attachAssociationsToDTOs(array $dtos): array
    {
        $courseIds = array_keys($dtos);

        $qb = $this->_em->createQueryBuilder();
        $qb->select('s.id as schoolId, cl.id as clerkshipTypeId, a.id as ancestorId, c.id as courseId')
            ->from(Course::class, 'c')
            ->join('c.school', 's')
            ->leftJoin('c.clerkshipType', 'cl')
            ->leftJoin('c.ancestor', 'a')
            ->where($qb->expr()->in('c.id', ':courseIds'))
            ->setParameter('courseIds', $courseIds);

        foreach ($qb->getQuery()->getResult() as $arr) {
            $dtos[$arr['courseId']]->school = (int)$arr['schoolId'];
            $dtos[$arr['courseId']]->clerkshipType =
                $arr['clerkshipTypeId'] ? (int)$arr['clerkshipTypeId'] : null;
            $dtos[$arr['courseId']]->ancestor = $arr['ancestorId'] ? (int)$arr['ancestorId'] : null;
        }

        $dtos = $this->attachRelatedToDtos(
            $dtos,
            [
                'directors',
                'administrators',
                'studentAdvisors',
                'cohorts',
                'terms',
                'courseObjectives',
                'meshDescriptors',
                'learningMaterials',
                'sessions',
                'descendants',
            ],
        );

        return array_values($dtos);
    }

    protected function attachCriteriaToQueryBuilder(
        QueryBuilder $qb,
        array $criteria,
        ?array $orderBy,
        ?int $limit,
        ?int $offset
    ): void {
        if (array_key_exists('sessions', $criteria)) {
            $ids = is_array($criteria['sessions']) ? $criteria['sessions'] : [$criteria['sessions']];
            $qb->join('x.sessions', 'se_session');
            $qb->andWhere($qb->expr()->in('se_session.id', ':sessions'));
            $qb->setParameter(':sessions', $ids);
        }

        if (array_key_exists('terms', $criteria)) {
            $ids = is_array($criteria['terms']) ? $criteria['terms'] : [$criteria['terms']];
            $qb->leftJoin('x.terms', 't_term1');
            $qb->leftJoin('x.sessions', 't_session');
            $qb->leftJoin('t_session.terms', 't_term2');
            $qb->andWhere($qb->expr()->orX(
                $qb->expr()->in('t_term1.id', ':terms'),
                $qb->expr()->in('t_term2.id', ':terms')
            ));
            $qb->setParameter(':terms', $ids);
        }

        if (array_key_exists('programs', $criteria)) {
            $ids = is_array($criteria['programs']) ? $criteria['programs'] : [$criteria['programs']];
            $qb->join('x.cohorts', 'p_cohort');
            $qb->join('p_cohort.programYear', 'p_programYear');
            $qb->join('p_programYear.program', 'p_program');
            $qb->andWhere($qb->expr()->in('p_program.id', ':programs'));
            $qb->setParameter(':programs', $ids);
        }

        if (array_key_exists('programYears', $criteria)) {
            $ids = is_array($criteria['programYears']) ? $criteria['programYears'] : [$criteria['programYears']];
            $qb->join('x.cohorts', 'py_cohort');
            $qb->join('py_cohort.programYear', 'py_programYear');
            $qb->andWhere($qb->expr()->in('py_programYear.id', ':programYears'));
            $qb->setParameter(':programYears', $ids);
        }

        if (array_key_exists('instructors', $criteria)) {
            $ids = is_array($criteria['instructors']) ? $criteria['instructors'] : [$criteria['instructors']];
            $qb->leftJoin('x.sessions', 'i_session');
            $qb->leftJoin('x.directors', 'i_director');
            $qb->leftJoin('i_session.offerings', 'i_offering');
            $qb->leftJoin('i_offering.instructors', 'i_user');
            $qb->leftJoin('i_offering.instructorGroups', 'i_insGroup');
            $qb->leftJoin('i_insGroup.users', 'i_groupUser');
            $qb->leftJoin('i_session.ilmSession', 'i_ilmSession');
            $qb->leftJoin('i_ilmSession.instructors', 'i_ilmInstructor');
            $qb->leftJoin('i_ilmSession.instructorGroups', 'i_ilmInsGroup');
            $qb->leftJoin('i_ilmInsGroup.users', 'i_ilmInsGroupUser');
            $qb->andWhere($qb->expr()->orX(
                $qb->expr()->in('i_director.id', ':users'),
                $qb->expr()->in('i_user.id', ':users'),
                $qb->expr()->in('i_groupUser.id', ':users'),
                $qb->expr()->in('i_ilmInstructor.id', ':users'),
                $qb->expr()->in('i_ilmInsGroupUser.id', ':users')
            ));
            $qb->setParameter(':users', $ids);
        }

        if (array_key_exists('instructorGroups', $criteria)) {
            $ids = is_array($criteria['instructorGroups']) ?
                $criteria['instructorGroups'] : [$criteria['instructorGroups']];
            $qb->leftJoin('x.sessions', 'ig_session');
            $qb->leftJoin('ig_session.offerings', 'ig_offering');
            $qb->leftJoin('ig_offering.instructorGroups', 'ig_igroup');
            $qb->leftJoin('ig_session.ilmSession', 'ig_ilmSession');
            $qb->leftJoin('ig_ilmSession.instructorGroups', 'ig_ilmInsGroup');
            $qb->andWhere(
                $qb->expr()->orX(
                    $qb->expr()->in('ig_igroup.id', ':igroups'),
                    $qb->expr()->in('ig_ilmInsGroup.id', ':igroups')
                )
            );
            $qb->setParameter(':igroups', $ids);
        }

        if (array_key_exists('learningMaterials', $criteria)) {
            $ids = is_array($criteria['learningMaterials']) ?
                $criteria['learningMaterials'] : [$criteria['learningMaterials']];
            $qb->leftJoin('x.learningMaterials', 'lm_clm');
            $qb->leftJoin('lm_clm.learningMaterial', 'lm_lm');
            $qb->leftJoin('x.sessions', 'lm_session');
            $qb->leftJoin('lm_session.learningMaterials', 'lm_slm');
            $qb->leftJoin('lm_slm.learningMaterial', 'lm_lm2');
            $qb->andWhere($qb->expr()->orX(
                $qb->expr()->in('lm_lm.id', ':lms'),
                $qb->expr()->in('lm_lm2.id', ':lms')
            ));
            $qb->setParameter(':lms', $ids);
        }

        if (array_key_exists('competencies', $criteria)) {
            $ids = is_array($criteria['competencies']) ? $criteria['competencies'] : [$criteria['competencies']];
            $qb->join('x.courseObjectives', 'c_course_objective');
            $qb->join('c_course_objective.programYearObjectives', 'c_program_year_objective');
            $qb->leftJoin('c_program_year_objective.competency', 'c_competency');
            $qb->leftJoin('c_competency.parent', 'c_competency2');
            $qb->andWhere($qb->expr()->orX(
                $qb->expr()->in('c_competency.id', ':competencies'),
                $qb->expr()->in('c_competency2.id', ':competencies')
            ));
            $qb->setParameter(':competencies', $ids);
        }

        if (array_key_exists('meshDescriptors', $criteria)) {
            $ids = is_array($criteria['meshDescriptors']) ?
                $criteria['meshDescriptors'] : [$criteria['meshDescriptors']];
            $qb->leftJoin('x.meshDescriptors', 'm_meshDescriptor');
            $qb->leftJoin('x.sessions', 'm_session');
            $qb->leftJoin('m_session.meshDescriptors', 'm_sessMeshDescriptor');
            $qb->leftJoin('x.courseObjectives', 'm_cObjective');
            $qb->leftJoin('m_cObjective.meshDescriptors', 'm_cObjectiveMeshDescriptor');
            $qb->leftJoin('m_session.sessionObjectives', 'm_sObjective');
            $qb->leftJoin('m_sObjective.meshDescriptors', 'm_sObjectiveMeshDescriptors');
            $qb->andWhere($qb->expr()->orX(
                $qb->expr()->in('m_meshDescriptor.id', ':meshDescriptors'),
                $qb->expr()->in('m_sessMeshDescriptor.id', ':meshDescriptors'),
                $qb->expr()->in('m_cObjectiveMeshDescriptor.id', ':meshDescriptors'),
                $qb->expr()->in('m_sObjectiveMeshDescriptors.id', ':meshDescriptors')
            ));
            $qb->setParameter(':meshDescriptors', $ids);
        }

        if (array_key_exists('schools', $criteria)) {
            $ids = is_array($criteria['schools']) ? $criteria['schools'] : [$criteria['schools']];
            $qb->join('x.school', 'sc_school');
            $qb->andWhere($qb->expr()->in('sc_school.id', ':schools'));
            $qb->setParameter(':schools', $ids);
        }

        if (array_key_exists('ancestors', $criteria)) {
            $ids = is_array($criteria['ancestors']) ? $criteria['ancestors'] : [$criteria['ancestors']];
            $qb->join('x.ancestor', 'anc_course');
            $qb->andWhere($qb->expr()->in('anc_course.id', ':ancestors'));
            $qb->setParameter(':ancestors', $ids);
        }

        //cleanup all the possible relationship filters
        unset($criteria['schools']);
        unset($criteria['sessions']);
        unset($criteria['terms']);
        unset($criteria['programs']);
        unset($criteria['programYears']);
        unset($criteria['instructors']);
        unset($criteria['instructorGroups']);
        unset($criteria['learningMaterials']);
        unset($criteria['competencies']);
        unset($criteria['meshDescriptors']);
        unset($criteria['ancestors']);

        $this->attachClosingCriteriaToQueryBuilder($qb, $criteria, $orderBy, $limit, $offset);
    }

    /**
     * Create course index objects for a set of courses
     *
     */
    public function getCourseIndexesFor(array $courseIds): array
    {
        $qb = $this->_em->createQueryBuilder();
        $qb->select(
            'c.id AS id, c.title AS title, c.level AS level, c.year AS year, ' .
            'c.startDate AS startDate, c.endDate AS endDate, c.externalId AS externalId, ' .
            'c.locked AS locked, c.archived AS archived, c.publishedAsTbd AS publishedAsTbd, ' .
            'c.published AS published, s.title as school, cl.title as clerkshipType'
        )
            ->from(Course::class, 'c')
            ->join('c.school', 's')
            ->leftJoin('c.clerkshipType', 'cl')
            ->where($qb->expr()->in('c.id', ':courseIds'))
            ->setParameter('courseIds', $courseIds);

        /** @var IndexableCourse[] $indexableCourses */
        $indexableCourses = [];
        foreach ($qb->getQuery()->getResult(AbstractQuery::HYDRATE_ARRAY) as $arr) {
            $index = new IndexableCourse();
            $index->courseDTO = new CourseDTO(
                $arr['id'],
                $arr['title'],
                $arr['level'],
                $arr['year'],
                $arr['startDate'],
                $arr['endDate'],
                $arr['externalId'],
                $arr['locked'],
                $arr['archived'],
                $arr['publishedAsTbd'],
                $arr['published']
            );
            $index->school = $arr['school'];
            $index->clerkshipType = $arr['clerkshipType'] ? $arr['clerkshipType'] : null;

            $indexableCourses[$arr['id']] = $index;
        }

        $directors = $this->joinResults(
            Course::class,
            'directors',
            "CONCAT(r.firstName, ' ', r.lastName, ' ', r.displayName) AS name",
            $courseIds
        );
        foreach ($directors as $courseId => $arr) {
            $indexableCourses[$courseId]->directors[] = $arr[0]['name'];
        }

        $administrators = $this->joinResults(
            Course::class,
            'administrators',
            "CONCAT(r.firstName, ' ', r.lastName, ' ', r.displayName) AS name",
            $courseIds
        );
        foreach ($administrators as $courseId => $arr) {
            $indexableCourses[$courseId]->administrators[] = $arr[0]['name'];
        }

        $terms = $this->joinResults(
            Course::class,
            'terms',
            "r.title",
            $courseIds
        );
        foreach ($terms as $courseId => $arr) {
            $indexableCourses[$courseId]->terms[] = $arr[0]['title'];
        }

        $objectives = $this->joinObjectiveResults(
            Course::class,
            'courseObjectives',
            'o.title',
            $courseIds
        );
        foreach ($objectives as $courseId => $arr) {
            $indexableCourses[$courseId]->objectives[] = $arr[0]['title'];
        }

        $meshDescriptors = $this->joinResults(
            Course::class,
            'meshDescriptors',
            "r.id, r.name, r.annotation",
            $courseIds
        );
        foreach ($meshDescriptors as $courseId => $courseDescriptors) {
            foreach ($courseDescriptors as $arr) {
                $indexableCourses[$courseId]->meshDescriptorIds[] = $arr['id'];
                $indexableCourses[$courseId]->meshDescriptorNames[] = $arr['name'];
                $indexableCourses[$courseId]->meshDescriptorAnnotations[] = $arr['annotation'];
            }
        }

        $qb = $this->_em->createQueryBuilder()
            ->select("c.id AS courseId, l.id as learningMaterialId, l.relativePath, " .
                "l.title, l.description, l.citation")
            ->from(Course::class, 'c')
            ->join("c.learningMaterials", 'clm')
            ->join("clm.learningMaterial", 'l')
            ->where($qb->expr()->in('c.id', ':ids'))
            ->setParameter('ids', $courseIds);

        foreach ($qb->getQuery()->getResult() as $arr) {
            $indexableCourses[$arr['courseId']]->learningMaterialTitles[] = $arr['title'];
            $indexableCourses[$arr['courseId']]->learningMaterialDescriptions[] = $arr['description'];
            $indexableCourses[$arr['courseId']]->learningMaterialCitations[] = $arr['citation'];
            if ($arr['relativePath']) {
                $indexableCourses[$arr['courseId']]->fileLearningMaterialIds[] = $arr['learningMaterialId'];
            }
        }

        $arr = $this->joinResults(
            Course::class,
            'sessions',
            "r.id AS sessionId",
            $courseIds
        );

        $sessionIds = array_reduce(
            $arr,
            fn(array $carry, array $item) => array_merge($carry, array_column($item, 'sessionId')),
            []
        );

        $chunks = array_chunk(array_unique($sessionIds), 500);
        foreach ($chunks as $ids) {
            $indexableSessions = $this->sessionDataForIndex($ids);
            foreach ($indexableSessions as $session) {
                $indexableCourses[$session->courseId]->sessions[] = $session;
            }
        }

        return array_values($indexableCourses);
    }

    /**
     */
    protected function joinResults(string $from, string $rel, string $select, array $ids): array
    {
        $qb = $this->_em->createQueryBuilder();
        $qb->select("f.id AS fromId, ${select}")->from($from, 'f')
            ->join("f.{$rel}", 'r')
            ->where($qb->expr()->in('f.id', ':ids'))
            ->setParameter('ids', $ids);

        $rhett = [];
        foreach ($qb->getQuery()->getResult() as $arr) {
            $rhett[$arr['fromId']][] = $arr;
        }

        return $rhett;
    }

    /**
     */
    protected function joinObjectiveResults(string $from, string $rel, string $select, array $ids): array
    {
        $qb = $this->_em->createQueryBuilder();
        $qb->select("f.id AS fromId, ${select}")->from($from, 'f')
            ->join("f.{$rel}", 'o')
            ->where($qb->expr()->in('f.id', ':ids'))
            ->setParameter('ids', $ids);

        $rhett = [];
        foreach ($qb->getQuery()->getResult() as $arr) {
            $rhett[$arr['fromId']][] = $arr;
        }

        return $rhett;
    }

    protected function sessionDataForIndex(array $sessionIds): array
    {
        $qb = $this->_em->createQueryBuilder();
        $qb->select(
            's.id AS sessionId, s.title AS title, s.description AS description, c.id as courseId, ' .
            'st.title AS sessionType'
        )
            ->from(Session::class, 's')
            ->join('s.course', 'c')
            ->leftJoin('s.sessionType', 'st')
            ->where($qb->expr()->in('s.id', ':ids'))
            ->setParameter('ids', $sessionIds);

        /** @var IndexableSession[] $sessions */
        $sessions = [];
        foreach ($qb->getQuery()->getResult(AbstractQuery::HYDRATE_ARRAY) as $arr) {
            $session = new IndexableSession();
            $session->courseId = $arr['courseId'];
            $session->sessionId = $arr['sessionId'];
            $session->title = $arr['title'];
            $session->sessionType = $arr['sessionType'];
            $session->description = $arr['description'];

            $sessions[$arr['sessionId']] = $session;
        }

        $administrators = $this->joinResults(
            Session::class,
            'administrators',
            "CONCAT(r.firstName, ' ', r.lastName, ' ', r.displayName) AS name",
            $sessionIds
        );
        foreach ($administrators as $sessionId => $arr) {
            $sessions[$sessionId]->administrators[] = $arr[0]['name'];
        }

        $terms = $this->joinResults(
            Session::class,
            'terms',
            "r.title",
            $sessionIds
        );
        foreach ($terms as $sessionId => $arr) {
            $sessions[$sessionId]->terms[] = $arr[0]['title'];
        }

        $objectives = $this->joinObjectiveResults(
            Session::class,
            'sessionObjectives',
            'o.title',
            $sessionIds
        );
        foreach ($objectives as $sessionId => $arr) {
            $sessions[$sessionId]->objectives[] = $arr[0]['title'];
        }

        $meshDescriptors = $this->joinResults(
            Session::class,
            'meshDescriptors',
            "r.id, r.name, r.annotation",
            $sessionIds
        );
        foreach ($meshDescriptors as $sessionId => $sessionDescriptors) {
            foreach ($sessionDescriptors as $arr) {
                $sessions[$sessionId]->meshDescriptorIds[] = $arr['id'];
                $sessions[$sessionId]->meshDescriptorNames[] = $arr['name'];
                $sessions[$sessionId]->meshDescriptorAnnotations[] = $arr['annotation'];
            }
        }

        $qb = $this->_em->createQueryBuilder()
            ->select("s.id AS sessionId, l.id as learningMaterialId, l.relativePath, " .
                "l.title, l.description, l.citation")
            ->from(Session::class, 's')
            ->join("s.learningMaterials", 'slm')
            ->join("slm.learningMaterial", 'l')
            ->where($qb->expr()->in('s.id', ':ids'))
            ->setParameter('ids', $sessionIds);

        foreach ($qb->getQuery()->getResult() as $arr) {
            $sessions[$arr['sessionId']]->learningMaterialTitles[] = $arr['title'];
            $sessions[$arr['sessionId']]->learningMaterialDescriptions[] = $arr['description'];
            $sessions[$arr['sessionId']]->learningMaterialCitations[] = $arr['citation'];
            if ($arr['relativePath']) {
                $sessions[$arr['sessionId']]->fileLearningMaterialIds[] = $arr['learningMaterialId'];
            }
        }

        return array_values($sessions);
    }
}


text:
using System;

namespace Serenity.ComponentModel
{
    /// <summary>
    /// Sets formatting type to "Boolean"
    /// </summary>
    /// <seealso cref="Serenity.ComponentModel.CustomFormatterAttribute" />
    public class BooleanFormatterAttribute : CustomFormatterAttribute
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="BooleanFormatterAttribute"/> class.
        /// </summary>
        public BooleanFormatterAttribute()
            : base("Boolean")
        {
        }

        /// <summary>
        /// Gets or sets the text corresponding to falsey value.
        /// </summary>
        /// <value>
        /// The false text.
        /// </value>
        public String FalseText
        {
            get { return GetOption<String>("falseText"); }
            set { SetOption("falseText", value); }
        }

        /// <summary>
        /// Gets or sets the text corresponding to trueish value.
        /// </summary>
        /// <value>
        /// The true text.
        /// </value>
        public String TrueText
        {
            get { return GetOption<String>("trueText"); }
            set { SetOption("trueText", value); }
        }
    }

    /// <summary>
    /// Sets formatting type to "Checkbox"
    /// </summary>
    /// <seealso cref="Serenity.ComponentModel.CustomFormatterAttribute" />
    public class CheckboxFormatterAttribute : CustomFormatterAttribute
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="CheckboxFormatterAttribute"/> class.
        /// </summary>
        public CheckboxFormatterAttribute()
            : base("Checkbox")
        {
        }
    }

    /// <summary>
    /// Sets formatting type to "Date"
    /// </summary>
    /// <seealso cref="Serenity.ComponentModel.CustomFormatterAttribute" />
    public class DateFormatterAttribute : CustomFormatterAttribute
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="DateFormatterAttribute"/> class.
        /// </summary>
        public DateFormatterAttribute()
            : base("Date")
        {
        }

        /// <summary>
        /// Gets or sets the display format.
        /// </summary>
        /// <value>
        /// The display format.
        /// </value>
        public String DisplayFormat
        {
            get { return GetOption<String>("displayFormat"); }
            set { SetOption("displayFormat", value); }
        }
    }

    /// <summary>
    /// Sets formatting type to "DateTime".
    /// </summary>
    /// <seealso cref="Serenity.ComponentModel.CustomFormatterAttribute" />
    public class DateTimeFormatterAttribute : CustomFormatterAttribute
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="DateTimeFormatterAttribute"/> class.
        /// </summary>
        public DateTimeFormatterAttribute()
            : base("DateTime")
        {
        }

        /// <summary>
        /// Gets or sets the display format.
        /// </summary>
        /// <value>
        /// The display format.
        /// </value>
        public String DisplayFormat
        {
            get { return GetOption<String>("displayFormat"); }
            set { SetOption("displayFormat", value); }
        }
    }

    /// <summary>
    /// Sets formatting type to "Enum".
    /// </summary>
    /// <seealso cref="Serenity.ComponentModel.CustomFormatterAttribute" />
    public class EnumFormatterAttribute : CustomFormatterAttribute
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="EnumFormatterAttribute"/> class.
        /// </summary>
        public EnumFormatterAttribute()
            : base("Enum")
        {
        }

        /// <summary>
        /// Gets or sets the enum key which is full namespace and
        /// class name of the enum or it should match the value
        /// set with [EnumKey] attribute on the enum type.
        /// </summary>
        /// <value>
        /// The enum key.
        /// </value>
        public String EnumKey
        {
            get { return GetOption<String>("enumKey"); }
            set { SetOption("enumKey", value); }
        }
    }

    /// <summary>
    /// Sets formatting type to "FileDownload".
    /// </summary>
    /// <seealso cref="Serenity.ComponentModel.CustomFormatterAttribute" />
    public class FileDownloadFormatterAttribute : CustomFormatterAttribute
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="FileDownloadFormatterAttribute"/> class.
        /// </summary>
        public FileDownloadFormatterAttribute()
            : base("FileDownload")
        {
        }

        /// <summary>
        /// Gets or sets the display format.
        /// </summary>
        /// <value>
        /// The display format.
        /// </value>
        public String DisplayFormat
        {
            get { return GetOption<String>("displayFormat"); }
            set { SetOption("displayFormat", value); }
        }

        /// <summary>
        /// Gets or sets the original name property which indicates
        /// the property to read original file name from (if any).
        /// </summary>
        /// <value>
        /// The original name property.
        /// </value>
        public String OriginalNameProperty
        {
            get { return GetOption<String>("originalNameProperty"); }
            set { SetOption("originalNameProperty", value); }
        }
    }

    /// <summary>
    /// Sets formatting type to "Number"
    /// </summary>
    /// <seealso cref="Serenity.ComponentModel.CustomFormatterAttribute" />
    public class NumberFormatterAttribute : CustomFormatterAttribute
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="NumberFormatterAttribute"/> class.
        /// </summary>
        public NumberFormatterAttribute()
            : base("Number")
        {
        }

        /// <summary>
        /// Gets or sets the display format.
        /// </summary>
        /// <value>
        /// The display format.
        /// </value>
        public String DisplayFormat
        {
            get { return GetOption<String>("displayFormat"); }
            set { SetOption("displayFormat", value); }
        }
    }

    /// <summary>
    /// Sets formatting type to "Minute" which formats an integer value in HH:mm format.
    /// </summary>
    /// <seealso cref="Serenity.ComponentModel.CustomFormatterAttribute" />
    public class MinuteFormatterAttribute : CustomFormatterAttribute
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MinuteFormatterAttribute"/> class.
        /// </summary>
        public MinuteFormatterAttribute()
            : base("Serenity.MinuteFormatter")
        {
        }

        /// <summary>
        /// Gets or sets the display format.
        /// </summary>
        /// <value>
        /// The display format.
        /// </value>
        public String DisplayFormat
        {
            get { return GetOption<String>("displayFormat"); }
            set { SetOption("displayFormat", value); }
        }
    }

    /// <summary>
    /// Sets formatting type to "Url"
    /// </summary>
    /// <seealso cref="Serenity.ComponentModel.CustomFormatterAttribute" />
    public class UrlFormatterAttribute : CustomFormatterAttribute
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="UrlFormatterAttribute"/> class.
        /// </summary>
        public UrlFormatterAttribute()
            : base("Url")
        {
        }

        /// <summary>
        /// Gets or sets the display property to show in hyperlink as text.
        /// </summary>
        /// <value>
        /// The display property.
        /// </value>
        public String DisplayProperty
        {
            get { return GetOption<String>("displayProperty"); }
            set { SetOption("displayProperty", value); }
        }

        /// <summary>
        /// Gets or sets the display format.
        /// </summary>
        /// <value>
        /// The display format.
        /// </value>
        public String DisplayFormat
        {
            get { return GetOption<String>("displayFormat"); }
            set { SetOption("displayFormat", value); }
        }

        /// <summary>
        /// Gets or sets the URL property.
        /// </summary>
        /// <value>
        /// The URL property.
        /// </value>
        public String UrlProperty
        {
            get { return GetOption<String>("urlProperty"); }
            set { SetOption("urlProperty", value); }
        }

        /// <summary>
        /// Gets or sets the URL format.
        /// </summary>
        /// <value>
        /// The URL format.
        /// </value>
        public String UrlFormat
        {
            get { return GetOption<String>("urlFormat"); }
            set { SetOption("urlFormat", value); }
        }

        /// <summary>
        /// Gets or sets the target window, e.g. "_blank".
        /// </summary>
        /// <value>
        /// The target.
        /// </value>
        public String Target
        {
            get { return GetOption<String>("target"); }
            set { SetOption("target", value); }
        }
    }
}


text:
package org.forpdi.planning.fields.table;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.Where;

import br.com.caelum.vraptor.boilerplate.SimpleLogicalDeletableEntity;

@Entity(name = TableFields.TABLE)
@Table(name = TableFields.TABLE)
public class TableFields extends SimpleLogicalDeletableEntity{
	public static final String TABLE = "fpdi_table_field";
	private static final long serialVersionUID = 1L;

	@OneToMany(fetch=FetchType.LAZY, mappedBy="tableFields", targetEntity=TableStructure.class)
	@Cascade(CascadeType.ALL)
	private List<TableStructure> tableStructures;

	@OneToMany(fetch=FetchType.LAZY, mappedBy="tableFields", targetEntity=TableInstance.class)
	@Cascade(CascadeType.ALL)
	@Where(clause="deleted=0")
	private List<TableInstance> tableInstances;

	@Column(nullable = false)
	private Long attributeId;

	@Column(nullable = true)
	private boolean isDocument = false;

	public List<TableStructure> getTableStructures() {
		return tableStructures;
	}

	public void setTableStructures(List<TableStructure> tableStructures) {
		this.tableStructures = tableStructures;
	}

	public List<TableInstance> getTableInstances() {
		return tableInstances;
	}

	public void setTableInstances(List<TableInstance> tableInstances) {
		this.tableInstances = tableInstances;
	}

	public Long getAttributeId() {
		return attributeId;
	}

	public void setAttributeId(Long attributeId) {
		this.attributeId = attributeId;
	}

	public boolean isDocument() {
		return isDocument;
	}

	public void setIsDocument(boolean isDocument) {
		this.isDocument = isDocument;
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">SPEED CLICKING</string>
    <string name="new_high_score">KỈ LỤC MỚI!!!</string>
    <string name="sixty_seconds_button">60 GIÂY</string>
    <string name="ten_seconds_button">10 GIÂY</string>
    <string name="thirty_seconds_button">30 GIÂY</string>
    <string name="app_name_local">Nhấp nhanh</string>
</resources>


text:
.class public interface abstract annotation Lroboguice/inject/InjectView;
.super Ljava/lang/Object;
.source "InjectView.java"

# interfaces
.implements Ljava/lang/annotation/Annotation;

# annotations
.annotation runtime Lcom/google/inject/BindingAnnotation;
.end annotation

.annotation system Ldalvik/annotation/AnnotationDefault;
    value = .subannotation Lroboguice/inject/InjectView;
        tag = ""
        value = -0x1
    .end subannotation
.end annotation

.annotation runtime Ljava/lang/annotation/Retention;
    value = .enum Ljava/lang/annotation/RetentionPolicy;->RUNTIME:Ljava/lang/annotation/RetentionPolicy;
.end annotation

.annotation runtime Ljava/lang/annotation/Target;
    value = {
        .enum Ljava/lang/annotation/ElementType;->FIELD:Ljava/lang/annotation/ElementType;,
        .enum Ljava/lang/annotation/ElementType;->PARAMETER:Ljava/lang/annotation/ElementType;,
        .enum Ljava/lang/annotation/ElementType;->METHOD:Ljava/lang/annotation/ElementType;
    }
.end annotation

# virtual methods
.method public abstract tag()Ljava/lang/String;
.end method

.method public abstract value()I
.end method


text:
/* Javascript */
$(function () {
	var date = new Date();
	var d = date.getDate();
	var m = date.getMonth();
	var y = date.getFullYear();

	$('#calendar').fullCalendar({
		header: {
			left: 'prev,next today',
			center: 'title',
			right: 'month,agendaWeek,agendaDay'
		},
		editable: true
	});
});


text:
@implementation _DDFunctionContainer
@synthesize function;
@synthesize aliases;

+ (NSString *)normalizedAlias:(NSString *)alias {
    return [alias lowercaseString];
}

- (id)initWithFunction:(DDMathFunction)f name:(NSString *)name {
    self = [super init];
    if (self) {
        [self setFunction:f];
        aliases = [[NSMutableSet alloc] init];
        [self addAlias:name];
    }
    return self;
}

#if !DD_HAS_ARC
- (void)dealloc {
    [function release];
    [aliases release];
    [super dealloc];
}
#endif

- (NSMutableSet *)_aliases {
    return (NSMutableSet *)aliases;
}

- (NSString *)_normalizedAlias:(NSString *)alias {
    return [alias lowercaseString];
}

- (void)addAlias:(NSString *)alias {
    [[self _aliases] addObject:[_DDFunctionContainer normalizedAlias:alias]];
}

- (void)removeAlias:(NSString *)alias {
    [[self _aliases] removeObject:[_DDFunctionContainer normalizedAlias:alias]];
}

- (BOOL)containsAlias:(NSString *)alias {
    return [aliases containsObject:[_DDFunctionContainer normalizedAlias:alias]];
}

@end


text:
/**
 * (Internal) Uri parsing code from JBoss RESTEasy.
 *
 * The files in this package have been copied from the JBoss RESTEasy project in order to avoid
 * dragging in the complete RESTEasy framework and because recent versions available on Maven
 * Central.
 */
package de.tudarmstadt.ukp.dkpro.lab.resteasy;


text:
#include <stdio.h>
#include <assert.h>

/**
* 封装assert宏,提供运行时级别的友好的错误信息
*/

#define ASSERT_STRING(_Expression, ...) \
	(void)((!!(_Expression)) || (printf(__VA_ARGS__), printf("\n"), 0) || (assert(_Expression), 0))

#include "DllLoader.h"

#ifndef WIN32
#include <dlfcn.h>
#endif

namespace /* 匿名命名空间保护本文件内部函数 */ {

	HMODULE Load(const char* path) {
#ifdef WIN32
		return ::LoadLibraryA(path);
#else
		return dlopen(path, RTLD_LAZY);
#endif
	}

	void Free(HMODULE hModule) {
#ifdef WIN32
		::FreeLibrary(hModule);
#else
		dlclose(hModule);
#endif
	}

	void* GetProc(HMODULE hModule, const char* procName) {
		void* addr =
#ifdef WIN32
			::GetProcAddress(hModule, procName);
#else
			dlsym(hModule, procName);
#endif
		return addr;
	}

}

DllLoader::DllLoader() :
	m_hModule(nullptr) {
}

DllLoader::~DllLoader(void) {
	Free();
}

bool DllLoader::Load(const char* path) {
	if (m_hModule == nullptr) {
		m_hModule = ::Load(path);
	} else {
		ASSERT_STRING(false, "already load, please use Free() before.");
	}
	return (m_hModule != nullptr);
}

void DllLoader::Free() {
	if (m_hModule != nullptr) {
		::Free(m_hModule);
		m_hModule = nullptr;
	}
}

void* DllLoader::GetProcAddress(const char* name) {
	if (m_hModule == nullptr) {
		return nullptr;
	}
	return ::GetProc(m_hModule, name);
}


text:
#include "time.h"

using namespace Scheduler;

double Time::time = 0.0;

double Time::getTime()
{
	return time;
}

void Time::updateTime(double t)
{
	time = t;
}


text:
require 'rails_helper'

describe MessageTrain::UnsubscribesController do
  include_context 'loaded site'
  include ControllerMacros
  routes { MessageTrain::Engine.routes }

  let(:valid_attributes) do
    { from_type: 'Group', from_id: membered_group.id }
  end

  let(:invalid_attributes) do
    { from_type: 'Group', from_id: empty_group.id }
  end

  before do
    login_user first_user
  end

  describe 'GET #index' do
    before do
      get :index
    end
    it_should_behave_like 'a successful page', which_renders: 'index'

    context 'loads subscriptions into @subscriptions' do
      subject { assigns(:subscriptions) }
      it { should be_an Array }
      it { should have_at_least(3).items }
    end
  end

  describe 'POST #create' do
    describe 'with invalid attributes' do
      before do
        post :create, params: { unsubscribe: invalid_attributes }
      end
      it_should_behave_like 'a 404 Not Found error'
    end
    describe 'with valid attributes' do
      before do
        post :create, params: { unsubscribe: valid_attributes }
      end
      it_should_behave_like(
        'a redirect with a message',
        '/unsubscribes',
        notice: 'You are now unsubscribed from Membered Group, which means '\
          'that you will not be notified by email of any messages received by '\
          'that Group.'
      )
      it_should_behave_like 'a response without error'
    end
    describe 'with :all set to true' do
      before do
        post :create, params: { all: true }
      end
      it_should_behave_like(
        'a redirect with a message',
        '/unsubscribes',
        notice: 'You have unsubscribed from all messages, which means that '\
          'you will not be notified by email of any messages received in any '\
          'of your boxes.'
      )
      it_should_behave_like 'a response without error'
    end
  end

  describe 'DELETE #destroy' do
    describe 'with an id' do
      before do
        delete(
          :destroy,
          params: {
            id: first_user.unsubscribes.where(
              from_type: 'Group',
              from_id: unsubscribed_group.id
            ).first.id
          }
        )
      end
      it_should_behave_like(
        'a redirect with a message',
        '/unsubscribes',
        notice: 'You are no longer unsubscribed from Unsubscribed Group, '\
          'which means that you will now be notified by email of any '\
          'messages received in that Group.'
      )
    end
    describe 'with :all set to true' do
      before do
        delete :destroy, params: { all: true }
      end
      it_should_behave_like(
        'a redirect with a message',
        '/unsubscribes',
        notice: 'You are no longer unsubscribed from all messages, which '\
          'means that you will now be notified by email of any messages '\
          'received in boxes you are subscribed to.'
      )
    end
  end
end


text:
// This file was automatically generated by the code gen tool - do not modify.

using System ;
using scg = System.Collections.Generic ;
using sd = System.Data ;
using sds = System.Data.SqlClient ;
using sr = System.Reflection ;
using mst = Microsoft.SqlServer.Types ;
using mss = Microsoft.SqlServer.Server ;
using acr = alby.codegen.runtime ;

using nu = NUnit.Framework;
using t = alby.pantheon.codegen.table ;

namespace alby.pantheon.codegen.test
{
	public partial class CodeGenUnitTestClass : acr.CodeGenUnitTestBase
	{
		protected void PopulateOverride٠ExpenseDetail( bool insert, t.ExpenseDetail obj )
		{
			if ( insert )
			{
				// obj.ExpenseDetailID = null ;
				// obj.ExpenseTotal = null ;
				// obj.ExpensePaymentCommenceDate = null ;
				// obj.ExpensePaymentCommenceDateText = null ;
				// obj.OperatingPercent = null ;
				// obj.OperatingExpense = null ;
				// obj.OperatingSQM = null ;
				// obj.StatutoryPercent = null ;
				// obj.StatutoryExpense = null ;
				// obj.StatutorySQM = null ;
				// obj.ACGeneralEnergyPercent = null ;
				// obj.ACGeneralEnergyExpense = null ;
				// obj.ACGeneralEnergySQM = null ;
				// obj.ACMaintenanceRepairPercent = null ;
				// obj.ACMaintenanceRepairExpense = null ;
				// obj.ACMaintenanceRepairSQM = null ;
				// obj.UpdateUserCode = null ;
				// obj.UpdateDateTime = null ;
			}
			else // update
			{
				// obj.ExpenseDetailID = null ;
				// obj.ExpenseTotal = null ;
				// obj.ExpensePaymentCommenceDate = null ;
				// obj.ExpensePaymentCommenceDateText = null ;
				// obj.OperatingPercent = null ;
				// obj.OperatingExpense = null ;
				// obj.OperatingSQM = null ;
				// obj.StatutoryPercent = null ;
				// obj.StatutoryExpense = null ;
				// obj.StatutorySQM = null ;
				// obj.ACGeneralEnergyPercent = null ;
				// obj.ACGeneralEnergyExpense = null ;
				// obj.ACGeneralEnergySQM = null ;
				// obj.ACMaintenanceRepairPercent = null ;
				// obj.ACMaintenanceRepairExpense = null ;
				// obj.ACMaintenanceRepairSQM = null ;
				// obj.UpdateUserCode = null ;
				// obj.UpdateDateTime = null ;
			}

		}
	}

}


text:
<?php declare(strict_types = 1);

namespace Smalldb\StateMachine\AccessControlExtension\Predicate;

use Psr\Log\LoggerInterface;
use Smalldb\StateMachine\ReferenceInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;

class IsGrantedCompiled implements PredicateCompiled
{
	private string $attribute;
	private AuthorizationCheckerInterface $authorizationChecker;

	public function __construct(string $attribute, AuthorizationCheckerInterface $authorizationChecker)
	{
		$this->attribute = $attribute;
		$this->authorizationChecker = $authorizationChecker;
	}

	/**
	 * @see Twig's is_granted from \Symfony\Bridge\Twig\Extension\SecurityExtension.
	 */
	public function evaluate(ReferenceInterface $ref): bool
	{
		try {
			return $this->authorizationChecker->isGranted($this->attribute, $ref);
		}
		catch (AuthenticationCredentialsNotFoundException $ex) {
			return false;
		}
	}

}