text:
package org.apache.commons.exec;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * The main abstraction to start an external process.
 *
 * The interface allows to
 *

 *
set a current working directory for the subprocess

 *
provide a set of environment variables passed to the subprocess

 *
capture the subprocess output of stdout and stderr using an ExecuteStreamHandler

 *
kill long-running processes using an ExecuteWatchdog

 *
define a set of expected exit values

 *
terminate any started processes when the main process is terminating using a ProcessDestroyer

 *

 *
 * The following example shows the basic usage:
 *
 *

 * Executor exec = new DefaultExecutor();
 * CommandLine cl = new CommandLine("ls -l");
 * int exitvalue = exec.execute(cl);
 *

 */

public interface Executor {

    /** Invalid exit code. */
    int INVALID_EXITVALUE = 0xdeadbeef;

    /**
     * Define the exitValue of the process to be considered
     * successful. If a different exit value is returned by
     * the process then {@link org.apache.commons.exec.Executor#execute(CommandLine)}
     * will throw an {@link org.apache.commons.exec.ExecuteException}
     *
     * @param value the exit code representing successful execution
     */
    void setExitValue(final int value);

    /**
     * Define a list of exitValue of the process to be considered
     * successful. The caller can pass one of the following values
     *

     *
an array of exit values to be considered successful

     *
an empty array for auto-detect of successful exit codes relying on {@link org.apache.commons.exec.Executor#isFailure(int)}

     *
null to indicate to skip checking of exit codes

     *

     *
     * If an undefined exit value is returned by the process then
     * {@link org.apache.commons.exec.Executor#execute(CommandLine)}  will
     * throw an {@link org.apache.commons.exec.ExecuteException}.
     *
     * @param values a list of the exit codes
     */
    void setExitValues(final int[] values);

    /**
     * Checks whether exitValue signals a failure. If no
     * exit values are set than the default conventions of the OS is
     * used. e.g. most OS regard an exit code of '0' as successful
     * execution and everything else as failure.
     *
     * @param exitValue the exit value (return code) to be checked
     * @return true if exitValue signals a failure
     */
    boolean isFailure(final int exitValue);

    /**
     * Get the StreamHandler used for providing input and
     * retrieving the output.
     *
     * @return the StreamHandler
     */
    ExecuteStreamHandler getStreamHandler();

    /**
     * Set a custom the StreamHandler used for providing
     * input and retrieving the output. If you don't provide
     * a proper stream handler the executed process might block
     * when writing to stdout and/or stderr (see
     * {@link java.lang.Process Process}).
     *
     * @param streamHandler the stream handler
     */
    void setStreamHandler(ExecuteStreamHandler streamHandler);

    /**
     * Get the watchdog used to kill of processes running,
     * typically, too long time.
     *
     * @return the watchdog
     */
    ExecuteWatchdog getWatchdog();

    /**
     * Set the watchdog used to kill of processes running,
     * typically, too long time.
     *
     * @param watchDog the watchdog
     */
    void setWatchdog(ExecuteWatchdog watchDog);

    /**
     * Set the handler for cleanup of started processes if the main process
     * is going to terminate.
     *
     * @return the ProcessDestroyer
     */
    ProcessDestroyer getProcessDestroyer();

    /**
     * Get the handler for cleanup of started processes if the main process
     * is going to terminate.
     *
     * @param processDestroyer the ProcessDestroyer
     */
    void setProcessDestroyer(ProcessDestroyer processDestroyer);

    /**
     * Get the working directory of the created process.
     *
     * @return the working directory
     */
    File getWorkingDirectory();

    /**
     * Set the working directory of the created process. The
     * working directory must exist when you start the process.
     *
     * @param dir the working directory
     */
    void setWorkingDirectory(File dir);

    /**
     * Methods for starting synchronous execution. The child process inherits
     * all environment variables of the parent process.
     *
     * @param command the command to execute
     * @return process exit value
     * @throws ExecuteException execution of subprocess failed or the
     *          subprocess returned a exit value indicating a failure
     *          {@link Executor#setExitValue(int)}.
     */
    int execute(CommandLine command)
        throws ExecuteException, IOException;

    /**
     * Methods for starting synchronous execution.
     *
     * @param command the command to execute
     * @param environment The environment for the new process. If null, the
     *          environment of the current process is used.
     * @return process exit value
     * @throws ExecuteException execution of subprocess failed or the
     *          subprocess returned a exit value indicating a failure
     *          {@link Executor#setExitValue(int)}.
     */
    int execute(CommandLine command, Map environment)
        throws ExecuteException, IOException;

    /**
     * Methods for starting asynchronous execution. The child process inherits
     * all environment variables of the parent process. Result provided to
     * callback handler.
     *
     * @param command the command to execute
     * @param handler capture process termination and exit code
     * @throws ExecuteException execution of subprocess failed
     */
    void execute(CommandLine command, ExecuteResultHandler handler)
        throws ExecuteException, IOException;

    /**
     * Methods for starting asynchronous execution. The child process inherits
     * all environment variables of the parent process. Result provided to
     * callback handler.
     *
     * @param command the command to execute
     * @param environment The environment for the new process. If null, the
     *          environment of the current process is used.
     * @param handler capture process termination and exit code
     * @throws ExecuteException execution of subprocess failed
     */
    void execute(CommandLine command, Map environment, ExecuteResultHandler handler)
        throws ExecuteException, IOException;
}


text:
package com.sylvanaar.idea.Lua.intentions.control;

import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.IncorrectOperationException;
import com.sylvanaar.idea.Lua.intentions.LuaIntentionsBundle;
import com.sylvanaar.idea.Lua.intentions.base.IntentionUtils;
import com.sylvanaar.idea.Lua.intentions.base.MutablyNamedIntention;
import com.sylvanaar.idea.Lua.intentions.base.PsiElementPredicate;
import com.sylvanaar.idea.Lua.intentions.utils.ComparisonUtils;
import com.sylvanaar.idea.Lua.lang.psi.expressions.LuaBinaryExpression;
import com.sylvanaar.idea.Lua.lang.psi.expressions.LuaExpression;
import org.jetbrains.annotations.NotNull;

public class FlipComparisonIntention extends MutablyNamedIntention {
  protected String getTextForElement(PsiElement element) {
    final LuaBinaryExpression binaryExpression =
        (LuaBinaryExpression) element;
    final IElementType tokenType = binaryExpression.getOperationTokenType();
    final String comparison = ComparisonUtils.getStringForComparison(tokenType);
    final String flippedComparison = ComparisonUtils.getFlippedComparison(tokenType);

    return LuaIntentionsBundle.message("flip.comparison.intention.name", comparison, flippedComparison);
  }

  @NotNull
  public PsiElementPredicate getElementPredicate() {
    return new ComparisonPredicate();
  }

  public void processIntention(@NotNull PsiElement element)
      throws IncorrectOperationException {
    final LuaBinaryExpression exp =
        (LuaBinaryExpression) element;
    final IElementType tokenType = exp.getOperationTokenType();

    final LuaExpression lhs = exp.getLeftOperand();
    final String lhsText = lhs.getText();

    final LuaExpression rhs = exp.getRightOperand();
    final String rhsText = rhs.getText();

    final String flippedComparison = ComparisonUtils.getFlippedComparison(tokenType);

    final String newExpression =
        rhsText + flippedComparison + lhsText;
    IntentionUtils.replaceExpression(newExpression, exp);
  }

}

redpajama_set_name: RedPajamaGithub


text:
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using PictureStorage.SQL.Contexts;
using System;

