text:
package com.theoryinpractice.testng.configuration;

import com.intellij.application.options.ModuleDescriptionsComboBox;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.JavaExecutionUtil;
import com.intellij.execution.MethodBrowser;
import com.intellij.execution.ShortenCommandLine;
import com.intellij.execution.configuration.BrowseModuleValueActionListener;
import com.intellij.execution.testDiscovery.TestDiscoveryExtension;
import com.intellij.execution.testframework.TestSearchScope;
import com.intellij.execution.ui.*;
import com.intellij.ide.util.TreeClassChooser;
import com.intellij.ide.util.TreeClassChooserFactory;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.fileTypes.PlainTextLanguage;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComponentWithBrowseButton;
import com.intellij.openapi.ui.LabeledComponent;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.ui.*;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBList;
import com.intellij.ui.components.fields.ExpandableTextField;
import com.intellij.ui.table.TableView;
import com.intellij.util.IconUtil;
import com.intellij.util.containers.ContainerUtil;
import com.theoryinpractice.testng.MessageInfoException;
import com.theoryinpractice.testng.configuration.browser.GroupBrowser;
import com.theoryinpractice.testng.configuration.browser.PackageBrowser;
import com.theoryinpractice.testng.configuration.browser.SuiteBrowser;
import com.theoryinpractice.testng.configuration.browser.TestClassBrowser;
import com.theoryinpractice.testng.model.*;
import com.theoryinpractice.testng.util.TestNGUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Map;

public class TestNGConfigurationEditor<T extends TestNGConfiguration> extends SettingsEditor<T> implements PanelWithAnchor {
  //private static final Logger LOGGER = Logger.getInstance("TestNG Runner");
  private final Project project;

  private JPanel panel;

  private LabeledComponent<EditorTextFieldWithBrowseButton> classField;
  private LabeledComponent<ModuleDescriptionsComboBox> moduleClasspath;
  private JrePathEditor alternateJDK;
  private final ConfigurationModuleSelector moduleSelector;
  private JComboBox<TestType> myTestKind;
  private JBLabel myTestLabel;
  private final TestNGConfigurationModel model;
  private LabeledComponent<EditorTextFieldWithBrowseButton> methodField;
  private LabeledComponent<EditorTextFieldWithBrowseButton> packageField;
  private LabeledComponent<TextFieldWithBrowseButton.NoPathCompletion> groupField;
  private LabeledComponent<TextFieldWithBrowseButton> suiteField;
  private JComponent anchor;
  private JRadioButton packagesInProject;
  private JRadioButton packagesInModule;
  private JRadioButton packagesAcrossModules;
  private JPanel packagePanel;
  private TestNGParametersTableModel propertiesTableModel;
  private LabeledComponent<TextFieldWithBrowseButton> propertiesFile;
  private LabeledComponent<TextFieldWithBrowseButton> outputDirectory;
  private TableView propertiesTableView;
  private JPanel commonParametersPanel;//temp compilation problems
  private JList myListenersList;
  private JCheckBox myUseDefaultReportersCheckBox;
  private LabeledComponent<JPanel> myPattern;
  private JPanel myPropertiesPanel;
  private JPanel myListenersPanel;
  private LabeledComponent<ShortenCommandLineModeCombo> myShortenCommandLineCombo;
  TextFieldWithBrowseButton myPatternTextField;
  private final CommonJavaParametersPanel commonJavaParameters = new CommonJavaParametersPanel();
  private final ArrayList<Map.Entry<String, String>> propertiesList = new ArrayList<>();
  private TestNGListenersTableModel listenerModel;

  private TestNGConfiguration config;