namespace PictureStorage.SQL.Migrations
{
    [DbContext(typeof(PictureContext))]
    partial class PictureContextModelSnapshot : ModelSnapshot
    {
        protected override void BuildModel(ModelBuilder modelBuilder)
        {
#pragma warning disable 612, 618
            modelBuilder
                .HasAnnotation("ProductVersion", "2.0.0-rtm-26452")
                .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

            modelBuilder.Entity("PictureStorage.Entities.Picture", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<byte[]>("Data");

                    b.Property<string>("FileName");

                    b.Property<Guid>("ProjectId");

                    b.HasKey("Id");

                    b.ToTable("_pictures");
                });
#pragma warning restore 612, 618
        }
    }
}


text:
package com.box.boxjavalibv2.dao;

import java.util.Map;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Enterprise.
 */
@SuppressWarnings("unused")
public class BoxEnterprise extends BoxObject {

    public static final String FIELD_NAME = "name";

    public BoxEnterprise() {
    }

    /**
     * Copy constructor, this does deep copy for all the fields.
     *
     * @param obj
     */
    public BoxEnterprise(BoxEnterprise obj) {
        super(obj);
    }

    /**
     * Instantiate the object from a map. Each entry in the map reflects to a field.
     *
     * @param map
     */
    public BoxEnterprise(Map<String, Object> map) {
        super(map);
    }

    private String name;

    /**
     * Get name of user's enterprise.
     *
     * @return name
     */
    @JsonProperty(FIELD_NAME)
    public String getName() {
        return (String) getValue(FIELD_NAME);
    }

    /**
     * Setter. This is only used by {@see Jackson JSON processer}
     *
     * @param name
     *            name
     */

    @JsonProperty(FIELD_NAME)
    private void setName(String name) {
        put(FIELD_NAME, name);
    }

    public BoxEnterprise(IBoxParcelWrapper in) {
        super(in);
    }
}


text:
<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "image".
 *
 * @property integer $id
 * @property string $path
 *
 * @property Product[] $products
 */