  public TestNGConfigurationEditor(Project project) {
    this.project = project;
    BrowseModuleValueActionListener[] browseListeners = new BrowseModuleValueActionListener[]{new PackageBrowser(project),
      new TestClassBrowser(project, this), new TestNGMethodBrowser(project), new GroupBrowser(project, this), new SuiteBrowser(project),
      new TestClassBrowser(project, this) {
        @Override
        protected void onClassChoosen(PsiClass psiClass) {
          final JTextField textField = myPatternTextField.getTextField();
          final String text = textField.getText();
          textField.setText(text + (text.length() > 0 ? "||" : "") + psiClass.getQualifiedName());
        }

        @Override
        public void actionPerformed(ActionEvent e) {
          showDialog();
        }
      }};
    model = new TestNGConfigurationModel(project);
    model.setListener(this);
    createView();
    moduleSelector = new ConfigurationModuleSelector(project, getModulesComponent());
    alternateJDK.setDefaultJreSelector(DefaultJreSelector.fromModuleDependencies(getModulesComponent(), false));
    commonJavaParameters.setModuleContext(moduleSelector.getModule());
    moduleClasspath.getComponent().addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        commonJavaParameters.setModuleContext(moduleSelector.getModule());
      }
    });
    commonJavaParameters.setHasModuleMacro();

    final JPanel panel = myPattern.getComponent();
    panel.setLayout(new BorderLayout());
    myPatternTextField = new TextFieldWithBrowseButton(new ExpandableTextField());
    myPatternTextField.setButtonIcon(IconUtil.getAddIcon());
    panel.add(myPatternTextField, BorderLayout.CENTER);

    final CollectionComboBoxModel<TestType> testKindModel = new CollectionComboBoxModel<>();
    for (TestType type : TestType.values()) {
      if (type != TestType.SOURCE || Registry.is(TestDiscoveryExtension.TEST_DISCOVERY_REGISTRY_KEY)) {
        testKindModel.add(type);
      }
    }
    myTestKind.setModel(testKindModel);
    myTestKind.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        TestNGConfigurationEditor.this.model.setType((TestType)myTestKind.getSelectedItem());
      }
    });
    myTestKind.setRenderer(new ListCellRendererWrapper<TestType>() {
                             @Override
                             public void customize(JList list, TestType value, int index, boolean selected, boolean hasFocus) {
                               if (value != null) {
                                 setText(value.getPresentableName());
                               }
                             }
                           });
    registerListener(new JRadioButton[]{packagesInProject, packagesInModule, packagesAcrossModules}, null);
    packagesInProject.addChangeListener(new ChangeListener() {
      @Override
      public void stateChanged(ChangeEvent e) {
        evaluateModuleClassPath();
      }
    });

    LabeledComponent[] components = new LabeledComponent[]{packageField, classField, methodField, groupField, suiteField, myPattern};
    for (int i = 0; i < components.length; i++) {
      JComponent field = components[i].getComponent();
      Object document = model.getDocument(i);
      if (field instanceof TextFieldWithBrowseButton) {
        ((TextFieldWithBrowseButton)field).getTextField().setDocument((PlainDocument)document);
      }
      else if (field instanceof EditorTextFieldWithBrowseButton) {
        document = ((EditorTextFieldWithBrowseButton)field).getChildComponent().getDocument();
      }
      else {
        field = myPatternTextField;
        document = new PlainDocument();
        ((TextFieldWithBrowseButton)field).getTextField().setDocument((Document)document);
      }

      browseListeners[i].setField((ComponentWithBrowseButton)field);
      if (browseListeners[i] instanceof MethodBrowser) {
        final EditorTextField childComponent = (EditorTextField)((ComponentWithBrowseButton)field).getChildComponent();
        ((MethodBrowser)browseListeners[i]).installCompletion(childComponent);
        document = childComponent.getDocument();
      }
      model.setDocument(i, document);
    }
    model.setType(TestType.CLASS);
    propertiesFile.getComponent().getTextField().setDocument(model.getPropertiesFileDocument());
    outputDirectory.getComponent().getTextField().setDocument(model.getOutputDirectoryDocument());

    commonJavaParameters.setProgramParametersLabel(ExecutionBundle.message("junit.configuration.test.runner.parameters.label"));

    myShortenCommandLineCombo.setComponent(new ShortenCommandLineModeCombo(project, alternateJDK, getModulesComponent()));
    setAnchor(outputDirectory.getLabel());
    alternateJDK.setAnchor(moduleClasspath.getLabel());
    commonJavaParameters.setAnchor(moduleClasspath.getLabel());
    myShortenCommandLineCombo.setAnchor(moduleClasspath.getLabel());
  }

  private void evaluateModuleClassPath() {
    final boolean allPackagesInProject = packagesInProject.isSelected() && packagePanel.isVisible();
    moduleClasspath.setEnabled(!allPackagesInProject);
    if (allPackagesInProject) {
      moduleClasspath.getComponent().setSelectedItem(null);
    }
  }

  private void redisplay() {
    final TestType testKind = (TestType)myTestKind.getSelectedItem();
    if (testKind == TestType.PACKAGE) {
      packagePanel.setVisible(true);
      packageField.setVisible(true);
      classField.setVisible(false);
      methodField.setVisible(false);
      groupField.setVisible(false);
      suiteField.setVisible(false);
      myPattern.setVisible(false);
    }
    else if (testKind == TestType.CLASS) {
      packagePanel.setVisible(false);
      classField.setVisible(true);
      methodField.setVisible(false);
      groupField.setVisible(false);
      suiteField.setVisible(false);
      myPattern.setVisible(false);
    }
    else if (testKind == TestType.METHOD || testKind == TestType.SOURCE) {
      packagePanel.setVisible(false);
      classField.setVisible(true);
      methodField.setVisible(true);
      groupField.setVisible(false);
      suiteField.setVisible(false);
      myPattern.setVisible(false);
    }
    else if (testKind == TestType.GROUP) {
      packagePanel.setVisible(true);
      classField.setVisible(false);
      methodField.setVisible(false);
      groupField.setVisible(true);
      suiteField.setVisible(false);
      myPattern.setVisible(false);
    }
    else if (testKind == TestType.SUITE) {
      packagePanel.setVisible(true);
      classField.setVisible(false);
      methodField.setVisible(false);
      groupField.setVisible(false);
      suiteField.setVisible(true);
      myPattern.setVisible(false);
    }
    else if (testKind == TestType.PATTERN) {
      packagePanel.setVisible(true);
      classField.setVisible(false);
      methodField.setVisible(false);
      groupField.setVisible(false);
      suiteField.setVisible(false);
      myPattern.setVisible(true);
    }
  }

  public String getClassName() {
    return classField.getComponent().getText();
  }

  public ModuleDescriptionsComboBox getModulesComponent() {
    return moduleClasspath.getComponent();
  }

  @Override
  protected void resetEditorFrom(@NotNull TestNGConfiguration config) {
    this.config = config;
    model.reset(config);
    commonJavaParameters.reset(config);
    getModuleSelector().reset(config);
    TestData data = config.getPersistantData();
    TestSearchScope scope = data.getScope();
    if (scope == TestSearchScope.SINGLE_MODULE) {
      packagesInModule.setSelected(true);
    }
    else if (scope == TestSearchScope.MODULE_WITH_DEPENDENCIES) {
      packagesAcrossModules.setSelected(true);
    }
    else {
      packagesInProject.setSelected(true);
    }
    evaluateModuleClassPath();
    alternateJDK.setPathOrName(config.ALTERNATIVE_JRE_PATH, config.ALTERNATIVE_JRE_PATH_ENABLED);
    propertiesList.clear();
    propertiesList.addAll(data.TEST_PROPERTIES.entrySet());
    propertiesTableModel.setParameterList(propertiesList);

    listenerModel.setListenerList(data.TEST_LISTENERS);
    myUseDefaultReportersCheckBox.setSelected(data.USE_DEFAULT_REPORTERS);
    myShortenCommandLineCombo.getComponent().setSelectedItem(config.getShortenCommandLine());
  }

  @Override
  public void applyEditorTo(@NotNull TestNGConfiguration config) {
    model.apply(getModuleSelector().getModule(), config);
    getModuleSelector().applyTo(config);
    TestData data = config.getPersistantData();
    final TestType testKind = (TestType)myTestKind.getSelectedItem();
    if (testKind != TestType.CLASS && testKind != TestType.METHOD && testKind != TestType.SOURCE) {
      if (packagesInProject.isSelected()) {
        data.setScope(TestSearchScope.WHOLE_PROJECT);
      }
      else if (packagesInModule.isSelected()) {
        data.setScope(TestSearchScope.SINGLE_MODULE);
      }
      else if (packagesAcrossModules.isSelected()) data.setScope(TestSearchScope.MODULE_WITH_DEPENDENCIES);
    }
    else {
      data.setScope(TestSearchScope.MODULE_WITH_DEPENDENCIES);
    }
    commonJavaParameters.applyTo(config);
    config.ALTERNATIVE_JRE_PATH = alternateJDK.getJrePathOrName();
    config.ALTERNATIVE_JRE_PATH_ENABLED = alternateJDK.isAlternativeJreSelected();

    data.TEST_PROPERTIES.clear();
    for (Map.Entry<String, String> entry : propertiesList) {
      data.TEST_PROPERTIES.put(entry.getKey(), entry.getValue());
    }

    data.TEST_LISTENERS.clear();
    data.TEST_LISTENERS.addAll(listenerModel.getListenerList());

    data.USE_DEFAULT_REPORTERS = myUseDefaultReportersCheckBox.isSelected();
    config.setShortenCommandLine((ShortenCommandLine)myShortenCommandLineCombo.getComponent().getSelectedItem());
  }

  public ConfigurationModuleSelector getModuleSelector() {
    return moduleSelector;
  }

  @NotNull
  @Override
  protected JComponent createEditor() {
    return panel;
  }

  @Override
  public JComponent getAnchor() {
    return anchor;
  }

  @Override
  public void setAnchor(JComponent anchor) {
    this.anchor = anchor;
    methodField.setAnchor(anchor);
    packageField.setAnchor(anchor);
    groupField.setAnchor(anchor);
    suiteField.setAnchor(anchor);
    outputDirectory.setAnchor(anchor);
    classField.setAnchor(anchor);
    myPattern.setAnchor(anchor);
    myTestLabel.setAnchor(anchor);
  }

  private void createUIComponents() {
    myShortenCommandLineCombo = new LabeledComponent<>();
  }

  private static void registerListener(JRadioButton[] buttons, ChangeListener changelistener) {
    ButtonGroup buttongroup = new ButtonGroup();
    for (JRadioButton button : buttons) {
      button.getModel().addChangeListener(changelistener);
      buttongroup.add(button);
    }

    if (buttongroup.getSelection() == null) buttongroup.setSelected(buttons[0].getModel(), true);
  }

  private void createView() {
    commonParametersPanel.add(commonJavaParameters, BorderLayout.CENTER);
    classField.setComponent(new EditorTextFieldWithBrowseButton(project, true, new JavaCodeFragment.VisibilityChecker() {
      @Override
      public Visibility isDeclarationVisible(PsiElement declaration, PsiElement place) {
        if (declaration instanceof PsiClass && place.getParent() instanceof PsiJavaCodeReferenceElement) {
          return Visibility.VISIBLE;
        }
        try {
          if (declaration instanceof PsiClass &&
              new TestClassBrowser(project, TestNGConfigurationEditor.this).getFilter().isAccepted((PsiClass)declaration)) {
            return Visibility.VISIBLE;
          }
        }
        catch (MessageInfoException e) {
          return Visibility.NOT_VISIBLE;
        }
        return Visibility.NOT_VISIBLE;
      }
    }));

    final EditorTextFieldWithBrowseButton methodEditorTextField = new EditorTextFieldWithBrowseButton(project, true,
                                                                                JavaCodeFragment.VisibilityChecker.EVERYTHING_VISIBLE,
                                                                                PlainTextLanguage.INSTANCE.getAssociatedFileType());
    methodField.setComponent(methodEditorTextField);

    groupField.setComponent(new TextFieldWithBrowseButton.NoPathCompletion());
    suiteField.setComponent(new TextFieldWithBrowseButton());
    packageField.setVisible(true);
    packageField.setEnabled(true);
    packageField.setComponent(new EditorTextFieldWithBrowseButton(project, false));

    TextFieldWithBrowseButton outputDirectoryButton = new TextFieldWithBrowseButton();
    outputDirectory.setComponent(outputDirectoryButton);
    outputDirectoryButton.addBrowseFolderListener("TestNG", "Select test output directory", project,
                                                  FileChooserDescriptorFactory.createSingleFolderDescriptor());
    moduleClasspath.setEnabled(true);

    propertiesTableModel = new TestNGParametersTableModel();
    listenerModel = new TestNGListenersTableModel();

    TextFieldWithBrowseButton textFieldWithBrowseButton = new TextFieldWithBrowseButton();
    propertiesFile.setComponent(textFieldWithBrowseButton);

    FileChooserDescriptor propertiesFileDescriptor = new FileChooserDescriptor(true, false, false, false, false, false) {
      @Override
      public boolean isFileVisible(VirtualFile virtualFile, boolean showHidden) {
        if (!showHidden && virtualFile.getName().charAt(0) == '.') return false;
        return virtualFile.isDirectory() || "properties".equals(virtualFile.getExtension());
      }
    };

    textFieldWithBrowseButton
      .addBrowseFolderListener("TestNG", "Select .properties file for test properties", project, propertiesFileDescriptor);

    propertiesTableView = new TableView(propertiesTableModel);

    myPropertiesPanel.add(
      ToolbarDecorator.createDecorator(propertiesTableView)
        .setAddAction(new AnActionButtonRunnable() {
          @Override
          public void run(AnActionButton button) {
            propertiesTableModel.addParameter();
            int index = propertiesTableModel.getRowCount() - 1;
            propertiesTableView.setRowSelectionInterval(index, index);
          }
        }).setRemoveAction(new AnActionButtonRunnable() {
        @Override
        public void run(AnActionButton button) {
          int idx = propertiesTableView.getSelectedRow() - 1;
          for (int row : propertiesTableView.getSelectedRows()) {
            propertiesTableModel.removeProperty(row);
          }
          if (idx > -1) propertiesTableView.setRowSelectionInterval(idx, idx);
        }
      }).disableUpDownActions().createPanel(), BorderLayout.CENTER);

    myListenersList = new JBList(listenerModel);
    myListenersPanel.add(
      ToolbarDecorator.createDecorator(myListenersList).setAddAction(new AddActionButtonRunnable())
        .setRemoveAction(new AnActionButtonRunnable() {
          @Override
          public void run(AnActionButton button) {
            int idx = myListenersList.getSelectedIndex() - 1;
            for (int row : myListenersList.getSelectedIndices()) {
              listenerModel.removeListener(row);
            }
            if (idx > -1) myListenersList.setSelectedIndex(idx);
          }
        }).setAddActionUpdater(new AnActionButtonUpdater() {
        @Override
        public boolean isEnabled(@NotNull AnActionEvent e) {
          return !project.isDefault();
        }
      }).disableUpDownActions().createPanel(), BorderLayout.CENTER);
  }

  public void onTypeChanged(TestType type) {
    //LOGGER.info("onTypeChanged with " + type);
    myTestKind.setSelectedItem(type);
    if (type == TestType.PACKAGE) {
      packageField.setEnabled(true);
      classField.setEnabled(false);
      methodField.setEnabled(false);
      groupField.setEnabled(false);
      suiteField.setEnabled(false);
      myPattern.setEnabled(false);
    }
    else if (type == TestType.CLASS) {
      packageField.setEnabled(false);
      classField.setEnabled(true);
      methodField.setEnabled(false);
      groupField.setEnabled(false);
      suiteField.setEnabled(false);
      myPattern.setEnabled(false);
    }
    else if (type == TestType.METHOD || type == TestType.SOURCE) {
      packageField.setEnabled(false);
      classField.setEnabled(true);
      methodField.setEnabled(true);
      groupField.setEnabled(false);
      suiteField.setEnabled(false);
      myPattern.setEnabled(false);
    }
    else if (type == TestType.GROUP) {
      groupField.setEnabled(true);
      packageField.setVisible(false);
      classField.setEnabled(false);
      methodField.setEnabled(false);
      suiteField.setEnabled(false);
      myPattern.setEnabled(false);
    }
    else if (type == TestType.SUITE) {
      suiteField.setEnabled(true);
      packageField.setVisible(false);
      classField.setEnabled(false);
      methodField.setEnabled(false);
      groupField.setEnabled(false);
      myPattern.setEnabled(false);
    }
    else if (type == TestType.PATTERN) {
      myPattern.setEnabled(true);
      suiteField.setEnabled(false);
      packageField.setVisible(false);
      classField.setEnabled(false);
      methodField.setEnabled(false);
      groupField.setEnabled(false);
    }
    redisplay();
    evaluateModuleClassPath();
  }

  private class AddActionButtonRunnable implements AnActionButtonRunnable {
    private final Logger LOGGER = Logger.getInstance("TestNG Runner");

    @Nullable
    protected GlobalSearchScope getSearchScope(Module[] modules) {
      if (modules == null || modules.length == 0) return null;
      GlobalSearchScope[] scopes =
        ContainerUtil.map2Array(modules, GlobalSearchScope.class, module -> GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module));
      return GlobalSearchScope.union(scopes);
    }

    @Nullable
    protected String selectListenerClass() {
      GlobalSearchScope searchScope = getSearchScope(config.getModules());
      if (searchScope == null) {
        searchScope = GlobalSearchScope.allScope(project);
      }
      final TestListenerFilter filter = new TestListenerFilter(searchScope, project);

      TreeClassChooser chooser = TreeClassChooserFactory.getInstance(project)
        .createWithInnerClassesScopeChooser("Choose Listener Class", filter.getScope(), filter, null);
      chooser.showDialog();
      PsiClass psiclass = chooser.getSelected();
      if (psiclass == null) {
        return null;
      }
      else {
        return JavaExecutionUtil.getRuntimeQualifiedName(psiclass);
      }
    }

    @Override
    public void run(AnActionButton button) {
      final String className = selectListenerClass();
      if (className != null) {
        listenerModel.addListener(className);
        LOGGER.info("Adding listener " + className + " to configuration.");
      }
    }
  }

  private class TestNGMethodBrowser extends MethodBrowser {
    TestNGMethodBrowser(Project project) {
      super(project);
    }

    @Override
    protected Condition<PsiMethod> getFilter(PsiClass testClass) {
      return method -> TestNGUtil.hasTest(method);
    }

    @Override
    protected String getClassName() {
      return TestNGConfigurationEditor.this.getClassName();
    }

    @Override
    protected ConfigurationModuleSelector getModuleSelector() {
      return moduleSelector;
    }
  }
}


text:
package com.ok.lab.magiclantern.adapters;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.ok.lab.magiclantern.R;
import com.ok.lab.magiclantern.data.MovieData;
import com.squareup.picasso.Picasso;

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

/**
 * Created by olgakuklina on 2015-08-25.
 */
public class ImageAdapter extends BaseAdapter {

    private static final String TAG = ImageAdapter.class.getSimpleName();
    private static final int IMAGE_WIDTH = 185;
    private static final int IMAGE_HEIGHT = 278;
    private final ArrayList<MovieData> finalMoviePosters = new ArrayList<>();
    private final HashSet<Integer> movieIdSet = new HashSet<>();
    private final float density;

    private final Context mContext;

    public ImageAdapter(Context c) {
        mContext = c;
        density = mContext.getResources().getDisplayMetrics().density;
    }

    public int getCount() {
        return finalMoviePosters.size();
    }

    public Object getItem(int position) {
        return finalMoviePosters.get(position);
    }