class Image extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'image';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['path'], 'required'],
            [['path'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'path' => 'Path',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProducts()
    {
        return $this->hasMany(Product::className(), ['image_id' => 'id']);
    }
}


text:
A bunch of sorting algorithms
Copyright (c) Michał Jastrząb


text:
<?php

require_once('pinjector/DocParser.php');
require_once('pinjector/Pointcut.php');

/**
 *
 * @author Tobias Sarnowski
 */
class RequiresPermissionsPointcut implements Pointcut {

    public function matchesMethod(ReflectionMethod &$method) {
        $value = DocParser::parseSetting($method->getDocComment(), 'requiresPermissions');
        if (is_null($value)) {
            return false;
        } else {
            if (trim($value) == '') {
                throw new SecurityConfigurationException(
                    "@requiresPermissions without permission hints found in method ".
                            $method->getDeclaringClass()->getName().
                            "->".
                            $method->getName()
                );
            } else {
                return true;
            }
        }
    }
}


text:
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.application.options.schemes;

import com.intellij.icons.AllIcons;
import com.intellij.ide.HelpTooltip;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.actions.NonTrivialActionGroup;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.options.Scheme;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.BalloonBuilder;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.ListPopup;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.NlsContexts;
import com.intellij.ui.JBColor;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.util.ui.JBDimension;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.util.Collection;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

/**
 * Base panel for schemes combo box and related actions. When settings change, {@link #updateOnCurrentSettingsChange()} method must be
 * called to reflect the change in schemes panel. The method should be added to settings model listener.
 *
 * @param <T> The actual scheme type.
 * @see AbstractSchemeActions
 * @see SchemesModel
 */
public abstract class AbstractSchemesPanel<T extends Scheme, InfoComponent extends JComponent> extends JPanel {

  private EditableSchemesCombo<T> mySchemesCombo;
  private AbstractSchemeActions<T> myActions;
  private JComponent myToolbar;
  InfoComponent myInfoComponent;

  // region Colors (probably should be standard for platform UI)

  private static final Color HINT_FOREGROUND = JBColor.GRAY;
  @SuppressWarnings("UseJBColor")
  private static final Color ERROR_MESSAGE_FOREGROUND = Color.RED;

  protected static final int DEFAULT_VGAP = 8;
  private JSeparator mySettingsPanelSeparator;

  // endregion

  AbstractSchemesPanel() {
    this(DEFAULT_VGAP);
  }

  AbstractSchemesPanel(int vGap) {
    setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
    createUIComponents(vGap);
  }

  private void createUIComponents(int vGap) {
    JPanel controlsPanel = createControlsPanel();
    add(controlsPanel);

    JComponent topComponent = createTopComponent();
    if (topComponent != null) {
      add(topComponent);
    }
    JComponent bottomComponent = createBottomComponent();
    if (bottomComponent != null) {
      add(bottomComponent);
    }
    mySettingsPanelSeparator = new JSeparator();
    add(mySettingsPanelSeparator);
    if (vGap > 0) {
      add(Box.createVerticalGlue());
      add(Box.createRigidArea(new JBDimension(0, vGap)));
    }
  }

  public void setSeparatorVisible(boolean visible) {
    mySettingsPanelSeparator.setVisible(visible);
  }

  protected JComponent createTopComponent() {
    return null;
  }

  @Nullable
  protected JComponent createBottomComponent() {
    return null;
  }

  @NotNull
  private JPanel createControlsPanel() {
    JPanel controlsPanel = new JPanel();
    controlsPanel.setLayout(new BoxLayout(controlsPanel, BoxLayout.LINE_AXIS));
    String label = getComboBoxLabel();
    if (label != null) {
      controlsPanel.add(new JLabel(label));
      controlsPanel.add(Box.createRigidArea(new JBDimension(10, 0)));
    }
    myActions = createSchemeActions();
    mySchemesCombo = new EditableSchemesCombo<>(this);
    controlsPanel.add(mySchemesCombo.getComponent());
    ActionToolbar toolbar = createToolbar();
    toolbar.setTargetComponent(mySchemesCombo.getComponent());
    myToolbar = toolbar.getComponent();
    controlsPanel.add(Box.createRigidArea(new JBDimension(4, 0)));
    controlsPanel.add(myToolbar);
    controlsPanel.add(Box.createRigidArea(new JBDimension(9, 0)));
    myInfoComponent = createInfoComponent();
    controlsPanel.add(myInfoComponent);
    controlsPanel.add(Box.createHorizontalGlue());

    mySchemesCombo.getComponent().setMaximumSize(mySchemesCombo.getComponent().getPreferredSize());

    int height = mySchemesCombo.getComponent().getPreferredSize().height;
    controlsPanel.setMaximumSize(new Dimension(controlsPanel.getMaximumSize().width, height));
    return controlsPanel;
  }

  @NotNull
  private ActionToolbar createToolbar() {
    DefaultActionGroup group = new DefaultActionGroup();
    group.add(new ShowSchemesActionsListAction(myActions));
    ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar("SchemesPanelToolbar", group, true);
    toolbar.setReservePlaceAutoPopupIcon(false);
    toolbar.setLayoutPolicy(ActionToolbar.NOWRAP_LAYOUT_POLICY);
    JComponent toolbarComponent = toolbar.getComponent();
    Dimension maxSize = toolbarComponent.getMaximumSize();
    toolbarComponent.setMaximumSize(JBUI.size(22, maxSize.height));
    toolbarComponent.setBorder(JBUI.Borders.empty(3));
    return toolbar;
  }

  public final JComponent getToolbar() {
    return myToolbar;
  }

  /**
   * Creates schemes actions. Used when panel UI components are created.
   * @return Scheme actions associated with the panel.
   * @see AbstractSchemeActions
   */
  @NotNull
  protected abstract AbstractSchemeActions<T> createSchemeActions();

  public final T getSelectedScheme() {
    return mySchemesCombo.getSelectedScheme();
  }

  public void selectScheme(@Nullable T scheme) {
    mySchemesCombo.selectScheme(scheme);
  }

  public final void resetSchemes(@NotNull Collection<? extends T> schemes) {
    mySchemesCombo.resetSchemes(schemes);
  }

  public void disposeUIResources() {
    removeAll();
  }

  final void editCurrentSchemeName(@NotNull BiConsumer<? super T, ? super String> newSchemeNameConsumer) {
    T currentScheme = getSelectedScheme();
    if (currentScheme != null) {
      String currentName = currentScheme.getName();
      mySchemesCombo.startEdit(
        currentName,
        getModel().isProjectScheme(currentScheme),
        newName -> {
          if (!newName.equals(currentName)) {
            newSchemeNameConsumer.accept(currentScheme, newName);
          }
        });
    }
  }

  public final void editNewSchemeName(@NotNull String preferredName, boolean isProjectScheme, @NotNull Consumer<? super String> nameConsumer) {
    String name =
      SchemeNameGenerator.getUniqueName(preferredName, schemeName -> getModel().containsScheme(schemeName, isProjectScheme));
    mySchemesCombo.startEdit(name, isProjectScheme, nameConsumer);
  }

  public final void cancelEdit() {
    mySchemesCombo.cancelEdit();
  }

  public final void showInfo(@NotNull @Nls String message, @NotNull MessageType messageType) {
    myToolbar.setVisible(false);
    showMessage(message, messageType);
  }

  protected abstract void showMessage(@NlsContexts.Label @Nullable String message, @NotNull MessageType messageType);

  final void clearInfo() {
    myToolbar.setVisible(true);
    clearMessage();
  }

  protected abstract void clearMessage();

  @NotNull
  public final AbstractSchemeActions<T> getActions() {
    return myActions;
  }

  @NotNull
  protected abstract InfoComponent createInfoComponent();

  /**
   * @return a string label to place before the combobox or {@code null} if it is not needed
   */
  @Nullable
  protected @NlsContexts.Label String getComboBoxLabel() {
    return getSchemeTypeName() + ":";
  }

  @NotNull
  @Nls
  protected String getSchemeTypeName() {
    return ApplicationBundle.message("editbox.scheme.type.name");
  }

  /**
   * @return Schemes model implementation.
   * @see SchemesModel
   */
  @NotNull
  public abstract SchemesModel<T> getModel();

  /**
   * Must be called when any settings are changed.
   */
  public final void updateOnCurrentSettingsChange() {
    mySchemesCombo.updateSelected();
  }

  /**
   * Returns an indent to calculate a left margin for the scheme name in the combo box.
   * By default, all names are aligned to the left.
   *
   * @param scheme the scheme to calculate its indent
   * @return an indent that shows a nesting level for the specified scheme
   */
  protected int getIndent(@NotNull T scheme) {
    return 0;
  }

  /**
   * @return True if the panel supports project-level schemes along with IDE ones. In this case there will be
   *         additional "Copy to Project" and "Copy to IDE" actions for IDE and project schemes respectively and Project/IDE schemes
   *         separators.
   */
  protected abstract boolean supportsProjectSchemes();

  protected abstract boolean highlightNonDefaultSchemes();

  protected boolean hideDeleteActionIfUnavailable() {
    return true;
  }

  public abstract boolean useBoldForNonRemovableSchemes();

  public void showStatus(@NotNull @NlsContexts.PopupContent String message, @NotNull MessageType messageType) {
    BalloonBuilder balloonBuilder = JBPopupFactory.getInstance()
      .createHtmlTextBalloonBuilder(message, messageType.getDefaultIcon(),
                                    messageType.getPopupBackground(), null);
    balloonBuilder.setFadeoutTime(5000);
    final Balloon balloon = balloonBuilder.createBalloon();
    Point pointOnComponent = new Point(myToolbar.getWidth() / 4, myToolbar.getHeight() / 4);
    balloon.show(new RelativePoint(myToolbar, pointOnComponent), Balloon.Position.above);
    Disposer.register(ApplicationManager.getApplication(), balloon);
  }

  private static class ShowSchemesActionsListAction extends NonTrivialActionGroup implements DumbAware {
    private final AbstractSchemeActions<?> mySchemeActions;

    ShowSchemesActionsListAction(AbstractSchemeActions<?> schemeActions) {
      setPopup(true);
      mySchemeActions = schemeActions;
      getTemplatePresentation().setIcon(AllIcons.General.GearPlain);
      getTemplatePresentation().setText(IdeBundle.messagePointer("action.presentation.AbstractSchemesPanel.text"));
      getTemplatePresentation().setDescription(IdeBundle.messagePointer("action.presentation.AbstractSchemesPanel.description"));
      getTemplatePresentation().setPerformGroup(true);
    }

    @Override
    public AnAction @NotNull [] getChildren(@Nullable AnActionEvent e) {
      return mySchemeActions.getActions().toArray(EMPTY_ARRAY);
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
      ListPopup popup = JBPopupFactory.getInstance().
        createActionGroupPopup(null, this, e.getDataContext(), true, null, Integer.MAX_VALUE);

      HelpTooltip.setMasterPopup(e.getInputEvent().getComponent(), popup);
      Component component = e.getInputEvent().getComponent();
      if (component instanceof ActionButtonComponent) {
        popup.showUnderneathOf(component);
      }
      else {
        popup.showInCenterOf(component);
      }
    }
  }

  protected static void showMessage(@NlsContexts.Label @Nullable String message,
                                    @NotNull MessageType messageType,
                                    @NotNull JLabel infoComponent) {
    infoComponent.setText(message);
    Color foreground =
      messageType == MessageType.INFO ? HINT_FOREGROUND :
      messageType == MessageType.ERROR ? ERROR_MESSAGE_FOREGROUND :
      messageType.getTitleForeground();
    infoComponent.setForeground(foreground);
  }
}


text:
package com.xeiam.xchange.cryptsy.service.polling;

import java.io.IOException;
import java.util.Map;

import com.xeiam.xchange.Exchange;
import com.xeiam.xchange.cryptsy.CryptsyAdapters;
import com.xeiam.xchange.cryptsy.dto.marketdata.CryptsyCurrencyPairsReturn;
import com.xeiam.xchange.cryptsy.dto.marketdata.CryptsyPublicMarketData;
import com.xeiam.xchange.cryptsy.dto.marketdata.CryptsyPublicOrderbook;
import com.xeiam.xchange.exceptions.ExchangeException;

public class CryptsyPublicMarketDataServiceRaw extends CryptsyBasePollingService {

  /**
   * Constructor
   *
   * @param exchange
   */
  public CryptsyPublicMarketDataServiceRaw(Exchange exchange) {

    super(exchange);
  }

  public Map<Integer, CryptsyPublicMarketData> getAllCryptsyMarketData() throws IOException, ExchangeException {

    return CryptsyAdapters.adaptPublicMarketDataMap(checkResult(cryptsy.getAllMarketData()).getReturnValue());
  }

  public Map<Integer, CryptsyPublicMarketData> getCryptsyMarketData(int marketId) throws IOException, ExchangeException {

    return CryptsyAdapters.adaptPublicMarketDataMap(checkResult(cryptsy.getMarketData(marketId)).getReturnValue());
  }

  public Map<Integer, CryptsyPublicOrderbook> getAllCryptsyOrderBooks() throws IOException, ExchangeException {

    return CryptsyAdapters.adaptPublicOrderBookMap(checkResult(cryptsy.getAllOrderbookData()).getReturnValue());
  }

  public Map<Integer, CryptsyPublicOrderbook> getCryptsyOrderBook(int marketId) throws IOException, ExchangeException {

    return CryptsyAdapters.adaptPublicOrderBookMap(checkResult(cryptsy.getOrderbookData(marketId)).getReturnValue());
  }

  public CryptsyCurrencyPairsReturn getCryptsyCurrencyPairs() throws IOException {

    return checkResult(cryptsy.getCryptsyCurrencyPairs());
  }
}


text:
import DS from 'ember-data';
import Ember from 'ember';

const { attr, belongsTo } = DS;
const { computed } = Ember;

export default DS.Model.extend({
  url: attr('string'),
  committedAt: attr('date'),
  gist: belongsTo('gist'),

  shortId: computed('id', function() {
    return (this.get('id')||'').substring(0,7);
  })
});


text:
var gutil = require("gulp-util");
var path = require("path");
var through = require("through2");

var name = "gulp-rev-manifest-combine";

/**
 * Creates a master manifest file from several manifests.
 *
 * @param filename The filename to write to.
 * @param options Plugin options
 * @param options.base Base path to prefix to asset paths.
 *
 * @returns A readable/writable stream
 */
module.exports = function(filename, options) {
  if (!filename) {
    throw new gutil.PluginError(name, "missing filename");
  }

  options = options || {};
  options.base = options.base || "";

  var firstFile = null;
  var manifest = {};

  function stream(file, enc, cb) {
    if (file.isNull()) {
      this.push(file);

    } else if (file.isStream()) {
      this.emit("error", new gutil.PluginError(name, "streaming is not supported"));

    } else {
      if (!firstFile) {
        firstFile = file;
      }

      var content;
      try {
        content = JSON.parse(file.contents.toString("utf8"));
      } catch(error) {
        content = {};
        gutil.log("Skipped due to errors: " + file.path);
      }

      // Prefix manifest entries with the proper base paths
      var base = path.join(options.base, path.dirname(file.relative));
      for (var prop in content) {
        manifest[path.join(base, prop)] = path.join(base, content[prop]);
      }
    }

    cb();
  }

  function end(cb) {
    if (firstFile) {
      this.push(new gutil.File({
        cwd: firstFile.cwd,
        base: firstFile.base,
        path: path.join(firstFile.base, filename),
        contents: new Buffer(JSON.stringify(manifest, null, options.space))
      }));
    }

    cb();
  }

  return through.obj(stream, end);
};


text:
// Copyright 2015 Sascha-Christian Hensel
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System.Web.Mvc;
using System.Web.Routing;

namespace ezNReporting.Web
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}


text:
package com.system.dormitory.dormitory_system_android;

import android.app.Application;
import android.test.ApplicationTestCase;

/**
 * Testing Fundamentals
 */
public class ApplicationTest extends ApplicationTestCase<Application> {
    public ApplicationTest() {
        super(Application.class);
    }
}


text:
using System;
using System.Threading.Tasks;
using ChatterBox.Core.Infrastructure;
using ChatterBox.MessageContracts.Owners.Commands;
using Nimbus.Handlers;

namespace ChatterBox.ChatServer.Handlers.Owners
{
    public class KickUserCommandHandler : IHandleCommand<KickUserCommand>
    {
        private readonly IUnitOfWork _unitOfWork;

        public KickUserCommandHandler(IUnitOfWork unitOfWork)
        {
            if (unitOfWork == null)
                throw new ArgumentNullException("unitOfWork");

            _unitOfWork = unitOfWork;
        }

        public Task Handle(KickUserCommand command)
        {
            throw new NotImplementedException();
        }
    }
}


text:
using IdParser.Attributes;

namespace IdParser.Parsers.Id
{
    [Parser("DDI")]
    public class Under19UntilParser : AbstractParser
    {
        public Under19UntilParser(IdentificationCard idCard, Version version, Country country) : base(idCard, version, country)
        {
        }

        public override void ParseAndSet(string input)
        {
            if (DateHasNoValue(input) || Version < Version.Aamva2000)
            {
                return;
            }

            IdCard.Under19Until = ParseDate(input);
        }
    }
}


text:
<?php

	require_once 'conexion.php';

  $alumnId = $_GET['alumnId'];
  $eventId = $_GET['eventId'];

  $sqlQuery = "CALL pa_buscar_categoria_x_peso_x_alumno" . "($eventId,'$alumnId')";

  $result = $conexion->query($sqlQuery);

  if(!$result)die('Sql query failed' . $conexion->error);

  $category = array();

  while($data = mysqli_fetch_assoc($result)) {
  	$category[] = $data;
  }

  echo json_encode($category);
?>


text:
<?php

namespace Ens\JobeetBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Category
 */
class Category
{
    /**
     * @var integer
     */
    private $id;

    /**
     * @var string
     */
    private $name;

    /**
     * @var \Doctrine\Common\Collections\Collection
     */
    private $jobs;

    /**
     * @var \Doctrine\Common\Collections\Collection
     */
    private $category_affiliates;

    private $active_jobs;

    private $more_jobs;

    /**
    * @var string $slug
    */
    private $slug;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->jobs = new \Doctrine\Common\Collections\ArrayCollection();
        $this->category_affiliates = new \Doctrine\Common\Collections\ArrayCollection();
    }

    public function __toString()
    {
        return $this->getName();
    }
    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    public function setMoreJobs($jobs)
    {
        $this->more_jobs = $jobs >=  0 ? $jobs : 0;
    }

    public function getMoreJobs()
    {
        return $this->more_jobs;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Category
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Add jobs
     *
     * @param \Ens\JobeetBundle\Entity\Job $jobs
     * @return Category
     */
    public function addJob(\Ens\JobeetBundle\Entity\Job $jobs)
    {
        $this->jobs[] = $jobs;

        return $this;
    }

    /**
     * Remove jobs
     *
     * @param \Ens\JobeetBundle\Entity\Job $jobs
     */
    public function removeJob(\Ens\JobeetBundle\Entity\Job $jobs)
    {
        $this->jobs->removeElement($jobs);
    }

    /**
     * Get jobs
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getJobs()
    {
        return $this->jobs;
    }

    /**
     * Add category_affiliates
     *
     * @param \Ens\JobeetBundle\Entity\CategoryAffiliate $categoryAffiliates
     * @return Category
     */
    public function addCategoryAffiliate(\Ens\JobeetBundle\Entity\CategoryAffiliate $categoryAffiliates)
    {
        $this->category_affiliates[] = $categoryAffiliates;

        return $this;
    }

    /**
     * Remove category_affiliates
     *
     * @param \Ens\JobeetBundle\Entity\CategoryAffiliate $categoryAffiliates
     */
    public function removeCategoryAffiliate(\Ens\JobeetBundle\Entity\CategoryAffiliate $categoryAffiliates)
    {
        $this->category_affiliates->removeElement($categoryAffiliates);
    }

    /**
     * Get category_affiliates
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getCategoryAffiliates()
    {
        return $this->category_affiliates;
    }

    public function setActiveJobs($jobs)
    {
        $this->active_jobs = $jobs;
    }

    public function getActiveJobs()
    {
        return $this->active_jobs;
    }

    /**
    * Set slug
    *
    * @param string $slug
    */
    public function setSlug($slug)
    {
        $this->slug = $slug;
    }
    /**
    * Get slug
    *
    * @return string
    */
    public function getSlug()
    {
        return $this->slug;
    }
    /**
    * @ORM\prePersist
    */
    public function setSlugValue()
    {
        // Add your code here
        $this->slug = $this->getName();
    }

    /*public function getSlug()
    {
        return Jobeet::slugify($this->getName());
    }*/
}


text:
README
======

This is a quick-and-dirty Rails app built to demonstrate how some of the same Ruby programming techniques we've learned would be used in a Rails web application.

Most of this app was built automatically using a tool called Rails Scaffolding, which gives you the basics for an object in your system: it creates the database table, Rails Model (e.g., my_model.rb), and the various HTML pages you'd want for listing, adding, editing and removing instances of this object from your database. This is very helpful - this (admittedly very basic) application was built in about 30 minutes... it took longer to remember the proper CSS for a navbar than it did to get Student objects in and out of the database!

A proper course on Rails will go into much more detail than we can here. This is just meant to give you a taste of the power of the Rails framework and to demonstrate how the very same Ruby coding techniques you're learning in class can be applied to a modern web application.