    public long getItemId(int position) {
        return finalMoviePosters.get(position).getMovieId();
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        View view;
        ImageView imageView;
        TextView textView;
        if (convertView == null) {
            view = ((LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.image_layout, parent, false);

        } else {
            view = convertView;
        }
        MovieData data = finalMoviePosters.get(position);
        imageView = (ImageView) view.findViewById(R.id.movie_poster_view);
        view.setLayoutParams(new GridView.LayoutParams((int) (IMAGE_WIDTH * density), (int) (IMAGE_HEIGHT * density)));
        //imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        if (data.getMoviePoster() == null) {
            textView = (TextView) view.findViewById(R.id.movie_title);
            textView.setText(data.getTitle());
        }

        Picasso pic = Picasso.with(mContext);
        pic.load(data.getMoviePoster())
                .into(imageView);
        return view;
    }

    public void add(MovieData res) {
        if (movieIdSet.contains(res.getMovieId())) {
            Log.w(TAG, "Movie duplicate found, movieID = " + res.getMovieId());
            return;
        }

        finalMoviePosters.add(res);
        movieIdSet.add(res.getMovieId());
    }

    public void addAll(List<MovieData> res) {
        finalMoviePosters.addAll(res);
    }

    public void clearData() {
        finalMoviePosters.clear();
        movieIdSet.clear();
        notifyDataSetChanged();
    }

    public List<MovieData> getMovieData() {
        return finalMoviePosters;
    }
}

redpajama_set_name: RedPajamaGithub


text:
import MalmoPython
import time

# set up out malmo client
malmo = MalmoPython.AgentHost()
spec = open("classroom_basic.xml").read()
spec = spec.replace("__WIDTH__", "640")
spec = spec.replace("__HEIGHT__", "480")
spec = spec.replace("__EPISODE_TIME_MS__", "10000000")
mission = MalmoPython.MissionSpec(spec, True)
mission_record = MalmoPython.MissionRecordSpec()

malmo.startMission(mission, mission_record)

while True:
  world_state = malmo.getWorldState()
  if len(world_state.rewards) > 0:
    print "len?", len(world_state.rewards)
    print world_state.rewards[0].getValue()
  time.sleep(1)


text:
/**
 * @author Dan Nuffer
 */

#include "OW_config.h"
#include "OW_IndicationRepLayerImpl.hpp"
#include "OW_Format.hpp"
#include "OW_CIMProperty.hpp"
#include "OW_CIMParameter.hpp"
#include "OW_CIMException.hpp"
#include "OW_CIMNameSpace.hpp"
#include "OW_CIMMethod.hpp"
#include "OW_CIMParamValue.hpp"
#include "OW_CIMClass.hpp"
#include "OW_CIMInstance.hpp"
#include "OW_CIMObjectPath.hpp"
#include "OW_IndicationRepLayerMediator.hpp"
#include "OW_CIMOMEnvironment.hpp"
#include "OW_CIMValue.hpp"
#include "OW_CIMQualifierType.hpp"
#include "OW_Logger.hpp"
#include "OW_ServiceIFCNames.hpp"
#include "OW_CIMDateTime.hpp"

namespace OW_NAMESPACE
{

namespace
{
	const String COMPONENT_NAME("ow.owcimomd.indication.LifecycleCreator");
}

using namespace WBEMFlags;
//////////////////////////////////////////////////////////////////////////////
IndicationRepLayer::~IndicationRepLayer()
{
}
//////////////////////////////////////////////////////////////////////////////
IndicationRepLayerImpl::~IndicationRepLayerImpl()
{
}
//////////////////////////////////////////////////////////////////////////////
String
IndicationRepLayerImpl::getName() const
{
	return ServiceIFCNames::IndicationRepLayer;
}
//////////////////////////////////////////////////////////////////////////////
CIMInstance
IndicationRepLayerImpl::getInstance(
	const String& ns,
	const CIMObjectPath& instanceName,
	ELocalOnlyFlag localOnly, EIncludeQualifiersFlag includeQualifiers, EIncludeClassOriginFlag includeClassOrigin,
	const StringArray* propertyList, OperationContext& context)
{
	CIMInstance theInst = m_pServer->getInstance(ns, instanceName, localOnly,
		includeQualifiers, includeClassOrigin, propertyList, context);

	if (m_pEnv->getIndicationRepLayerMediator()->getInstReadSubscriptionCount() > 0)
	{
		try
		{
			CIMInstance expInst("CIM_InstRead");
			expInst.setProperty("SourceInstance", CIMValue(theInst));
			expInst.setProperty("IndicationTime", CIMValue(CIMDateTime(DateTime::getCurrent())));
			exportIndication(expInst, ns);
		}
		catch (CIMException&)
		{
			OW_LOG_DEBUG(m_pEnv->getLogger(COMPONENT_NAME), "Unable to export indication for getInstance"
				" because CIM_InstRead does not exist");
		}
	}
	return theInst;
}
//////////////////////////////////////////////////////////////////////////////
CIMValue
IndicationRepLayerImpl::invokeMethod(
	const String& ns,
	const CIMObjectPath& path,
	const String& methodName, const CIMParamValueArray& inParams,
	CIMParamValueArray& outParams, OperationContext& context)
{
	CIMValue rval = m_pServer->invokeMethod(ns, path, methodName, inParams,
		outParams, context);
	if (m_pEnv->getIndicationRepLayerMediator()->getInstMethodCallSubscriptionCount() > 0)
	{
		if (path.isInstancePath()) // process the indication only if instance.
		{
			try
			{
				CIMInstance expInst("CIM_InstMethodCall");
				CIMInstance theInst = m_pServer->getInstance(ns, path, E_NOT_LOCAL_ONLY,
					E_INCLUDE_QUALIFIERS, E_INCLUDE_CLASS_ORIGIN, NULL, context);

				if (!theInst)
				{
					// can't export indication
					return rval;
				}

				CIMInstance ParamsEmbed;
				ParamsEmbed.setClassName("__MethodParameters");

				for (size_t i = 0; i < inParams.size(); i++)
				{
					CIMProperty prop(inParams[i].getName(), inParams[i].getValue());
					ParamsEmbed.setProperty(prop);
				}

				for (size_t i = 0; i < outParams.size(); i++)
				{
					CIMProperty prop(outParams[i].getName(), outParams[i].getValue());
					ParamsEmbed.setProperty(prop);
				}

				expInst.setProperty("SourceInstance", CIMValue(theInst)); // from CIM_InstIndication
				expInst.setProperty("MethodName", CIMValue(methodName));
				expInst.setProperty("MethodParameters", CIMValue(ParamsEmbed));
				expInst.setProperty("PreCall", CIMValue(false));
				expInst.setProperty("ReturnValue", CIMValue(rval.toString()));
				expInst.setProperty("IndicationTime", CIMValue(CIMDateTime(DateTime::getCurrent())));
				exportIndication(expInst, ns);
			}
			catch (CIMException&)
			{
				OW_LOG_DEBUG(m_pEnv->getLogger(COMPONENT_NAME), "Unable to export indication for"
					" invokeMethod because CIM_InstMethodCall does not exist");
			}
		}
	}
	return rval;
}
#ifndef OW_DISABLE_SCHEMA_MANIPULATION
//////////////////////////////////////////////////////////////////////////////
CIMClass
IndicationRepLayerImpl::modifyClass(const String &ns,
	const CIMClass& cc, OperationContext& context)
{
	CIMClass CCOrig = m_pServer->modifyClass(ns, cc, context);

	if (m_pEnv->getIndicationRepLayerMediator()->getClassModificationSubscriptionCount() > 0)
	{

		try
		{
			CIMInstance expInst("CIM_ClassModification");
			expInst.setProperty("PreviousClassDefinition", CIMValue(CCOrig));
			expInst.setProperty("ClassDefinition", CIMValue(cc));
			expInst.setProperty("IndicationTime", CIMValue(CIMDateTime(DateTime::getCurrent())));
			exportIndication(expInst, ns);
		}
		catch (CIMException&)
		{
			OW_LOG_DEBUG(m_pEnv->getLogger(COMPONENT_NAME), "Unable to export indication for modifyClass"
				" because CIM_ClassModification does not exist");
		}
	}
	return CCOrig;
}
//////////////////////////////////////////////////////////////////////////////
void
IndicationRepLayerImpl::createClass(const String& ns,
	const CIMClass& cc, OperationContext& context)
{
	m_pServer->createClass(ns, cc, context);
	if (m_pEnv->getIndicationRepLayerMediator()->getClassCreationSubscriptionCount() > 0)
	{

		try
		{
			CIMInstance expInst("CIM_ClassCreation");
			expInst.setProperty("ClassDefinition", CIMValue(cc));
			expInst.setProperty("IndicationTime", CIMValue(CIMDateTime(DateTime::getCurrent())));
			exportIndication(expInst, ns);
		}
		catch(CIMException&)
		{
			OW_LOG_DEBUG(m_pEnv->getLogger(COMPONENT_NAME), "Unable to export indication for createClass"
				" because CIM_ClassCreation does not exist");
		}
	}
}
//////////////////////////////////////////////////////////////////////////////
CIMClass
IndicationRepLayerImpl::deleteClass(const String& ns, const String& className,
	OperationContext& context)
{
	CIMClass cc = m_pServer->deleteClass(ns, className, context);
	if (m_pEnv->getIndicationRepLayerMediator()->getClassDeletionSubscriptionCount() > 0)
	{
		try
		{
			CIMInstance expInst("CIM_ClassDeletion");
			expInst.setProperty("ClassDefinition", CIMValue(cc));
			expInst.setProperty("IndicationTime", CIMValue(CIMDateTime(DateTime::getCurrent())));
			exportIndication(expInst, ns);
		}
		catch (CIMException&)
		{
			OW_LOG_DEBUG(m_pEnv->getLogger(COMPONENT_NAME), "Unable to export indication for"
				" deleteClass because CIM_ClassDeletion does not exist");
		}
	}

	return cc;
}
#endif // #ifndef OW_DISABLE_SCHEMA_MANIPULATION
#ifndef OW_DISABLE_INSTANCE_MANIPULATION
//////////////////////////////////////////////////////////////////////////////
CIMInstance
IndicationRepLayerImpl::modifyInstance(
	const String& ns,
	const CIMInstance& modifiedInstance,
	EIncludeQualifiersFlag includeQualifiers,
	const StringArray* propertyList,
	OperationContext& context)
{
	CIMInstance ciOrig = m_pServer->modifyInstance(ns, modifiedInstance,
		includeQualifiers, propertyList, context);
	if (m_pEnv->getIndicationRepLayerMediator()->getInstModificationSubscriptionCount() > 0)
	{
		try
		{
			CIMInstance expInst("CIM_InstModification");
			expInst.setProperty("PreviousInstance", CIMValue(ciOrig));
			// Filtering the properties in ss is done per the CIM_Interop
			// schema MOF by the indication server, we don't need to do it here.
			expInst.setProperty("SourceInstance", CIMValue(modifiedInstance));
			expInst.setProperty("IndicationTime", CIMValue(CIMDateTime(DateTime::getCurrent())));
			exportIndication(expInst, ns);
		}
		catch (CIMException&)
		{
			OW_LOG_DEBUG(m_pEnv->getLogger(COMPONENT_NAME), "Unable to export indication for modifyInstance"
				" because CIM_InstModification does not exist");
		}
	}
	return ciOrig;
}
//////////////////////////////////////////////////////////////////////////////
CIMObjectPath
IndicationRepLayerImpl::createInstance(const String& ns,
	const CIMInstance& ci, OperationContext& context)
{
	CIMObjectPath rval = m_pServer->createInstance(ns, ci, context);
	if (m_pEnv->getIndicationRepLayerMediator()->getInstCreationSubscriptionCount() > 0)
	{
		try
		{
			CIMInstance expInst("CIM_InstCreation");
			expInst.setProperty("SourceInstance", CIMValue(ci));
			expInst.setProperty("IndicationTime", CIMValue(CIMDateTime(DateTime::getCurrent())));
			exportIndication(expInst, ns);
		}
		catch(CIMException&)
		{
			OW_LOG_DEBUG(m_pEnv->getLogger(COMPONENT_NAME), "Unable to export indication for createInstance"
				" because CIM_InstCreation does not exist");
		}
	}
	return rval;
}
//////////////////////////////////////////////////////////////////////////////
CIMInstance
IndicationRepLayerImpl::deleteInstance(const String& ns, const CIMObjectPath& path,
	OperationContext& context)
{
	CIMInstance instOrig = m_pServer->deleteInstance(ns, path, context);
	if (m_pEnv->getIndicationRepLayerMediator()->getInstDeletionSubscriptionCount() > 0)
	{
		try
		{
			CIMInstance expInst("CIM_InstDeletion");
			expInst.setProperty("SourceInstance", CIMValue(instOrig));
			expInst.setProperty("IndicationTime", CIMValue(CIMDateTime(DateTime::getCurrent())));
			exportIndication(expInst, ns);
		}
		catch (CIMException&)
		{
			OW_LOG_DEBUG(m_pEnv->getLogger(COMPONENT_NAME), "Unable to export indication for deleteInstance"
				" because CIM_InstDeletion does not exist");
		}
	}
	return instOrig;
}
#endif // #ifndef OW_DISABLE_INSTANCE_MANIPULATION
IndicationRepLayerImpl::IndicationRepLayerImpl() : IndicationRepLayer(), m_pServer(0) {}
void IndicationRepLayerImpl::open(const String&) {}
void IndicationRepLayerImpl::close() {}
void IndicationRepLayerImpl::init(const ServiceEnvironmentIFCRef& env) {}
void IndicationRepLayerImpl::shutdown() {}
ServiceEnvironmentIFCRef IndicationRepLayerImpl::getEnvironment() const
{
	return m_pEnv;
}
void IndicationRepLayerImpl::enumClasses(const String& ns,
	const String& className,
	CIMClassResultHandlerIFC& result,
	EDeepFlag deep, ELocalOnlyFlag localOnly, EIncludeQualifiersFlag includeQualifiers,
	EIncludeClassOriginFlag includeClassOrigin, OperationContext& context)
{
	m_pServer->enumClasses(ns, className, result, deep, localOnly, includeQualifiers,
		includeClassOrigin, context);
}
void IndicationRepLayerImpl::enumClassNames(
	const String& ns,
	const String& className,
	StringResultHandlerIFC& result,
	EDeepFlag deep, OperationContext& context)
{
	m_pServer->enumClassNames(ns, className, result, deep, context);
}
void IndicationRepLayerImpl::enumInstances(
	const String& ns,
	const String& className,
	CIMInstanceResultHandlerIFC& result,
	EDeepFlag deep,
	ELocalOnlyFlag localOnly,
	EIncludeQualifiersFlag includeQualifiers,
	EIncludeClassOriginFlag includeClassOrigin,
	const StringArray* propertyList,
	EEnumSubclassesFlag enumSubclasses,
	OperationContext& context)
{
	m_pServer->enumInstances(ns, className, result, deep, localOnly, includeQualifiers,
		includeClassOrigin, propertyList, enumSubclasses, context);
}
void IndicationRepLayerImpl::enumInstanceNames(
	const String& ns,
	const String& className,
	CIMObjectPathResultHandlerIFC& result,
	EDeepFlag deep, OperationContext& context)
{
	return m_pServer->enumInstanceNames(ns, className, result, deep, context);
}
CIMQualifierType IndicationRepLayerImpl::getQualifierType(
	const String& ns,
	const String& qualifierName, OperationContext& context)
{
	return m_pServer->getQualifierType(ns, qualifierName, context);
}
CIMClass IndicationRepLayerImpl::getClass(
	const String& ns,
	const String& className,
	ELocalOnlyFlag localOnly, EIncludeQualifiersFlag includeQualifiers,
	EIncludeClassOriginFlag includeClassOrigin, const StringArray* propertyList,
	OperationContext& context)
{
	return m_pServer->getClass(ns, className, localOnly, includeQualifiers,
		includeClassOrigin, propertyList, context);
}
#ifndef OW_DISABLE_QUALIFIER_DECLARATION
void IndicationRepLayerImpl::enumQualifierTypes(
	const String& ns,
	CIMQualifierTypeResultHandlerIFC& result, OperationContext& context)
{
	m_pServer->enumQualifierTypes(ns, result, context);
}
void IndicationRepLayerImpl::deleteQualifierType(const String& ns, const String& qualName,
	OperationContext& context)
{
	m_pServer->deleteQualifierType(ns, qualName, context);
}
void IndicationRepLayerImpl::setQualifierType(const String& ns,
	const CIMQualifierType& qt, OperationContext& context)
{
	m_pServer->setQualifierType(ns, qt, context);
}
#endif // #ifndef OW_DISABLE_QUALIFIER_DECLARATION
#ifndef OW_DISABLE_INSTANCE_MANIPULATION
#if !defined(OW_DISABLE_PROPERTY_OPERATIONS)
void IndicationRepLayerImpl::setProperty(
	const String& ns,
	const CIMObjectPath &name,
	const String &propertyName, const CIMValue &cv,
	OperationContext& context)
{
	m_pServer->setProperty(ns, name, propertyName, cv, context);
}
#endif // #if !defined(OW_DISABLE_PROPERTY_OPERATIONS)
#endif // #ifndef OW_DISABLE_INSTANCE_MANIPULATION
#if !defined(OW_DISABLE_PROPERTY_OPERATIONS)
CIMValue IndicationRepLayerImpl::getProperty(
	const String& ns,
	const CIMObjectPath &name,
	const String &propertyName, OperationContext& context)
{
	return m_pServer->getProperty(ns, name, propertyName, context);
}
#endif // #if !defined(OW_DISABLE_PROPERTY_OPERATIONS)
#ifndef OW_DISABLE_ASSOCIATION_TRAVERSAL
void IndicationRepLayerImpl::associators(
	const String& ns,
	const CIMObjectPath &path,
	CIMInstanceResultHandlerIFC& result,
	const String &assocClass, const String &resultClass,
	const String &role, const String &resultRole,
	EIncludeQualifiersFlag includeQualifiers, EIncludeClassOriginFlag includeClassOrigin,
	const StringArray* propertyList, OperationContext& context)
{
	m_pServer->associators(ns, path, result, assocClass, resultClass, role,
		resultRole, includeQualifiers, includeClassOrigin, propertyList, context);
}
void IndicationRepLayerImpl::associatorsClasses(
	const String& ns,
	const CIMObjectPath &path,
	CIMClassResultHandlerIFC& result,
	const String &assocClass, const String &resultClass,
	const String &role, const String &resultRole,
	EIncludeQualifiersFlag includeQualifiers, EIncludeClassOriginFlag includeClassOrigin,
	const StringArray* propertyList, OperationContext& context)
{
	m_pServer->associatorsClasses(ns, path, result, assocClass, resultClass, role,
		resultRole, includeQualifiers, includeClassOrigin, propertyList, context);
}
void IndicationRepLayerImpl::references(
	const String& ns,
	const CIMObjectPath &path,
	CIMInstanceResultHandlerIFC& result,
	const String &resultClass, const String &role,
	EIncludeQualifiersFlag includeQualifiers, EIncludeClassOriginFlag includeClassOrigin,
	const StringArray* propertyList, OperationContext& context)
{
	m_pServer->references(ns, path, result, resultClass, role,
		includeQualifiers, includeClassOrigin, propertyList, context);
}
void IndicationRepLayerImpl::referencesClasses(
	const String& ns,
	const CIMObjectPath &path,
	CIMClassResultHandlerIFC& result,
	const String &resultClass, const String &role,
	EIncludeQualifiersFlag includeQualifiers, EIncludeClassOriginFlag includeClassOrigin,
	const StringArray* propertyList, OperationContext& context)
{
	m_pServer->referencesClasses(ns, path, result, resultClass, role,
		includeQualifiers, includeClassOrigin, propertyList, context);
}
void IndicationRepLayerImpl::associatorNames(
	const String& ns,
	const CIMObjectPath &path,
	CIMObjectPathResultHandlerIFC& result,
	const String &assocClass,
	const String &resultClass, const String &role,
	const String &resultRole, OperationContext& context)
{
	m_pServer->associatorNames(ns, path, result, assocClass, resultClass, role,
		resultRole, context);
}
void IndicationRepLayerImpl::referenceNames(
	const String& ns,
	const CIMObjectPath &path,
	CIMObjectPathResultHandlerIFC& result,
	const String &resultClass,
	const String &role, OperationContext& context)
{
	m_pServer->referenceNames(ns, path, result, resultClass, role, context);
}
#endif // #ifndef OW_DISABLE_ASSOCIATION_TRAVERSAL
void IndicationRepLayerImpl::execQuery(
	const String& ns,
	CIMInstanceResultHandlerIFC& result,
	const String &query, const String& queryLanguage,
	OperationContext& context)
{
	m_pServer->execQuery(ns, result, query, queryLanguage, context);
}
#if !defined(OW_DISABLE_INSTANCE_MANIPULATION) && !defined(OW_DISABLE_NAMESPACE_MANIPULATION)
void IndicationRepLayerImpl::deleteNameSpace(const String &ns, OperationContext& context)
{
	m_pServer->deleteNameSpace(ns, context);
}
void IndicationRepLayerImpl::createNameSpace(const String& ns, OperationContext& context)
{
	m_pServer->createNameSpace(ns, context);
}
#endif // #ifndef OW_DISABLE_INSTANCE_MANIPULATION
void IndicationRepLayerImpl::enumNameSpace(StringResultHandlerIFC& result,
	OperationContext& context)
{
	m_pServer->enumNameSpace(result, context);
}
void IndicationRepLayerImpl::beginOperation(WBEMFlags::EOperationFlag op, OperationContext& context)
{
	m_pServer->beginOperation(op, context);
}
void IndicationRepLayerImpl::endOperation(WBEMFlags::EOperationFlag op, OperationContext& context, WBEMFlags::EOperationResultFlag result)
{
	m_pServer->endOperation(op, context, result);
}
void IndicationRepLayerImpl::setCIMServer(const RepositoryIFCRef& src)
{
	m_pServer = src;
	ServiceEnvironmentIFCRef env = m_pServer->getEnvironment();
	m_pEnv = env.cast_to<CIMOMEnvironment>();
}
void IndicationRepLayerImpl::exportIndication(const CIMInstance& instance,
	const String& instNS)
{
	m_pEnv->exportIndication(instance, instNS);
}

} // end namespace OW_NAMESPACE

//////////////////////////////////////////////////////////////////////////////
extern "C" OW_EXPORT OW_NAMESPACE::IndicationRepLayer*
createIndicationRepLayer()
{
	return new OW_NAMESPACE::IndicationRepLayerImpl;
}
//////////////////////////////////////////////////////////////////////////////
#if !defined(OW_STATIC_SERVICES)
extern "C" OW_EXPORT const char*
getOWVersion()
{
	return OW_VERSION;
}
#endif /* !defined(OW_STATIC_SERVICES) */


text:
package net.tridentsdk.server.packet.status;

import io.netty.buffer.ByteBuf;
import net.tridentsdk.server.packet.PacketOut;

/**
 * Server response to {@link StatusInPing}.
 */
public final class StatusOutPong extends PacketOut {
    /**
     * The time that was sent by the ping packet
     */
    private final long time;

    public StatusOutPong(long time) {
        super(StatusOutPong.class);
        this.time = time;
    }

    @Override
    public void write(ByteBuf buf) {
        // Schema:
        // long:time
        // fucking mojang won't make up their mind with
        // varlong and long and bs like that
        buf.writeLong(this.time);
    }
}


text: Welcome to Geo Twitter.