In-class demo of Rails Scaffolds
--------------------------------

In class, it may be helpful to demonstrate how these "scaffold" pages were generated. We can use the `Homework` class for this:

```
$ rails generate scaffold homework name points_possible:integer
$ rake db:migrate
```


text:
import { Component } from '@angular/core';

import { PropInfo } from './prop-info';

@Component({
  selector: 'prop-info',
  templateUrl: './prop-info.component.html'
  //styleUrls: ['./info.component.css']
})

export class PropInfoComponent {
  model = new PropInfo('', '', '', '', '');
}


text:
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('bs-progress', 'Integration | Component | bs-progress', {
  integration: true
});

test('bs-progress has correct markup', function(assert) {
  // Template block usage:
  this.render(hbs`
    {{#bs-progress as |p|}}
      template block text
    {{/bs-progress}}
  `);

  assert.equal(this.$().text().trim(), 'template block text', 'Shows block content');
  assert.equal(this.$('div.progress').length, 1, 'Has progress class');
});

test('Progress bar has correct width according to value, minValue and maxValue', function(assert) {

  let baseSize = 500;
  // some test data
  let testData = [
    {
      value: 60,
      minValue: 0,
      maxValue: 100
    },
    {
      value: 3,
      minValue: 0,
      maxValue: 10
    },
    {
      value: 6,
      minValue: 5,
      maxValue: 10
    }
  ];

  testData.forEach((data) => {
    this.render(hbs`
      <div style="width: 500px">
        {{#bs-progress as |p|}}
          {{p.bar value=value minValue=minValue maxValue=maxValue}}
        {{/bs-progress}}
      </div>
    `);

    let { value } = data;
    let minValue = data.minValue || 0;
    let maxValue = data.maxValue || 100;
    let expectedWidth = (value - minValue) / (maxValue - minValue) * baseSize;

    this.setProperties(data);

    assert.equal(this.$('.progress-bar').width(), expectedWidth, 'Progress bar has expected width.');
  });

});

test('progress bar has invisible label for screen readers', function(assert) {
  this.render(hbs`
    {{#bs-progress as |p|}}
      {{p.bar value=5 maxValue=10}}
    {{/bs-progress}}
  `);

  assert.equal(this.$('.progress-bar .sr-only').html().trim(), '50%', 'Progress bar shows correct default label');

  this.render(hbs`
    {{#bs-progress as |p|}}
      {{#p.bar value=5 maxValue=10 as |percent|}}5 ({{percent}}%){{/p.bar}}
    {{/bs-progress}}
  `);

  assert.equal(this.$('.progress-bar .sr-only').html().trim(), '5 (50%)', 'Progress bar shows correct custom label');

});

test('progress bar can show label', function(assert) {
  this.render(hbs`
    {{#bs-progress as |p|}}
      {{p.bar value=5 maxValue=10 showLabel=true}}
    {{/bs-progress}}
  `);

  assert.equal(this.$('.progress-bar').html().trim(), '50%', 'Progress bar shows correct default label');

  this.render(hbs`
    {{#bs-progress as |p|}}
      {{#p.bar value=5 maxValue=10 showLabel=true as |percent|}}5 ({{percent}}%){{/p.bar}}
    {{/bs-progress}}
  `);

  assert.equal(this.$('.progress-bar').html().trim(), '5 (50%)', 'Progress bar shows correct custom label');

});

test('progress bar can round label\'s percent value', function(assert) {
  this.render(hbs`
    {{#bs-progress as |p|}}
      {{p.bar value=5 maxValue=6 roundDigits=2 showLabel=true}}
    {{/bs-progress}}
  `);

  assert.equal(this.$('.progress-bar').html().trim(), '83.33%', 'Progress bar shows correct default label');

});

test('progress bar supports type class', function(assert) {
  this.render(hbs`
    {{#bs-progress as |p|}}
      {{p.bar value=50 type="success"}}
    {{/bs-progress}}
  `);

  assert.ok(this.$('.progress-bar').hasClass('progress-bar-success'), 'Progress bar has type class');

});

test('progress bar supports striped style', function(assert) {
  this.render(hbs`
    {{#bs-progress as |p|}}
      {{p.bar value=50 type="success" striped=true}}
    {{/bs-progress}}
  `);

  assert.ok(this.$('.progress-bar').hasClass('progress-bar-striped'), 'Progress bar has type class');

});

test('progress bar supports animated stripes', function(assert) {
  this.render(hbs`
    {{#bs-progress as |p|}}
      {{p.bar value=50 type="success" striped=true animate=true}}
    {{/bs-progress}}
  `);

  assert.ok(this.$('.progress-bar').hasClass('progress-bar-striped'), 'Progress bar has type class');
  assert.ok(this.$('.progress-bar').hasClass('active'), 'Progress bar has active class');

});

test('progress bar supports stacked bars', function(assert) {
  this.render(hbs`
    {{#bs-progress as |p|}}
      {{p.bar value=50 type="success"}}
      {{p.bar value=30 type="info"}}
    {{/bs-progress}}
  `);

  assert.equal(this.$('.progress-bar').length, 2, 'Progress bar has two bars');

});


text:
import {Component, EventEmitter, Input, Output} from "@angular/core";
import {MatchesConstants} from "../../matches.constant.service";
import {AbstractControl, FormBuilder, FormGroup, Validators} from "@angular/forms";
import "rxjs/add/operator/startWith";
import "rxjs/add/operator/map";
import {NgbModal} from "@ng-bootstrap/ng-bootstrap";
import {MatchesDataStoreService} from "../../matches-data-store";
import {Subject} from "rxjs/Subject";
import {DefaultModal} from "../../../../../pages/ui/components/modals/default-modal/default-modal.component";
import {MatchesService} from "../../../../common/services/matches.service";
/*/!**
 * Created by HudaZulifqar on 6/27/2017.
 *!/*/
@Component({
  selector: 'submit-score-wickets',
  templateUrl: 'wickets.html',
  //styleUrls: ['../../../../theme/components/baCheckbox/baCheckbox.scss'],
  styleUrls: ['../submitScore.scss'],
})
export class SubmitScoreWicketComponent {
  @Output() notify_Extras: EventEmitter<any> = new EventEmitter<any>();
  @Input() innings: string;
  @Input() isFirstInnings: boolean = true;
  private ngUnsubscribe: Subject<void> = new Subject<void>();
  isSubmitted: boolean = false;
  public matchInfo: any;
  public fowResStatus: string;
  public wicketForm: FormGroup;
  public name: AbstractControl;
  public innings_id: AbstractControl;
  public game_id: AbstractControl;
  public team: AbstractControl;
  public fow1: AbstractControl;
  public fow2: AbstractControl;
  public fow3: AbstractControl;
  public fow4: AbstractControl;
  public fow5: AbstractControl;
  public fow6: AbstractControl;
  public fow7: AbstractControl;
  public fow8: AbstractControl;
  public fow9: AbstractControl;
  public fow10: AbstractControl;
  public fow11: AbstractControl;