text:
package chapter07

import java.net.{MalformedURLException, URL}

object CatchYields {
  def main(args: Array[String]): Unit = {

    println(UrlFor("https://www.facebook.com"))
  }

  def UrlFor(path: String): URL =
    try {
      new URL(path)
    } catch {
      case e: MalformedURLException => new URL("https://www.google.com")
    }
}


text:
class AddRememberMe < ActiveRecord::Migration
  def self.up
    add_column :users, :auth_token, :string
    add_column :users, :auth_token_exp, :datetime
  end

  def self.down
    remove_column :users, :auth_token
    remove_column :users, :auth_token_exp
  end
end


text:
package com.amazonaws.services.securityhub.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.securityhub.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * AwsS3BucketWebsiteConfigurationRoutingRuleConditionMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class AwsS3BucketWebsiteConfigurationRoutingRuleConditionMarshaller {

    private static final MarshallingInfo<String> HTTPERRORCODERETURNEDEQUALS_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("HttpErrorCodeReturnedEquals").build();
    private static final MarshallingInfo<String> KEYPREFIXEQUALS_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("KeyPrefixEquals").build();

    private static final AwsS3BucketWebsiteConfigurationRoutingRuleConditionMarshaller instance = new AwsS3BucketWebsiteConfigurationRoutingRuleConditionMarshaller();

    public static AwsS3BucketWebsiteConfigurationRoutingRuleConditionMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(AwsS3BucketWebsiteConfigurationRoutingRuleCondition awsS3BucketWebsiteConfigurationRoutingRuleCondition,
            ProtocolMarshaller protocolMarshaller) {

        if (awsS3BucketWebsiteConfigurationRoutingRuleCondition == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(awsS3BucketWebsiteConfigurationRoutingRuleCondition.getHttpErrorCodeReturnedEquals(),
                    HTTPERRORCODERETURNEDEQUALS_BINDING);
            protocolMarshaller.marshall(awsS3BucketWebsiteConfigurationRoutingRuleCondition.getKeyPrefixEquals(), KEYPREFIXEQUALS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
package net.nemerosa.ontrack.jenkins.dsl.facade;

public interface ProjectFacade {
    /**
     * Gets or creates a branch for this project
     *
     * @param name        Name of the branch
     * @param description Description of the branch
     * @param getIfExists If true, gets the branch if it exists already, otherwise fails.
     * @return Created or existing branch
     */
    BranchFacade branch(String name, String description, boolean getIfExists);

    /**
     * Object to inject in any Ontrack DSL script
     * @return Object to inject in place of this facade
     */
    Object getDSLRoot();
}


text: This repository is for AP Computer Science course at CMIS 2017-2018 (edited)


text:
title: Pixleight
menu: home

form:
    name: contact-form
    action: /home
    fields:
        - name: name
          label: Name
          placeholder: Enter your name
          autocomplete: on
          type: text
          validate:
            required: true

        - name: email
          label: Email
          placeholder: Enter your email address
          type: text
          validate:
            rule: email
            required: true

        - name: message
          label: Message
          size: long
          placeholder: Enter your message
          type: textarea
          validate:
            required: true

    buttons:
        - type: submit
          value: Submit
          class: submit

    process:
        - email:
            from: "{{ config.plugins.email.from }}"
            to:
              - "{{ config.plugins.email.to }}"
              - "{{ form.value.email }}"
            subject: "[Feedback] {{ form.value.name|e }}"
            body: "{% include 'forms/data.html.twig' %}"
        - save:
            fileprefix: feedback-
            dateformat: Ymd-His-u
            extension: txt
            body: "{% include 'forms/data.txt.twig' %}"
        - message: Thank you for your feedback!
        - display: thankyou

onpage_menu: true
content:
    items: @self.modular
    order:
        by: default
        dir: asc
        custom:
            - _portfolio
            - _about
            - _resume
            - _call
            - _testimonials
            - _contact
---


text:
class CurrenciesHaveSymbols < ActiveRecord::Migration::Current
  def self.up
    # We use € for default currency symbol
    add_column "currencies", "symbol", :string, default: "€"
  end

  def self.down
    remove_column "currencies", "symbol"
  end
end


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

namespace _04.Merging_numbers
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var length = int.Parse(Console.ReadLine());
            var arrN = new int[length];
            var arrS = new string[length];
            for (int i = 0; i < length; i++)
            {
                arrS[i] = Console.ReadLine();
                arrN[i] = int.Parse(arrS[i]);
            }

            var sb_line1 = new StringBuilder();
            var sb_line2 = new StringBuilder();
            for (int i = 0; i < length - 1; i++)
            {
                sb_line1.AppendFormat("{0}{1} ", (char) arrS[i][arrS[i].Length - 1], (char) arrS[i + 1][0]);
                sb_line2.AppendFormat("{0} ", arrN[i] + arrN[i + 1]);
            }
            var line1 = sb_line1.ToString().Trim();
            var line2 = sb_line2.ToString().Trim();

            Console.WriteLine(line1);
            Console.WriteLine(line2);
        }
    }
}


text:
title: "3/4 pose"
excerpt: "PaperFaces portrait of @Coffeeplz drawn with Paper for iOS on an iPad."
image:
  path: &image /assets/images/paperfaces-coffeeplz-twitter.jpg
  feature: *image
  thumbnail: /assets/images/paperfaces-coffeeplz-twitter-150.jpg
categories: [paperfaces]
tags: [portrait, illustration, Paper for iOS]
---

PaperFaces portrait of [@Coffeeplz](https://twitter.com/Coffeeplz).

{% include_cached boilerplate/paperfaces.md %}


text:
<?php

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');

?>

	<?php if($this->manager('report') and $this->report){
		?>

<?php
	} ?>

			<button class="btn btn-small">
				<a href="http://virtuemart.net/news/list-all-news" target="_blank" title="<?php echo vmText::_('COM_VIRTUEMART_ALL_NEWS'); ?>"><?php echo vmText::_('COM_VIRTUEMART_ALL_NEWS'); ?>
			</button>

	<a class="cpanel" style="display: block;" href="http://extensions.joomla.org/extensions/e-commerce/shopping-cart/129" target="_blank" title=" <?php echo vmText::_('COM_VIRTUEMART_VOTE_JED_DESC') ?>"> <?php echo vmText::_('COM_VIRTUEMART_VOTE_JED_DESC') ?>

<?php echo vmText::_('COM_VIRTUEMART_FEED_LATEST_NEWS')?>

		<a href="http://extensions.virtuemart.net" target="_blank" title="<?php echo vmText::_('COM_VIRTUEMART_ALL_EXTENSIONS') ?>"> <?php echo vmText::_('COM_VIRTUEMART_ALL_EXTENSIONS') ?>


text:
require "test_helper"
require_relative "common"

class ActionCable::SubscriptionAdapter::TestTest < ActionCable::TestCase
  include CommonSubscriptionAdapterTest

  def setup
    super

    @tx_adapter.shutdown
    @tx_adapter = @rx_adapter
  end

  def cable_config
    { adapter: "test" }
  end

  test "#broadcast stores messages for streams" do
    @tx_adapter.broadcast("channel", "payload")
    @tx_adapter.broadcast("channel2", "payload2")

    assert_equal ["payload"], @tx_adapter.broadcasts("channel")
    assert_equal ["payload2"], @tx_adapter.broadcasts("channel2")
  end

  test "#clear_messages deletes recorded broadcasts for the channel" do
    @tx_adapter.broadcast("channel", "payload")
    @tx_adapter.broadcast("channel2", "payload2")

    @tx_adapter.clear_messages("channel")

    assert_equal [], @tx_adapter.broadcasts("channel")
    assert_equal ["payload2"], @tx_adapter.broadcasts("channel2")
  end

  test "#clear deletes all recorded broadcasts" do
    @tx_adapter.broadcast("channel", "payload")
    @tx_adapter.broadcast("channel2", "payload2")

    @tx_adapter.clear

    assert_equal [], @tx_adapter.broadcasts("channel")
    assert_equal [], @tx_adapter.broadcasts("channel2")
  end
end


text:
import logging
import re
from datetime import datetime as dt
from time import sleep

import unicodecsv as csv
import yaml

from twython import Twython
from twython.exceptions import TwythonRateLimitError, TwythonError, TwythonAuthError

logger = logging.getLogger('TwittrScrapr.BaseScrapr')

class TwittrScrapr(object):
    """
    The base TwittrScrapr class takes care of some configurations that are common to all of its
    descendants, including managing the object's connection to the Twitter API, consistent handling
    of some common Twython error cases, and utilities for parsing user inputs.
    """

    def __init__(self, key_path, writer):
        """
        Load API keys and initialize a Twython object

        :param key_path: location of a ``YAML`` file containing the application's API keys.
        """
        logger.debug('Loading keys from file {}'.format(key_path))

        with open(key_path, 'r') as inf:
            keys = yaml.load(inf)
            oauth_key = keys['API_KEY']
            oauth_secret = keys['API_SECRET']

        logger.debug('Authenticating application with twitter')

        try:
            t = Twython(oauth_key, oauth_secret, oauth_version=2)
            self.api = Twython(oauth_key, access_token=t.obtain_access_token())

        except TwythonAuthError:
            logger.error("Could not authorize Twython Object. Ensure that your keys are valid.")
            exit(1)

        self.scrape_queue = []
        self.search_type = None
        self.reset_time = None
        self.calls_remaining = None
        self.writer = writer

    @classmethod
    def error_handler(cls, func):
        def wrapper(self, *args, **kwargs):
            try:
                return func(self, *args, **kwargs)

            except TwythonRateLimitError:
                # stop everything until we've handled an appropriately long backoff
                logger.warning('Rate limit reached without catch - check proactive rate handling\n\t Initiating 15 minute backoff...')
                sleep(910)

                # reset the header parameters
                logger.debug('Backoff complete, resetting rate limit variables...')
                self.reset_time = None
                self.calls_remaining = None

                return None

            except TwythonError, e:
                # log the error for the user
                logger.error('Twitter API threw and error: \n{0}'.format(e))

                # still make sure we update the number of api calls remaining
                self.reset_time = self.api.get_lastfunction_header('x-rate-limit-reset')
                self.calls_remaining = self.api.get_lastfunction_header('x-rate-limit-remaining')
                logger.debug('Calls Remaining: {}'.format(self.calls_remaining))
                logger.debug('Rate limit will reset at: {}'.format(self.reset_time))

                return None

        return wrapper

    @staticmethod
    def sanitize(screen_name):
        """ Return a string containing only the valid characters for a Twitter screen name

        The sanitize method will attempt to interpret

        :param screen_name: string to convert to a valid twitter screen name
        :return: A string that could represent a valid twitter screen name (note that there is no validation against the API
        """

        if re.match("^@?[a-zA-Z0-9-_]+$", screen_name):
            return screen_name.lstrip('@').strip()
        else:
            # handle urls more carefully
            exp = re.compile("(?:https?://)?(?:www\.)?twitter\.com/(?:(?:\w)*#!/)?(?:pages/)?(?:[\w\-]*/)*([\w\-\.]*)")
            matches = exp.findall(screen_name)
            try:
                user = matches[0].strip()
                return user if re.match("^[a-zA-Z0-9-_]+$", user) else False
            except IndexError:  # something was either empty or the parsing failed to match
                return None

    def check_rate_limit(self, threshold=1):
        """
        Check the response headers from Twitter to avoid running afoul of rate limiting.
        Uses Twython's get_lastfunction_header:
            https://twython.readthedocs.org/en/latest/api.html#twython.Twython.get_lastfunction_header

        :param threshold: (optional) The number of remaining API calls
        :return True: Once this function returns, it's ok to submit additional API requests
        """
        if self.calls_remaining and self.calls_remaining <= threshold:
            reset_ts = dt.fromtimestamp(self.reset_time)

            while dt.now() <= reset_ts:
                delta = reset_ts - dt.now()
                if delta.seconds % 60 == 0:
                    logger.debug('  :: {} minutes remaining...'.format(delta.seconds / 60))
                sleep(1)

            # ensure not to return within the same second that the rate limiting expires
            sleep(1)
            self.calls_remaining = None
            self.reset_time = None

        return True

    def _infer_profile_type(self, override_mode, ids):
        """
        Infer whether the uploaded data file contains user ids or screennames.

        :param override_mode:
        :param ids:
        :return:
        """
        if override_mode == 1:
            logger.info("Override provided: will interpret passed data as screen names")
            profile_type = "screenname"
            queue = [self.sanitize(r) for r in ids]

        elif override_mode == 2:
            logger.info("Override provided: will interpret passed data as user ids")
            profile_type = "user_id"
            queue = ids

        else:
            sample = ids[0:min(10, len(ids))]
            try:  # check if they are IDs
                [int(s) for s in sample]
                logger.info('No override set: Inferred user_id from input')
                profile_type = 'user_id'
                queue = ids
            except ValueError:  # they are screennames
                logger.info('No override set: Inferred screen_name from input')
                profile_type = 'screenname'
                queue = [TwittrScrapr.sanitize(r) for r in ids]

        self.search_type = profile_type
        self.scrape_queue = queue

        return True

    def initialize_queue_from_file(self, infile, skip_header=True, override_mode=None, col_idx=0):
        """

        :param infile:
        :param skip_header:
        :param override_mode:
        :param col_idx:
        :return:
        """

        # get raw user identity information from infile
        with open(infile, 'rU') as inf:
            reader = csv.reader(inf)
            if skip_header:
                print 'Skipping header'
                reader.next()

            raw_ids = [row[col_idx] for row in reader]

        self._infer_profile_type(override_mode, raw_ids)

        # determine what type of ID is being used

        logger.debug("Initialized a queue of {} users to scrape".format(len(self.scrape_queue)))

        return

    def write_outputs(self, rows):
        """
        Write one or more rows to the output file.

        :param rows: An array, or nested array of data to write to the output file.
        :return: The number of rows written
        """
        self.writer.write(rows)

        return True


text:
require 'spec_helper'

describe ElectricSheep::Helpers::ShellSafe do

  ShellSafeKlazz = Class.new do
    include ElectricSheep::Helpers::ShellSafe
  end

  describe ShellSafeKlazz do

  it 'escapes shell expressions' do
    ShellSafeKlazz.new.shell_safe('"expression').must_equal "\\\"expression"
  end

  end

end


text:
"""
@author: Daniel Jiménez-Caminero Costa
"""

import numpy as np

def sone2phone(sones):
    """ Conversion between sones and phones, based on the work done by Hugo Fastl and Eberhard Zwicker in the article
    "Psychoacoustics: Facts and Models".

    Parameters
    ----------
    sones: float
        One of the units in which loudness is measured. 1 sone equals to 40 phones. The conversion from sones to phones
        is not linear.

    Returns
    -------
    phons: float
        Logarithmic unit of loudness (phon = Ln). The dB SPL values of the signal at 1 kHz have the same value in
        phons. For example, 50 db SPL @ 1 kHz corresponds to 50 phones. The rest of the frequencies does not have
        the same co-relation between each other.

    """

    if sones >= 1:
        phons = 40 + ((10 * np.log10(sones)) / np.log10(2))

    else:
        phons = 40 * ((sones + 0.0005) ** 0.35)
    return phons


text:
class AddDescriptionToQuiz < ActiveRecord::Migration
  def change
    add_column :quizzes, :description, :text
  end
end


text:
To use active_encode with MediaConvert, you will need:

* An AWS account that has access to create MediaConvert jobs
* An AWS [IAM service role that has access to necessary AWS resources](https://docs.aws.amazon.com/mediaconvert/latest/ug/iam-role.html).
* An S3 bucket to store source files
* An S3 bucket to store derivatives (recommended to be separate)
* Existing [MediaConvert Output presets](https://docs.aws.amazon.com/mediaconvert/latest/ug/creating-preset-from-scratch.html) to define your outputs (eg desired HLS adaptive variants)
* EventBridge/Cloudfront setup to store output (can be automatically created by code we include here)
* You have to add these gems to your project Gemfile, that are required for
 the mediaconvert adapter but not included as active_encode dependencies:
  * aws-sdk-cloudwatchevents
  * aws-sdk-cloudwatchlogs
  * aws-sdk-mediaconvert
  * aws-sdk-s3

You may find this tutorial helpful to create the AWS resources you need, or debug the process: https://github.com/aws-samples/aws-media-services-simple-vod-workflow (mainly the firsst two modules).

## Note: No Technical Metadata

This adapter does _not_ perform input characterization or fill out technical metadata in the encoding job `input` object. technical metadata in `encode.input` such as `width`, `duration`,
or `video_codec` will be nil.

## CloudWatch and EventBridge setup, optionally with setup!

[AWS Elemental MediaConvert](https://aws.amazon.com/mediaconvert/) makes it difficult to acesss
detailed output information in the job description that can be pulled directly from the service. One way to work around this is capture the MediaConvert job status notification
when the job status changes to `COMPLETE`, via an
[Amazon Eventbridge](https://aws.amazon.com/eventbridge/) rule that forwards the status change
notification to another service for capture and/or handling -- for instance a CloudWatch Logs]
(https://aws.amazon.com/cloudwatch/) log group.

`ActiveEncode::EngineAdapters::MediaConvert` is written to get detailed output information from just such a setup, a CloudWatch log group that has been set up to receive MediaConvert job status `COMPLETE` notifications via an EventBridge rule.

We proide a method to create this CloudWatch and EventBridge infrastructure for you, the `#setup!` method.

```ruby
ActiveEncode::Base.engine_adapter = :media_convert
ActiveEncode::Base.engine_adapter.setup!
```

The active AWS user/role when calling the `#setup!` method will require permissions to create the
necessary CloudWatch and EventBridge resources.

The `setup!` task will create an EventBridge rule name and CloudWatch log group name based on the MediaConvert queue setting, by default `"Default"`. So:
* EventBridge rule: `active-encode-mediaconvert-Default`
* Log group name: `/aws/events/active-encode/mediaconvert/Default`

The names chosen will respect the `log_group` and `queue` config though, if set.

**Alternately**, we have an experimental flag to get and derive what output information we can
directly from the job without requiring a CloudWatch log -- this is expected to be complete
only for  HLS output at present. It seems to work well for HLS output. To opt-in, and not require CloudWatch logs, try:

    ActiveEncode::Base.engine_adapter.direct_output_lookup = true

## Configuration

Some parameters are set as (typically global) configuration, while others are passed in as parameters to `create`. Here we'll discuss the configuration.

* `role`. Required. An IAM role that the MediaConvert job will run under. This is [required by MediaConvert](https://docs.aws.amazon.com/mediaconvert/latest/ug/iam-role.html), it can't just use your current AWS credentials.

* `output_bucket`. Required.  An S3 bucket name, all output will be written to this bucket, at a path prefix specified in the `create` call.

* `log_group`. Optional, unusual. Specify the name of the CloudWatch log group to use for logging. By default, will be constructed automatically from the MediaConvert queue to use.

* `queue`. Optional, unusual. Specify the name of the [MediaConvert queue](https://docs.aws.amazon.com/mediaconvert/latest/ug/working-with-queues.html) to use. By default it will use the MediaConvert default, called `"Default"`. Ordinarily there is no reason to set this.

```ruby
ActiveEncode::Base.engine_adapter = :media_convert

ActiveEncode::Base.engine_adapter.role = 'arn:aws:iam::11111111111111:role/my-role-name'
ActiveEncode::Base.engine_adapter.output_bucket = 'my-bucket-name'
```

## Input and output options, and the masterfile_bucket

The adapter can take a local file as argument (via `file://` URL or any other standard way for ActiveEncode), _or_ an `s3://` URL.

The input, whether local file _or_ remote S3 file, is normally _copied_ to a random-string-path location on the `masterfile_bucket`, and then that copy is used as input for the MediaConvert process.  Unless the input is already an `s3://` URL located in the `masterfile_bucket`, then it is just used.

```ruby
ActiveEncode::Base.create(
  "file://path/to/file.mp4",
  {
    masterfile_bucket: "my-masterfile-bucket"
    output_prefix: "path/to/output/base_name_of_outputs",
    outputs: [
      { preset: "my-hls-preset-high", modifier: "_high" },
      { preset: "my-hls-preset-medium", modifier: "_medium" },
      { preset: "my-hls-preset-low", modifier: "_low" }
    ]
  }
)
# your input will be COPIED to my-masterfile-bucket and that copy passed
# as an input to the MediaConvert operation.
```

However, if you pass the `use_original_url` bucket, then an `s3://` input URL you pass in will _not_ be copied to `masterfile_bucket`, but passed direct as input to the MediaConvert process.

```ruby
ActiveEncode::Base.create(
  "s3://some-other-bucket/path/to/file.mp4",
  {
    masterfile_bucket: "my-masterfile-bucket"
    use_original_url: true,
    output_prefix: "path/to/output/base_name_of_outputs",
    outputs: [
      { preset: "my-hls-preset-high", modifier: "_high" },
      { preset: "my-hls-preset-medium", modifier: "_medium" },
    ]
  }
)
# the S3 input will be used directly as input to the MediaConvert process,
# it will not be copied to the masterfile_bucket first.
```

Only in this case of `use_original_url` and an `s3://` input source, the `masterfile_bucket` argument can be ommitted, since it will be used.

You can also use `destination` instead of `output_prefix`, to supply a complete `s3://` url,
ignoring `output_bucket` config. With `use_original_url` you can now supply inputs and
outputs as simple s3 urls.

```ruby
ActiveEncode::Base.create(
  "s3://some-other-bucket/path/to/file.mp4",
  {
    use_original_url: true,
    destination: "s3://my-output-bucket/path/to/output/base_name_of_outputs",
    outputs: [
      { preset: "my-hls-preset-high", modifier: "_high" },
      { preset: "my-hls-preset-medium", modifier: "_medium" },
    ]
  }
)
```

## AWS Auth Credentials

The adapter, when interacting with AWS services, will interact with AWS using the [current AWS credentials looked up from environment](https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/setup-config.html#aws-ruby-sdk-setting-credentials) in the standard way, such as the `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` [environmental variables](https://docs.aws.amazon.com/sdkref/latest/guide/environment-variables.html), or [on disk at in a credentials file](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html).

The IAM identity, in order to issue MediaConvert jobs and get output information from CloudWatch, will need the following permissions, such as in this example policy:

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "mediaconvertActions",
      "Effect": "Allow",
      "Action": "mediaconvert:*",
      "Resource": "*"
    },
    {
      "Sid": "iamPassRole",
      "Effect": "Allow",
      "Action": "iam:PassRole",
      "Resource": "arn:aws:iam::111122223333:role/MediaConvertRole"
    },
    {
      "Sid": "logsStartQuery",
      "Effect": "Allow",
      "Action": "logs:StartQuery",
      "Resource": "*"
    },
    {
      "Sid": "logsGetQuery",
      "Effect": "Allow",
      "Action": "logs:GetQueryResult",
      "Resource": "*"
    },
  ]
}
```

Where the `iamPassRole` resource is the role you will pass in the `role` configuration. The `logsStartQuery` and `logsGetQuery` permissions could probably additionally be limited to the specific CloudWatch log group.

MediaConvert necessarily [requires you to pass a separate IAM role](https://docs.aws.amazon.com/mediaconvert/latest/ug/iam-role.html) that will be used by the actual MediaConvert operation -- the `role` config for this adapter. That role will need this permission:

```json
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "execute-api:Invoke",
                "execute-api:ManageConnections"
            ],
            "Resource": "arn:aws:execute-api:*:*:*"
        }
    ]
}
```

In addition to read/write access to the relevant S3 buckets.

Also see [this tutorial](https://github.com/aws-samples/aws-media-services-simple-vod-workflow/blob/master/1-IAMandS3/README.md#1-create-an-iam-role-to-use-with-aws-elemental-mediaconvert)


text:
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="torque-slide.html">
<script>
  Polymer({
    is: 'torque-slides',
    properties: {
      duration:  { type: Number },
      current:   { type: Number, observer: 'currentChanged' },
      countdown: { type: Number }
    },
    ready: function(){
      var self = this;
      window.addEventListener('WebComponentsReady', function(e) {
        self.list = self.querySelectorAll('torque-slides /deep/ torque-slide');
        for(var i = 1; i < self.list.length; i++) {
          self.list[i].hidden = true;
        }
        self.current = 0;
        self.countdown = self.list[0].getAttribute('duration') || self.duration;

        setInterval(function(){ self.updateSlide(); }, 1000);
      });
    },
    currentChanged: function(newValue, oldValue) {
      if(oldValue !== undefined) {
        this.list[oldValue].hidden = true;
      }
      this.list[newValue].hidden = false;
    },
    updateSlide: function() {
      if(this.countdown === 0){
        this.current = (this.current + 1) % this.list.length;
        var current = this.list[this.current];
        this.countdown = current.getAttribute('duration') || this.duration;
      } else {
        this.countdown -= 1;
      }
    }
  });
</script>


text:
<?php
/**
 * This file belongs to the AnoynmFramework
 *
 * @author vahitserifsaglam <vahit.serif119@gmail.com>
 * @see http://gemframework.com
 *
 * Thanks for using
 */

namespace Anonym\Session;

use SessionHandlerInterface;
use Anonym\Cookie\Cookie;

class CookieSessionHandler implements SessionHandlerInterface
{

    /**
     * the instane of cookie
     *
     * @var Cookie
     */
    protected $cookie;

    /**
     * lifetime of int
     *
     * @var int
     */
    protected $lifetime;

    /**
     * create a new instance
     *
     * @param Cookie $cookie
     * @param $lifetime
     */
    public function __construct(Cookie $cookie, $lifetime)
    {
        $this->cookie = $cookie;
        $this->lifetime = $lifetime;
    }

    /**
     * Close the session
     * @link http://php.net/manual/en/sessionhandlerinterface.close.php
     * @return bool

     * The return value (usually TRUE on success, FALSE on failure).
     * Note this value is returned internally to PHP for processing.
     *

     * @since 5.4.0
     */
    public function close()
    {
        return true;
    }

    /**
     * Destroy a session
     * @link http://php.net/manual/en/sessionhandlerinterface.destroy.php
     * @param string $session_id The session ID being destroyed.
     * @return bool

     * The return value (usually TRUE on success, FALSE on failure).
     * Note this value is returned internally to PHP for processing.
     *

     * @since 5.4.0
     */
    public function destroy($session_id)
    {

        $this->cookie->delete($this->prepareSession($session_id));
        return true;
    }

    /**
     * prepare name for session
     *
     * @param string $name
     * @return string
     */
    private function prepareSession($name){
        return $name."-session";
    }
    /**
     * Cleanup old sessions
     * @link http://php.net/manual/en/sessionhandlerinterface.gc.php
     * @param int $maxlifetime

     * Sessions that have not updated for
     * the last maxlifetime seconds will be removed.
     *

     * @return bool

     * The return value (usually TRUE on success, FALSE on failure).
     * Note this value is returned internally to PHP for processing.
     *

     * @since 5.4.0
     */
    public function gc($maxlifetime)
    {
        return true;
    }

    /**
     * Initialize session
     * @link http://php.net/manual/en/sessionhandlerinterface.open.php
     * @param string $save_path The path where to store/retrieve the session.
     * @param string $session_id The session id.
     * @return bool

     * The return value (usually TRUE on success, FALSE on failure).
     * Note this value is returned internally to PHP for processing.
     *

     * @since 5.4.0
     */
    public function open($save_path, $session_id)
    {
        return true;
    }

    /**
     * Read session data
     * @link http://php.net/manual/en/sessionhandlerinterface.read.php
     * @param string $session_id The session id to read data for.
     * @return string

     * Returns an encoded string of the read data.
     * If nothing was read, it must return an empty string.
     * Note this value is returned internally to PHP for processing.
     *

     * @since 5.4.0
     */
    public function read($session_id)
    {
        $session_id = $this->prepareSession($session_id);

        return $this->cookie->has($session_id) ? $this->cookie->get($session_id) : null;
    }

    /**
     * Write session data
     * @link http://php.net/manual/en/sessionhandlerinterface.write.php
     * @param string $session_id The session id.
     * @param string $session_data

     * The encoded session data. This data is the
     * result of the PHP internally encoding
     * the $_SESSION superglobal to a serialized
     * string and passing it as this parameter.
     * Please note sessions use an alternative serialization method.
     *

     * @return bool

     * The return value (usually TRUE on success, FALSE on failure).
     * Note this value is returned internally to PHP for processing.
     *

     * @since 5.4.0
     */
    public function write($session_id, $session_data)
    {
        $session_id = $this->prepareSession($session_id);

        $this->cookie->set($session_id, $session_data, $this->lifetime);
        return true;
    }
}


text:
package no_0297_serialize_and_deserialize_binary_tree

import (
	"fmt"
	"strconv"
	"strings"
)

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

type Codec struct {
}

func Constructor() Codec {
	return Codec{}
}

// Serializes a tree to a single string.
func (this *Codec) serialize(root *TreeNode) string {
	if root == nil {
		return "X"
	}
	left := this.serialize(root.Left)
	right := this.serialize(root.Right)
	return fmt.Sprintf("(%s)%d(%s)", left, root.Val, right)
}

// Deserializes your encoded data to tree.
func (this *Codec) deserialize(data string) *TreeNode {
	node, _ := this.parse(data)
	return node
}

func (this *Codec) parse(data string) (*TreeNode, string) {
	if data[0] == 'X' {
		return nil, data[1:]
	}
	left, data := this.parseSubtree(data)

	leftBracketIdx := strings.Index(data, "(")
	val, _ := strconv.Atoi(data[:leftBracketIdx])

	right, data := this.parseSubtree(data[leftBracketIdx:])

	node := &TreeNode{
		Val:   val,
		Left:  left,
		Right: right,
	}
	return node, data
}

func (this *Codec) parseSubtree(data string) (*TreeNode, string) {
	data = data[1:] // 跳过 '('
	node, data := this.parse(data)
	data = data[1:] // 跳过 ')'
	return node, data
}

/**
 * Your Codec object will be instantiated and called as such:
 * obj := Constructor();
 * data := obj.serialize(root);
 * ans := obj.deserialize(data);
 */


text:
define(
  [
    'underscore'
  ],
  function gameControllerRequireSuccessCallback (
    _
  ) {

    /**
     * GameController constructor
     * @param {Object} app The app event bus
     */
    var GameController = function GameControllerConstructor ( app ) {
      this.app = app;

      // Make sure the context is preserved
      return _.bindAll( this );
    };

    /**
     * Starts a new game, broadcasts a game:start event
     * @param  {String} word The word for this game
     * @return {Object}      Returns self for chaining, Error instance if no word is provided
     */
    GameController.prototype.start = function gameControllerStart ( word ) {
      if ( !_.isString( word ) ) { return new Error( 'A word is required to start a game, yo.' ); }

      this.word = word;
      this.wordCharacters = _.uniq( word.split( '' ) );
      this.guesses = [];
      // Not too happy with exposing this through 2 properties, method would be safer, yo.
      this.won = undefined;
      this.finished = false;
      this.lastPlayResult = undefined;
      this.app.trigger( 'game:started', word );

      return this;
    };

    /**
     * Handles a play, broadcasts game:character:{correct,incorrect}, game:{won,lost}
     * @param  {String} character The character chosen by the player
     * @return {Object}           Returns self for chaining
     */
    GameController.prototype.play = function gameControllerPlay ( character ) {
      if ( this.finished ) { return; }
      // Calculate play result
      var playResult = _.include( this.wordCharacters, character );
      // Save guess
      this.guesses.push( character );
      // Save the play result for future reference
      // NOTE: we could 'function lastPlayResult () { return _.include( this.wordCharacters, _.last( this.guesses ) ) }' instead
      //       This is only used by tests btw
      this.lastPlayResult = playResult;

      // Remove correctly guessed character, broadcast events
      if ( playResult ) {
        this.wordCharacters = _.without( this.wordCharacters, character );
        this.app.trigger( 'game:character:correct', character );
      } else {
        this.app.trigger( 'game:character:incorrect', character );
      }

      // Update won state
      this.won = _.isEmpty( this.wordCharacters );

      // Broadcast the game result
      if ( this.won ) {
        this.finished = true;
        this.app.trigger( 'game:won' );
      }

      // Player looses when failed guesses > original word characters - _.difference already applies _.uniq to second parameter
      var failedGuesses = _.difference( this.guesses, this.word.split( '' ) );
      if ( failedGuesses.length === this.word.length ) {
        if ( this.finished ) { return; }
        this.finished = true;
        this.app.trigger( 'game:lost' );
      }

      return this;
    };

    return GameController;

} );


text:
package com.s13g;

import com.google.common.base.Objects;

/**
 * Simple point class.
 */
public class Point {
  public final long x;
  public final long y;

  public Point(long first, long second) {
    this.x = first;
    this.y = second;
  }

  @Override
  public int hashCode() {
    return Objects.hashCode(x, y);
  }

  @Override
  public boolean equals(Object obj) {
    if (obj == null) {
      return false;
    }
    Point other = (Point) obj;
    return x == other.x && y == other.y;
  }

  @Override
  public String toString() {
    return "(" + x + " ," + y + ")";
  }
}


text:
<?php
/**
 * Broadcasting Config
 *
 * PHP version 5.6
 *
 * @category Config
 * @package  Config
 * @author   Taylor Otwell <taylorotwell@gmail.com>
 * @license  http://opensource.org/licenses/MIT MIT License
 * @link     https://laravel.com/docs/5.2 Laravel Documentation
 */
return [

    /*
    |--------------------------------------------------------------------------
    | Default Broadcaster
    |--------------------------------------------------------------------------
    |
    | This option controls the default broadcaster that will be used by the
    | framework when an event needs to be broadcast. You may set this to
    | any of the connections defined in the "connections" array below.
    |
    */

    'default' => env('BROADCAST_DRIVER', 'pusher'),

    /*
    |--------------------------------------------------------------------------
    | Broadcast Connections
    |--------------------------------------------------------------------------
    |
    | Here you may define all of the broadcast connections that will be used
    | to broadcast events to other systems or over websockets. Samples of
    | each available type of connection are provided inside this array.
    |
    */

    'connections' => [

        'pusher' => [
            'driver' => 'pusher',
            'key' => env('PUSHER_KEY'),
            'secret' => env('PUSHER_SECRET'),
            'app_id' => env('PUSHER_APP_ID'),
            'options' => [
                //
            ],
        ],

        'redis' => [
            'driver' => 'redis',
            'connection' => 'default',
        ],

        'log' => [
            'driver' => 'log',
        ],

    ],

];


text:
"use strict";
module.exports = function (PromiseArray) {
var util = require("./util.js");
var inherits = util.inherits;
var isArray = util.isArray;

function SomePromiseArray(values, caller, boundTo) {
    this.constructor$(values, caller, boundTo);
    this._howMany = 0;
    this._unwrap = false;
}
inherits(SomePromiseArray, PromiseArray);

SomePromiseArray.prototype._init = function SomePromiseArray$_init() {
    this._init$(void 0, 1);
    var isArrayResolved = isArray(this._values);
    this._holes = isArrayResolved
        ? this._values.length - this.length()
        : 0;

    if (!this._isResolved() && isArrayResolved) {
        this._howMany = Math.max(0, Math.min(this._howMany, this.length()));
        if (this.howMany() > this._canPossiblyFulfill() ) {
            this._reject([]);
        }
    }
};

SomePromiseArray.prototype.setUnwrap = function SomePromiseArray$setUnwrap() {
    this._unwrap = true;
};

SomePromiseArray.prototype.howMany = function SomePromiseArray$howMany() {
    return this._howMany;
};

SomePromiseArray.prototype.setHowMany =
function SomePromiseArray$setHowMany(count) {
    if (this._isResolved()) return;
    this._howMany = count;
};

SomePromiseArray.prototype._promiseFulfilled =
function SomePromiseArray$_promiseFulfilled(value) {
    if (this._isResolved()) return;
    this._addFulfilled(value);
    if (this._fulfilled() === this.howMany()) {
        this._values.length = this.howMany();
        if (this.howMany() === 1 && this._unwrap) {
            this._resolve(this._values[0]);
        }
        else {
            this._resolve(this._values);
        }
    }

};
SomePromiseArray.prototype._promiseRejected =
function SomePromiseArray$_promiseRejected(reason) {
    if (this._isResolved()) return;
    this._addRejected(reason);
    if (this.howMany() > this._canPossiblyFulfill()) {
        if (this._values.length === this.length()) {
            this._reject([]);
        }
        else {
            this._reject(this._values.slice(this.length() + this._holes));
        }
    }
};

SomePromiseArray.prototype._fulfilled = function SomePromiseArray$_fulfilled() {
    return this._totalResolved;
};

SomePromiseArray.prototype._rejected = function SomePromiseArray$_rejected() {
    return this._values.length - this.length() - this._holes;
};

SomePromiseArray.prototype._addRejected =
function SomePromiseArray$_addRejected(reason) {
    this._values.push(reason);
};

SomePromiseArray.prototype._addFulfilled =
function SomePromiseArray$_addFulfilled(value) {
    this._values[this._totalResolved++] = value;
};

SomePromiseArray.prototype._canPossiblyFulfill =
function SomePromiseArray$_canPossiblyFulfill() {
    return this.length() - this._rejected();
};

return SomePromiseArray;
};


text:
FILE(REMOVE_RECURSE
  "CMakeFiles/short_comparison_test.dir/unittests/short_comparison_test.cpp.o"
  "short_comparison_test.pdb"
  "short_comparison_test"
)

# Per-language clean rules from dependency scanning.
FOREACH(lang CXX)
  INCLUDE(CMakeFiles/short_comparison_test.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)


text:
from google.appengine.api import memcache

class Cache():
  keys = []
  def add(self, key, data):
    if not key in self.keys:
      self.keys.append(key)
    memcache.set(key, data)
  def get(self, key):
    return memcache.get(key)
  def clear(self):
    return memcache.flush_all();


text:
package com.swifts.frame.modules.act.entity;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.swifts.frame.common.utils.StringUtils;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.swifts.frame.common.persistence.BaseEntity;
import com.swifts.frame.common.utils.TimeUtils;
import com.swifts.frame.modules.act.utils.Variable;

/**
 * 工作流Entity
 * @author ThinkGem
 * @version 2013-11-03
 */
public class Act extends BaseEntity<Act> {

	private static final long serialVersionUID = 1L;

	private String taskId; 		// 任务编号
	private String taskName; 	// 任务名称
	private String taskDefKey; 	// 任务定义Key(任务环节标识)

	private String procInsId; 	// 流程实例ID
	private String procDefId; 	// 流程定义ID
	private String procDefKey; 	// 流程定义Key(流程定义标识)

	private String businessTable;	// 业务绑定Table
	private String businessId;		// 业务绑定ID

	private String title; 		// 任务标题

	private String status; 		// 任务状态(todo/claim/finish)

//	private String procExecUrl; 	// 流程执行(办理)RUL
	private String comment; 	// 任务意见
	private String flag; 		// 意见状态

	private Task task; 			// 任务对象
	private ProcessDefinition procDef; 	// 流程定义对象
	private ProcessInstance procIns;	// 流程实例对象
	private HistoricTaskInstance histTask; // 历史任务
	private HistoricActivityInstance histIns;	//历史活动任务

	private String assignee; // 任务执行人编号
	private String assigneeName; // 任务执行人名称

	private Variable vars; 		// 流程变量
//	private Variable taskVars; 	// 流程任务变量

	private Date beginDate;	// 开始查询日期
	private Date endDate;	// 结束查询日期

	private List<Act> list; // 任务列表

	public Act() {
		super();
	}

	public String getTaskId() {
		if (taskId == null && task != null){
			taskId = task.getId();
		}
		return taskId;
	}

	public void setTaskId(String taskId) {
		this.taskId = taskId;
	}

	public String getTaskName() {
		if (taskName == null && task != null){
			taskName = task.getName();
		}
		return taskName;
	}

	public void setTaskName(String taskName) {
		this.taskName = taskName;
	}

	public String getTaskDefKey() {
		if (taskDefKey == null && task != null){
			taskDefKey = task.getTaskDefinitionKey();
		}
		return taskDefKey;
	}

	public void setTaskDefKey(String taskDefKey) {
		this.taskDefKey = taskDefKey;
	}

	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
	public Date getTaskCreateDate() {
		if (task != null){
			return task.getCreateTime();
		}
		return null;
	}

	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
	public Date getTaskEndDate() {
		if (histTask != null){
			return histTask.getEndTime();
		}
		return null;
	}

	@JsonIgnore
	public Task getTask() {
		return task;
	}

	public void setTask(Task task) {
		this.task = task;
	}

	@JsonIgnore
	public ProcessDefinition getProcDef() {
		return procDef;
	}

	public void setProcDef(ProcessDefinition procDef) {
		this.procDef = procDef;
	}

	public String getProcDefName() {
		return procDef.getName();
	}

	@JsonIgnore
	public ProcessInstance getProcIns() {
		return procIns;
	}

	public void setProcIns(ProcessInstance procIns) {
		this.procIns = procIns;
		if (procIns != null && procIns.getBusinessKey() != null){
			String[] ss = procIns.getBusinessKey().split(":");
			setBusinessTable(ss[0]);
			setBusinessId(ss[1]);
		}
	}

//	public String getProcExecUrl() {
//		return procExecUrl;
//	}
//
//	public void setProcExecUrl(String procExecUrl) {
//		this.procExecUrl = procExecUrl;
//	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	@JsonIgnore
	public HistoricTaskInstance getHistTask() {
		return histTask;
	}

	public void setHistTask(HistoricTaskInstance histTask) {
		this.histTask = histTask;
	}

	@JsonIgnore
	public HistoricActivityInstance getHistIns() {
		return histIns;
	}

	public void setHistIns(HistoricActivityInstance histIns) {
		this.histIns = histIns;
	}

	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
	public Date getBeginDate() {
		return beginDate;
	}

	public void setBeginDate(Date beginDate) {
		this.beginDate = beginDate;
	}

	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public String getComment() {
		return comment;
	}

	public void setComment(String comment) {
		this.comment = comment;
	}

	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}

	public String getProcDefId() {
		if (procDefId == null && task != null){
			procDefId = task.getProcessDefinitionId();
		}
		return procDefId;
	}

	public void setProcDefId(String procDefId) {
		this.procDefId = procDefId;
	}

	public String getProcInsId() {
		if (procInsId == null && task != null){
			procInsId = task.getProcessInstanceId();
		}
		return procInsId;
	}

	public void setProcInsId(String procInsId) {
		this.procInsId = procInsId;
	}

	public String getBusinessId() {
		return businessId;
	}

	public void setBusinessId(String businessId) {
		this.businessId = businessId;
	}

	public String getBusinessTable() {
		return businessTable;
	}

	public void setBusinessTable(String businessTable) {
		this.businessTable = businessTable;
	}

	public String getAssigneeName() {
		return assigneeName;
	}

	public void setAssigneeName(String assigneeName) {
		this.assigneeName = assigneeName;
	}

	public String getAssignee() {
		if (assignee == null && task != null){
			assignee = task.getAssignee();
		}
		return assignee;
	}

	public void setAssignee(String assignee) {
		this.assignee = assignee;
	}

	public List<Act> getList() {
		return list;
	}

	public void setList(List<Act> list) {
		this.list = list;
	}

	public Variable getVars() {
		return vars;
	}

	public void setVars(Variable vars) {
		this.vars = vars;
	}

	/**
	 * 通过Map设置流程变量值
	 * @param map
	 */
	public void setVars(Map<String, Object> map) {
		this.vars = new Variable(map);
	}

//	public Variable getTaskVars() {
//		return taskVars;
//	}
//
//	public void setTaskVars(Variable taskVars) {
//		this.taskVars = taskVars;
//	}
//
//	/**
//	 * 通过Map设置流程任务变量值
//	 * @param map
//	 */
//	public void setTaskVars(Map<String, Object> map) {
//		this.taskVars = new Variable(map);
//	}

	/**
	 * 获取流程定义KEY
	 * @return
	 */
	public String getProcDefKey() {
		if (StringUtils.isBlank(procDefKey) && StringUtils.isNotBlank(procDefId)){
			procDefKey = StringUtils.split(procDefId, ":")[0];
		}
		return procDefKey;
	}

	public void setProcDefKey(String procDefKey) {
		this.procDefKey = procDefKey;
	}

	/**
	 * 获取过去的任务历时
	 * @return
	 */
	public String getDurationTime(){
		if (histIns!=null && histIns.getDurationInMillis() != null){
			return TimeUtils.toTimeString(histIns.getDurationInMillis());
		}
		return "";
	}

	/**
	 * 是否是一个待办任务
	 * @return
	 */
	public boolean isTodoTask(){
		return "todo".equals(status) || "claim".equals(status);
	}

	/**
	 * 是否是已完成任务
	 * @return
	 */
	public boolean isFinishTask(){
		return "finish".equals(status) || StringUtils.isBlank(taskId);
	}

	@Override
	public void preInsert() {

	}

	@Override
	public void preUpdate() {

	}

}


text:
<?php

namespace FoF\Upload\Templates;

class ImageTemplate extends AbstractTextFormatterTemplate
{
    /**
     * @var string
     */
    protected $tag = 'image';

    /**
     * {@inheritdoc}
     */
    public function name(): string
    {
        return $this->trans('fof-upload.admin.templates.image');
    }

    /**
     * {@inheritdoc}
     */
    public function description(): string
    {
        return $this->trans('fof-upload.admin.templates.image_description');
    }

    /**
     * {@inheritdoc}
     */
    public function template(): string
    {
        return $this->getView('fof-upload.templates::image');
    }

    /**
     * {@inheritdoc}
     */
    public function bbcode(): string
    {
        return '[upl-image uuid={IDENTIFIER} size={SIMPLETEXT2} url={URL}]{SIMPLETEXT1}[/upl-image]';
    }
}


text:
package io.crate.metadata.information;

import io.crate.metadata.table.SchemaInfo;
import io.crate.operation.reference.information.InformationDocLevelReferenceResolver;
import org.elasticsearch.common.inject.AbstractModule;
import org.elasticsearch.common.inject.multibindings.MapBinder;

public class MetaDataInformationModule extends AbstractModule {

    protected MapBinder<String, SchemaInfo> schemaBinder;

    @Override
    protected void configure() {
        schemaBinder = MapBinder.newMapBinder(binder(), String.class, SchemaInfo.class);
        schemaBinder.addBinding(InformationSchemaInfo.NAME).to(InformationSchemaInfo.class).asEagerSingleton();

        bind(InformationDocLevelReferenceResolver.class).asEagerSingleton();
    }
}