  constructor(fb: FormBuilder,
              private matchesService: MatchesService,
              private matchesConstants: MatchesConstants,
              private matchesDataStoreService: MatchesDataStoreService,
              private modalService: NgbModal) {

    this.wicketForm = fb.group({
      'name': ['', Validators.compose([Validators.required, Validators.minLength(4), Validators.maxLength(3)])],
      'innings_id': ['', Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(1)])],
      'game_id': ['', Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(1)])],
      'team': ['', Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(1)])],
      'fow1': ['', Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(3), Validators.pattern('^(0|[1-9][0-9]*)')])],
      'fow2': ['', Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(3), Validators.pattern('^(0|[1-9][0-9]*)')])],
      'fow3': ['', Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(3), Validators.pattern('^(0|[1-9][0-9]*)')])],
      'fow4': ['', Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(3), Validators.pattern('^(0|[1-9][0-9]*)')])],
      'fow5': ['', Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(3), Validators.pattern('^(0|[1-9][0-9]*)')])],
      'fow6': ['', Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(3), Validators.pattern('^(0|[1-9][0-9]*)')])],
      'fow7': ['', Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(3), Validators.pattern('^(0|[1-9][0-9]*)')])],
      'fow8': ['', Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(3), Validators.pattern('^(0|[1-9][0-9]*)')])],
      'fow9': ['', Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(3), Validators.pattern('^(0|[1-9][0-9]*)')])],
      'fow10': ['', Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(3), Validators.pattern('^(0|[1-9][0-9]*)')])],
      'fow11': ['', Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(3), Validators.pattern('^(0|[1-9][0-9]*)')])],

    });

    this.name = this.wicketForm.controls['name'];
    this.innings_id = this.wicketForm.controls['innings_id'];
    this.game_id = this.wicketForm.controls['game_id'];
    this.team = this.wicketForm.controls['team'];
    this.fow1 = this.wicketForm.controls['fow1'];
    this.fow2 = this.wicketForm.controls['fow2'];
    this.fow3 = this.wicketForm.controls['fow3'];
    this.fow4 = this.wicketForm.controls['fow4'];
    this.fow5 = this.wicketForm.controls['fow5'];
    this.fow6 = this.wicketForm.controls['fow6'];
    this.fow7 = this.wicketForm.controls['fow7'];
    this.fow8 = this.wicketForm.controls['fow8'];
    this.fow9 = this.wicketForm.controls['fow9'];
    this.fow10 = this.wicketForm.controls['fow10'];
    this.fow11 = this.wicketForm.controls['fow11'];

  }

  batting_poistion = this.matchesConstants.getBattingPositions();

  childModalShow() {
    const activeModal = this.modalService.open(DefaultModal, {size: 'sm'});
    activeModal.componentInstance.modalHeader = 'wicket';
    activeModal.componentInstance.modalContent = `I am a child modal, opened from parent component!`;
    activeModal.componentInstance.name = 'Hello for you '!;
    activeModal.componentInstance.createConfirm = 'Yes';
    console.log(activeModal.componentInstance);

  }

  onSelectedWickets(type: any, value: any) {
    console.info("onSelectedWickets: Type:", type, 'Value: ', value)
    this.wicketForm.controls[type].setValue(value);
    this.isSubmitted = false;
    console.log('this.extrasDetails.controls ', this.wicketForm.value)
  }

  getMatchData() {
    let matchInfo$ = this.matchesDataStoreService.getMatchDetails();
    console.log("Match Info", matchInfo$)

    if (!this.matchesService.isEmpty(matchInfo$)) {
      this.wicketForm.controls['game_id'].setValue(matchInfo$[0].game_id);
      if (this.isFirstInnings) {
        this.wicketForm.controls['team'].setValue(matchInfo$[0].batting_first_id);
        this.wicketForm.controls['innings_id'].setValue('1');
      } else {
        this.wicketForm.controls['team'].setValue(matchInfo$[0].batting_second_id);
        this.wicketForm.controls['innings_id'].setValue('2');
      }
    }
  }

  submitWickets() {
    this.getMatchData();
    let fowValue = this.wicketForm.value;
    console.log("SubmitScoreWicketComponent :: Request", fowValue)
    this.matchesService.submit_score_fow_details(fowValue)
      .takeUntil(this.ngUnsubscribe)
      .subscribe(responce => this.fowResStatus = responce,
        (err) => console.error("Submitting Totals failed", err),
        () => this.notify_Extras.emit({
          "innings": this.innings,
          "component": 'wickets'
        }));
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }
}


text:
package org.apache.taverna.workbench.file.impl.menu;

import static org.apache.taverna.workbench.file.impl.menu.FileOpenMenuSection.FILE_OPEN_SECTION_URI;

import java.net.URI;

import javax.swing.Action;

import org.apache.taverna.ui.menu.AbstractMenuAction;
import org.apache.taverna.workbench.file.FileManager;
import org.apache.taverna.workbench.file.impl.actions.NewWorkflowAction;

public class FileNewMenuAction extends AbstractMenuAction {
	private static final URI FILE_NEW_URI = URI
			.create("http://taverna.sf.net/2008/t2workbench/menu#fileNew");
	private final FileManager fileManager;

	public FileNewMenuAction(FileManager fileManager) {
		super(FILE_OPEN_SECTION_URI, 10, FILE_NEW_URI);
		this.fileManager = fileManager;
	}

	@Override
	protected Action createAction() {
		return new NewWorkflowAction(fileManager);
	}
}


text:
package com.ev3.brick.device;

import java.io.IOException;
import java.net.URI;
import java.util.Queue;

import javax.annotation.PostConstruct;
import javax.websocket.ClientEndpoint;
import javax.websocket.ContainerProvider;
import javax.websocket.DeploymentException;
import javax.websocket.MessageHandler;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

@ClientEndpoint
public class BrickClientEndpoint {

    private static final String WS_HOST_EV3 = "ws://localhost:8081/ev3";

    private Session session;
    private Queue<String> commandQueue;

    @PostConstruct
    public void connectBrickEndpoint() {
        final WebSocketContainer webSocketContainer = ContainerProvider
                .getWebSocketContainer();

        try {
            webSocketContainer.connectToServer(this, URI.create(WS_HOST_EV3));
        } catch (DeploymentException | IOException e) {
            e.printStackTrace();
        }
    }

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
    }

    public void addMessageHandler(MessageHandler.Whole<String> handler) {
        this.session.addMessageHandler(handler);
    }

    public void sendCommand(String command) throws IOException {
        this.session.getBasicRemote().sendText(command);
    }
}


text:
garden
======

Incrementers and gaming experiments

 To play, go to http://purepandemonium.github.io/garden/


text:
Adeia::Engine.routes.draw do

  resources :permissions, except: :show

  resources :tokens, except: :show

  resources :groups, except: :show

  resources :group_users, except: :show

end


text:
/**
 * Extended Memory interface for the Atmega2560 MCU.
 *
 * @author Francisco Soto <francisco@nanosatisfi.com>
 ******************************************************************************/

#include <stdlib.h>
#include <avr/io.h>

#include "conf_xmem.h"
#include "atmega2560-xmem.h"

/* If memory is not a multiple of 64KB we need to find out what's the last bank size. */
#if (XMEM_TOTAL_MEMORY % 65536) == 0
#define XMEM_LAST_BANK_END  ((void *)0xffff)
#else
#define XMEM_LAST_BANK_END  ((void *)((XMEM_TOTAL_MEMORY % 65536) - 1))
#endif

/* Atmega XMEM address space block */
#define XMEM_START      ((void *)0x2200)
#define XMEM_END        ((void *)0xffff)

/* The address space to use for unshadowed memory */
#define XMEM_SHADOWED_START ((void *)0x8000)
#define XMEM_SHADOWED_END   ((void *)0x9fff)

struct bank_heap_state {
    void *__brkval;             /* Pointer between __malloc_heap_start and __malloc_heap_end, shows growth. */
    void *__flp;                /* Pointer to the free block list that malloc handles. */
    char *__malloc_heap_start;  /* Pointer to the beginning of the heap. */
    char *__malloc_heap_end;    /* Pointer to the end of the heap, 0 if the heap is below the stack. */
};

/* Private heap variables */
#ifdef __cplusplus
extern "C" {
#endif
    extern void *__flp;
    extern void *__brkval;
#ifdef __cplusplus
}
#endif

struct bank_heap_state _system_heap_state;
struct bank_heap_state _bank_state[XMEM_BANKS];
uint8_t _system_heap_in_place = 0;
uint8_t _current_bank = -1;

/**
 * @docstring
 * Save the current heap state in the given bank_heap_state pointer.
 */
static void _xmem_save_bank_state (struct bank_heap_state *bs) {
    bs->__brkval = __brkval;
    bs->__flp = __flp;
    bs->__malloc_heap_start = __malloc_heap_start;
    bs->__malloc_heap_end = __malloc_heap_end;
}

/**
 * @docstring
 * Load the given bank_heap_state into the global heap state.
 */
static void _xmem_load_bank_state (struct bank_heap_state *bs) {
    __brkval = bs->__brkval;
    __flp = bs->__flp;
    __malloc_heap_start = bs->__malloc_heap_start;
    __malloc_heap_end = bs->__malloc_heap_end;
}

/**
 * @docstring
 * Unshadow the lower 8KB of the extended memory and return a pointer that
 * you can use to access it. You have to call the xmem_shadow_lower_memory when done.
 * The pointer returned is the start of your 8KB block of memory.
 */
void *xmem_unshadow_lower_memory (void) {
    /* Configures PORTC pins as output pins. */
    DDRC = 0xff;

    /* Port C has all 0s now. */
    PORTC = 0x00;

    /* Release the 5,6,7 pins from extended memory addressing duty. They are still
       addressing memory, they are just always set to 0 and that will leave us with
       only 13 pins (8KB) of address in external memory. Since these pins are zeroed out,
       you will be effectively addressing the lower 8KB of external memory. */
    XMCRB = (1 << XMM0) | (1 << XMM1);

    return XMEM_SHADOWED_START;
}

/**
 * @docstring
 * Shadow the lower 8KB of the extended memory and set normal addressing pins.
 */
void xmem_shadow_lower_memory (void) {
    /* Configures PORTC pins as output pins. */
    DDRC = 0xff;

    /* Port C has all 0s now. */
    PORTC = 0x00;

    /* Set every pin to regular memory addressing duty. */
    XMCRB = 0;
}

/**
 * @docstring
 * Switch bank if the bank exist and is not the current one.
 */
void xmem_switch_bank (uint8_t bank) {
    if (_current_bank == bank || bank > XMEM_BANKS) {
        return;
    }

    if (!_system_heap_in_place) {
        /* Save the current bank heap state */
        _xmem_save_bank_state(&_bank_state[_current_bank]);

        /* And restore the state we are switching to. */
        _xmem_load_bank_state(&_bank_state[bank]);
    }

    _current_bank = bank;

    /* Have the user set the higher bits */
    XMEM_USER_SWITCH_BANK(bank);
}

/**
 * @docstring
 * This will save the current bank state and return the heap to the
 * internal memory. You can effectively stop xmem from being used for
 * the heap if you use this function.
 */
void xmem_set_system_heap (void) {
    if (_system_heap_in_place) {
        return;
    }

    _xmem_save_bank_state(&_bank_state[_current_bank]);
    _xmem_load_bank_state(&_system_heap_state);

    _system_heap_in_place = 1;
}

/**
 * @docstring
 * This should be used after a call to xmem_set_system_heap. This will save
 * the current internal memory heap state and return the heap to the extended
 * memory using the current bank.
 */
void xmem_set_xmem_heap (void) {
    if (!_system_heap_in_place) {
        return;
    }

    _xmem_save_bank_state(&_system_heap_state);
    _xmem_load_bank_state(&_bank_state[_current_bank]);

    _system_heap_in_place = 0;
}

/**
 * @docstring
 * Returns the last valid address in the current selected bank.
 */
void *xmem_get_current_bank_address_start (void) {
    return (void *)_bank_state[_current_bank].__malloc_heap_start;
}

/**
 * @docstring
 * Returns the last valid address in the current selected bank.
 */
void *xmem_get_current_bank_address_end (void) {
    return (void *)_bank_state[_current_bank].__malloc_heap_end;
}

/**
 * @docstring
 * Initializes the external memory and the internal data structures if we are managing the heap in the xmem.
 */
void xmem_init (void) {
   /* TODO: Calculate the # of pins we need for the given memory and
      calculate a mask for XMCRB. Save this mask because we will need it
      to restore XMCRB later on if we want to access the first 8KB of XMEM.
      This assumes we want all 8 bits from PORTC. */
    XMCRB = 0;

    /* XMEM Enable bit, entire xmem is treated like one sector and set the wait
       states for it. */
    XMCRA = (1 << SRE) | (XMEM_WAIT_STATES << SRW10);

    /* Have the user configure his extra pins. */
    XMEM_USER_INIT();

    _xmem_save_bank_state(&_system_heap_state);

    /* If heap should be in xmem ram then we should let avr-libc where is it. */
    __malloc_heap_start = (char *)XMEM_START;
    __malloc_heap_end = (char *)XMEM_END;
    __brkval = (char *)XMEM_START;

#ifdef XMEM_USE_BANKING
    /* All banks except the last one have 64KB size. */
    for (uint8_t i = 0; i < XMEM_BANKS - 1; i++) {
        _xmem_save_bank_state(&_bank_state[i]);
    }
#endif /* XMEM_USE_BANKKING */

    /* Save the last bank with the correct address space size. */
    __malloc_heap_end = (char *)XMEM_LAST_BANK_END;
    _xmem_save_bank_state(&_bank_state[XMEM_BANKS - 1]);

    _system_heap_in_place = 0;

    xmem_switch_bank(0);
}


text:
package org.sur.ds.arrays;

import org.junit.Assert;
import org.junit.Test;

public class LargestContinuousSubArrayTest {

	LargestContinuousSubArray lcsa = new LargestContinuousSubArray();

	@Test
	public void testGetLargestContinuousSubArray() {
		Integer[] numbers = new Integer[]{-2, -3, 4, -1, -2, 1, 5, -3};
		Assert.assertEquals(7, lcsa.getLargestContinuousSubArray(numbers));
	}

}


text:
Api-gateway component tests use the [cucumber/godog](https://github.com/cucumber/godog) library.

## Prerequisites

- Kubernetes installed and kubeconfig configured to point to this cluster
- Kyma installed

### Environment variables

These environment variables determine how the tests are run on both Prow and your local machine:

- `EXPORT_RESULT` - set this environment variable to `true` if you want to export test results to JUnit XML, Cucumber JSON, and HTML report. The default value is `false`.

## Usage for standard api-gateway test suite

To start the test suite, run:

```
make test
```

If you don't have a cluster, you can run the tests on your local machine. To do so, run:

```
make test-k3d
```

This command creates a k3d cluster on your local machine, installs Kyma on it, and runs the tests.

## Usage for custom-domain test suite

### Prepare a secret with cloud credentials to manage DNS.

Create the secret in the default namespace:

```
kubectl create secret google-credentials -n default --from-file=serviceaccount.json=serviceaccount.json
```

### Set the environment variables with custom domain

- `TEST_CUSTOM_DOMAIN` - set this environment variable with your desired custom domain.
- `TEST_DOMAIN` - set this environment variable with your installed by default Kyma domain.

After exporting these domains, run `make setup-custom-domain` to finish the default test setup.

### Run the tests

To start the test suite, run:

```
make test-custom-domain
```


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Beih. Sydowia 7: 52 (1973)

#### Original name
Hydropus eitenianus Singer

### Remarks
null


text:
from telemetry.page import page as page_module
from telemetry import story

class ToughPathRenderingCasesPage(page_module.Page):

  def RunPageInteractions(self, action_runner):
    with action_runner.CreateInteraction('ClickStart'):
      action_runner.Wait(10)

class ChalkboardPage(page_module.Page):

  def RunPageInteractions(self, action_runner):
    with action_runner.CreateInteraction('ClickStart'):
      action_runner.EvaluateJavaScript(
          'document.getElementById("StartButton").click()')
      action_runner.Wait(20)

class ToughPathRenderingCasesPageSet(story.StorySet):

  """
  Description: Self-driven path rendering examples
  """

  def __init__(self):
    super(ToughPathRenderingCasesPageSet, self).__init__(
      archive_data_file='data/tough_path_rendering_cases.json',
      cloud_storage_bucket=story.PARTNER_BUCKET)

    urls_list = [
      'http://www.craftymind.com/factory/guimark2/HTML5ChartingTest.html'
    ]

    for url in urls_list:
      self.AddUserStory(ToughPathRenderingCasesPage(url, self))

    self.AddUserStory(ChalkboardPage(
        'http://ie.microsoft.com/testdrive/Performance/Chalkboard/', self))


text:
CFPApp.factory('UserProfile', ['Auth', function (Auth) {

        var userProfile = {};

        var clearUserProfile = function () {
            for (var prop in userProfile) {
                if (userProfile.hasOwnProperty(prop)) {
                    delete userProfile[prop];
                }
            }
        };

        var fetchUserProfile = function () {
            return Auth.getIsProfileComplete().then(function (response) {
                var isProfileComplete = response.data;

                return Auth.getProfile().then(function (response) {
                    clearUserProfile();
                    return angular.extend(userProfile, response.data, {
                        $refresh: fetchUserProfile,
                        $hasRole: function (role) {
                            return userProfile.roles.indexOf(role) >= 0;
                        },
                        $hasAnyRole: function (roles) {
                            return !!userProfile.roles.filter(function (role) {
                                return roles.indexOf(role) >= 0;
                            }).length;
                        },
                        $isAnonymous: function () {
                            return 204 === response.status;
                        },
                        $isAuthenticated: function () {
                            return 204 !== response.status;
                        },
                        $isProfileComplete: function () {
                            return isProfileComplete;
                        }
                    });
                });
            });
        };

        return fetchUserProfile();

    }]);


text:
package io.github.djxy.multiscripts.java.wrappers.maps;

import com.google.common.collect.ImmutableSet;
import io.github.djxy.multiscripts.java.wrappers.FunctionWrapper;
import io.github.djxy.multiscripts.java.wrappers.GetWrapper;
import io.github.djxy.multiscripts.java.wrappers.SetWrapper;
import io.github.djxy.multiscripts.objects.MapObject;
import io.github.djxy.multiscripts.objects.ObjectContainer;
import io.github.djxy.multiscripts.objects.Value;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Created by samuelmarchildon-lavoie on 16-11-12.
 */
public class MapObjectObjectWrapper implements MapObject, ObjectContainer {

    private final Object object;
    private final Map<String, GetWrapper> gets;
    private final Map<String, SetWrapper> sets;
    private final Map<String, FunctionWrapper> functions;
    private Set<String> keys;

    public MapObjectObjectWrapper(Object object, Map<String, GetWrapper> gets, Map<String, SetWrapper> sets, Map<String, FunctionWrapper> functions) {
        this.object = object;
        this.gets = gets;
        this.sets = sets;
        this.functions = functions;
    }

    @Override
    public void remove(String key) {}

    @Override
    public void set(String key, Value object) {
        SetWrapper setWrapper = sets.get(key);

        if(setWrapper != null)
            setWrapper.invoke(this.object, object);
    }

    @Override
    public Value get(String key) {
        GetWrapper getWrapper = gets.get(key);

        if(getWrapper != null)
            return getWrapper.invoke(object);

        FunctionWrapper functionWrapper = functions.get(key);

        if(functionWrapper != null)
            return functionWrapper.toFunctionValue(object);

        return VOID;
    }

    @Override
    public boolean has(String key) {
        initKeys();

        return keys.contains(key);
    }

    @Override
    public Set<String> getKeys() {
        initKeys();

        return keys;
    }

    @Override
    public void clear() {}

    @Override
    public Object getObject() {
        return object;
    }

    private void initKeys(){
        if(this.keys != null)
            return;

        Set<String> keys = new HashSet<>();

        keys.addAll(gets.keySet());
        keys.addAll(sets.keySet());
        keys.addAll(functions.keySet());

        this.keys = ImmutableSet.copyOf(keys);
    }
}


text:
#include "vom/ip_unnumbered.hpp"
#include "vom/ip_unnumbered_cmds.hpp"
#include "vom/singular_db_funcs.hpp"

namespace VOM {
/**
 * A DB of all LLDP configs
 */
singular_db<ip_unnumbered::key_t, ip_unnumbered> ip_unnumbered::m_db;

ip_unnumbered::event_handler ip_unnumbered::m_evh;

ip_unnumbered::ip_unnumbered(const interface& itf, const interface& l3_itf)
  : m_itf(itf.singular())
  , m_l3_itf(l3_itf.singular())
{
}

ip_unnumbered::ip_unnumbered(const ip_unnumbered& o)
  : m_itf(o.m_itf)
  , m_l3_itf(o.m_l3_itf)
  , m_config(o.m_config)
{
}

ip_unnumbered::~ip_unnumbered()
{
  sweep();

  // not in the DB anymore.
  m_db.release(m_itf->key(), this);
}

void
ip_unnumbered::sweep()
{
  if (m_config) {
    HW::enqueue(new ip_unnumbered_cmds::unconfig_cmd(m_config, m_itf->handle(),
                                                     m_l3_itf->handle()));
  }
  HW::write();
}

void
ip_unnumbered::dump(std::ostream& os)
{
  db_dump(m_db, os);
}

void
ip_unnumbered::replay()
{
  if (m_config) {
    HW::enqueue(new ip_unnumbered_cmds::config_cmd(m_config, m_itf->handle(),
                                                   m_l3_itf->handle()));
  }
}

std::string
ip_unnumbered::to_string() const
{
  std::ostringstream s;
  s << "IP Unnumbered-config:"
    << " itf:" << m_itf->to_string() << " l3-itf:" << m_l3_itf->to_string();

  return (s.str());
}

void
ip_unnumbered::update(const ip_unnumbered& desired)
{
  if (!m_config) {
    HW::enqueue(new ip_unnumbered_cmds::config_cmd(m_config, m_itf->handle(),
                                                   m_l3_itf->handle()));
  }
}

std::shared_ptr<ip_unnumbered>
ip_unnumbered::find_or_add(const ip_unnumbered& temp)
{
  return (m_db.find_or_add(temp.m_itf->key(), temp));
}

std::shared_ptr<ip_unnumbered>
ip_unnumbered::singular() const
{
  return find_or_add(*this);
}

ip_unnumbered::event_handler::event_handler()
{
  OM::register_listener(this);
  inspect::register_handler({ "ip-un" }, "IP unnumbered configurations", this);
}

void
ip_unnumbered::event_handler::handle_replay()
{
  m_db.replay();
}

void
ip_unnumbered::event_handler::handle_populate(const client_db::key_t& key)
{
  std::shared_ptr<ip_unnumbered_cmds::dump_cmd> cmd =
    std::make_shared<ip_unnumbered_cmds::dump_cmd>();

  HW::enqueue(cmd);
  HW::write();

  for (auto& ip_record : *cmd) {
    auto& payload = ip_record.get_payload();

    VOM_LOG(log_level_t::DEBUG) << "ip-unnumbered dump: "
                                << " itf: " << payload.sw_if_index
                                << " ip: " << payload.ip_sw_if_index;

    std::shared_ptr<interface> itf = interface::find(payload.sw_if_index);
    std::shared_ptr<interface> ip_itf = interface::find(payload.ip_sw_if_index);

    if (itf && ip_itf) {
      ip_unnumbered ipun(*itf, *ip_itf);
      OM::commit(key, ipun);
    }
  }
}

dependency_t
ip_unnumbered::event_handler::order() const
{
  return (dependency_t::BINDING);
}

void
ip_unnumbered::event_handler::show(std::ostream& os)
{
  db_dump(m_db, os);
}
}

/*
 * fd.io coding-style-patch-verification: OFF
 *
 * Local Variables:
 * eval: (c-set-style "mozilla")
 * End:
 */