text:
package org.jbromo.dao.jpa.query.jpql;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import org.jbromo.common.ListUtil;
import org.jbromo.dao.jpa.query.AbstractQueryBuilder;
import org.jbromo.dao.jpa.query.jpql.from.JpqlFromBuilder;
import org.jbromo.dao.jpa.query.jpql.orderby.JpqlOrderByBuilder;
import org.jbromo.dao.jpa.query.jpql.select.JpqlSelectBuilder;
import org.jbromo.dao.jpa.query.jpql.where.JpqlWhereBuilder;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

/**
 * JPQL Query builder.
 * @author qjafcunuas
 * @param <M> the model type.
 */
@Slf4j
public class AbstractJpqlQueryBuilder<M extends Serializable> extends AbstractQueryBuilder<M> {

    /**
     * The From JPQL query.
     */
    @Getter(AccessLevel.PUBLIC)
    private final JpqlFromBuilder from;

    /**
     * The Select JPQL query.
     */
    @Getter(AccessLevel.PROTECTED)
    private final JpqlSelectBuilder select;

    /**
     * The Where JPQL query.
     */
    @Getter(AccessLevel.PUBLIC)
    private final JpqlWhereBuilder where;

    /**
     * The OrderBy JPQL query.
     */
    @Getter(AccessLevel.PUBLIC)
    private final JpqlOrderByBuilder orderBy;

    /**
     * Default constructor.
     * @param entityManager the entityManager to used.
     * @param modelClass the modelClass to used.
     */
    public AbstractJpqlQueryBuilder(final EntityManager entityManager, final Class<M> modelClass) {
        super(entityManager, modelClass);
        this.from = new JpqlFromBuilder(getModelClass());
        this.select = new JpqlSelectBuilder(this.from.getRootAlias(), true);
        this.where = new JpqlWhereBuilder(this);
        this.orderBy = new JpqlOrderByBuilder();
    }

    @Override
    public String toString() {
        final StringBuilder builder = new StringBuilder();
        getSelect().build(builder);
        getFrom().build(builder);
        getWhere().build(builder, ListUtil.toList());
        getOrderBy().build(builder);
        return builder.toString();
    }

    /**
     * Return query result list.
     * @return the result list.
     */
    public List<M> getResultList() {
        final TypedQuery<M> query = getQuery();
        return query.getResultList();
    }

    /**
     * Return the JPQL query.
     * @return the query.
     */
    private TypedQuery<M> getQuery() {
        // Build JPQL query.
        final StringBuilder builder = new StringBuilder();
        final List<Object> parameters = new ArrayList<>();
        getSelect().build(builder);
        getFrom().build(builder);
        getWhere().build(builder, parameters);
        getOrderBy().build(builder);

        // / Build JPA query.
        final TypedQuery<M> query = getEntityManager().createQuery(builder.toString(), getModelClass());
        bindParameters(query, parameters);
        return query;
    }

    /**
     * Execute query for a single result. If no query result, return null.
     * @return the single result.
     */
    public M getSingleResult() {
        try {
            final TypedQuery<M> query = getQuery();
            return query.getSingleResult();
        } catch (final NoResultException e) {
            log.trace("No single result", e);
            return null;
        }
    }

    /**
     * Binds parameters to query.
     * @param query the query string.
     * @param parameters parameters
     */
    private void bindParameters(final Query query, final List<Object> parameters) {
        for (int index = 0; index < parameters.size(); index++) {
            // Parameters start to 1 : ?1 ?2 ?3 ...
            query.setParameter(index + 1, parameters.get(index));
        }
    }

}


text:
import * as React from 'react'

import { Button, ButtonGroup, DropdownButton, Glyphicon } from 'react-bootstrap'

import { EllipsisText } from '../../components/EllipsisText'
import { ILigand } from '../types'
import { ColorMenuItem } from './ColorMenuItem'

interface ILigandListItemProps extends ILigand {
  onVisibilityClick(id: string): void
  onColorClick(id: string, color: string): void
}

interface IState {
  menuOpen: boolean
}

const colors = ['#909090', '#32CD32', '#FF8C00']

export class LigandListItem extends React.Component<
  ILigandListItemProps,
  IState
> {
  state = {
    menuOpen: false
  }

  onVisibilityClick = () => {
    this.props.onVisibilityClick(this.props.id)
  }

  onColorClick = (color: string) => {
    this.props.onColorClick(this.props.id, color)
    this.onMenuToggle()
  }

  onMenuToggle = () => this.setState({ menuOpen: !this.state.menuOpen })

  render() {
    const { label, id, color, visible } = this.props
    const colorMenuItems = colors.map(c => (
      <ColorMenuItem
        key={c}
        checked={c === color}
        color={c}
        onClick={this.onColorClick}
      />
    ))
    return (

          <EllipsisText
            maxLength={32}
            text={label}
            tooltipId={'ligand-label-tooltip' + id}
          />

          <ButtonGroup>
            <Button bsSize="small" onClick={this.onVisibilityClick}>
              <Glyphicon glyph={visible ? 'eye-open' : 'eye-close'} />
            </Button>
          </ButtonGroup>
          <DropdownButton
            pullRight={true}
            disabled={!visible}
            bsSize="small"
            id={id}
            title=""
            open={this.state.menuOpen}
            onToggle={this.onMenuToggle}
          >
            {colorMenuItems}
          </DropdownButton>

    )
  }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/core/css/resolver/selector_filter_parent_scope.h"

#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/css/parser/css_parser.h"
#include "third_party/blink/renderer/core/execution_context/security_context.h"
#include "third_party/blink/renderer/core/html/html_element.h"
#include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"

namespace blink {

class SelectorFilterParentScopeTest : public testing::Test {
 protected:
  void SetUp() override {
    dummy_page_holder_ = std::make_unique<DummyPageHolder>(gfx::Size(800, 600));
    GetDocument().SetCompatibilityMode(Document::kNoQuirksMode);
  }

  Document& GetDocument() { return dummy_page_holder_->GetDocument(); }

  static constexpr size_t max_identifier_hashes = 4;

 private:
  std::unique_ptr<DummyPageHolder> dummy_page_holder_;
};

TEST_F(SelectorFilterParentScopeTest, ParentScope) {
  HeapVector<CSSSelector> arena;
  GetDocument().body()->setAttribute(html_names::kClassAttr, "match");
  GetDocument().documentElement()->SetIdAttribute("myId");
  auto* div = GetDocument().CreateRawElement(html_names::kDivTag);
  GetDocument().body()->appendChild(div);
  SelectorFilter& filter = GetDocument().GetStyleResolver().GetSelectorFilter();
  GetDocument().Lifecycle().AdvanceTo(DocumentLifecycle::kInStyleRecalc);

  SelectorFilterRootScope root_scope(nullptr);
  SelectorFilterParentScope html_scope(*GetDocument().documentElement());
  {
    SelectorFilterParentScope body_scope(*GetDocument().body());
    SelectorFilterParentScope::EnsureParentStackIsPushed();
    {
      SelectorFilterParentScope div_scope(*div);
      SelectorFilterParentScope::EnsureParentStackIsPushed();

      base::span<CSSSelector> selector_vector = CSSParser::ParseSelector(
          MakeGarbageCollected<CSSParserContext>(
              kHTMLStandardMode, SecureContextMode::kInsecureContext),
          /*parent_rule_for_nesting=*/nullptr, nullptr,
          "html *, body *, .match *, #myId *", arena);
      CSSSelectorList* selectors =
          CSSSelectorList::AdoptSelectorVector(selector_vector);

      for (const CSSSelector* selector = selectors->First(); selector;
           selector = CSSSelectorList::Next(*selector)) {
        unsigned selector_hashes[max_identifier_hashes];
        filter.CollectIdentifierHashes(*selector, selector_hashes,
                                       max_identifier_hashes);
        EXPECT_NE(selector_hashes[0], 0u);
        EXPECT_FALSE(
            filter.FastRejectSelector<max_identifier_hashes>(selector_hashes));
      }
    }
  }
}

TEST_F(SelectorFilterParentScopeTest, RootScope) {
  GetDocument().body()->setInnerHTML(R"HTML(

  )HTML");
  SelectorFilter& filter = GetDocument().GetStyleResolver().GetSelectorFilter();
  GetDocument().Lifecycle().AdvanceTo(DocumentLifecycle::kInStyleRecalc);

  SelectorFilterRootScope span_scope(GetDocument().getElementById("y"));
  SelectorFilterParentScope::EnsureParentStackIsPushed();

  HeapVector<CSSSelector> arena;
  base::span<CSSSelector> selector_vector = CSSParser::ParseSelector(
      MakeGarbageCollected<CSSParserContext>(
          kHTMLStandardMode, SecureContextMode::kInsecureContext),
      /*parent_rule_for_nesting=*/nullptr, nullptr,
      "html *, body *, div *, span *, .x *, #y *", arena);
  CSSSelectorList* selectors =
      CSSSelectorList::AdoptSelectorVector(selector_vector);

  for (const CSSSelector* selector = selectors->First(); selector;
       selector = CSSSelectorList::Next(*selector)) {
    unsigned selector_hashes[max_identifier_hashes];
    filter.CollectIdentifierHashes(*selector, selector_hashes,
                                   max_identifier_hashes);
    EXPECT_NE(selector_hashes[0], 0u);
    EXPECT_FALSE(
        filter.FastRejectSelector<max_identifier_hashes>(selector_hashes));
  }
}

TEST_F(SelectorFilterParentScopeTest, ReentrantSVGImageLoading) {
  GetDocument().body()->setInnerHTML(R"HTML(

  )HTML");

  // The SVG image is loaded synchronously from style recalc re-entering style
  // recalc for the SVG image Document. Without supporting re-entrancy for
  // SelectorFilterParentScope with a SelectorFilterRootScope, this update may
  // cause DCHECKs to fail.
  GetDocument().UpdateStyleAndLayoutTree();
}

TEST_F(SelectorFilterParentScopeTest, AttributeFilter) {
  GetDocument().body()->setInnerHTML(
      R"HTML(
<svg VIewBox></svg>
)HTML");
  auto* outer = To<Element>(GetDocument().body()->firstChild());
  auto* svg = To<Element>(outer->firstChild());
  auto* inner = GetDocument().CreateRawElement(html_names::kDivTag);
  svg->appendChild(inner);

  ASSERT_TRUE(outer->hasAttributes());
  EXPECT_EQ("attr", outer->Attributes()[0].GetName().LocalName());

  ASSERT_TRUE(svg->hasAttributes());
  EXPECT_EQ("viewBox", svg->Attributes()[0].GetName().LocalName());

  SelectorFilter& filter = GetDocument().GetStyleResolver().GetSelectorFilter();
  GetDocument().Lifecycle().AdvanceTo(DocumentLifecycle::kInStyleRecalc);

  SelectorFilterRootScope span_scope(inner);
  SelectorFilterParentScope::EnsureParentStackIsPushed();

  HeapVector<CSSSelector> arena;
  base::span<CSSSelector> selector_vector = CSSParser::ParseSelector(
      MakeGarbageCollected<CSSParserContext>(
          kHTMLStandardMode, SecureContextMode::kInsecureContext),
      /*parent_rule_for_nesting=*/nullptr, nullptr,
      "[Attr] *, [attr] *, [viewbox] *, [VIEWBOX] *", arena);
  CSSSelectorList* selectors =
      CSSSelectorList::AdoptSelectorVector(selector_vector);

  for (const CSSSelector* selector = selectors->First(); selector;
       selector = CSSSelectorList::Next(*selector)) {
    unsigned selector_hashes[max_identifier_hashes];
    filter.CollectIdentifierHashes(*selector, selector_hashes,
                                   max_identifier_hashes);
    EXPECT_NE(selector_hashes[0], 0u);
    EXPECT_FALSE(
        filter.FastRejectSelector<max_identifier_hashes>(selector_hashes));
  }
}

}  // namespace blink


text:
package androidx.media3.decoder.opus;

import androidx.media3.common.C;
import androidx.media3.test.utils.DefaultRenderersFactoryAsserts;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;

/** Unit test for {@link DefaultRenderersFactoryTest} with {@link LibopusAudioRenderer}. */
@RunWith(AndroidJUnit4.class)
public final class DefaultRenderersFactoryTest {

  @Test
  public void createRenderers_instantiatesOpusRenderer() {
    DefaultRenderersFactoryAsserts.assertExtensionRendererCreated(
        LibopusAudioRenderer.class, C.TRACK_TYPE_AUDIO);
  }
}


text:
Jupyter notebooks created as answers to assignments in courses etc. at
NTNU


text:
import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from 'my-app/tests/helpers/start-app';

module('Acceptance | foo', {
  beforeEach: function() {
    this.application = startApp();
  },

  afterEach: function() {
    Ember.run(this.application, 'destroy');
  }
});

test('visiting /foo', function(assert) {
  visit('/foo');

  andThen(function() {
    assert.equal(currentURL(), '/foo');
  });
});


text:
package com.tle.web.viewitem.treeviewer;

import com.tle.web.sections.SectionInfo;
import com.tle.web.viewurl.ItemUrlExtender;

public class DownloadIMSPackageLink implements ItemUrlExtender {
  private static final long serialVersionUID = 1L;

  @Override
  public void execute(SectionInfo info) {
    TreeNavigationSection navSection = info.lookupSection(TreeNavigationSection.class);
    navSection.getModel(info).setDownload(true);
  }
}


text:
RAILS_GEM_VERSION = '2.3.5' unless defined? RAILS_GEM_VERSION

# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')

# thanks to http://www.justinball.com/2009/06/16/testing-rails-engine-gems/
class TestGemLocator < Rails::Plugin::Locator
  def plugins
    Rails::Plugin.new(File.join(File.dirname(__FILE__), *%w(.. .. ..)))
  end
end

Rails::Initializer.run do |config|
  # Settings in config/environments/* take precedence over those specified here.
  # Application configuration should go into files in config/initializers
  # -- all .rb files in that directory are automatically loaded.

  # Add additional load paths for your own custom dirs
  # config.load_paths += %W( #{RAILS_ROOT}/extras )

  # Specify gems that this application depends on and have them installed with rake gems:install
  # config.gem "bj"
  # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
  # config.gem "sqlite3-ruby", :lib => "sqlite3"
  # config.gem "aws-s3", :lib => "aws/s3"
  # this allows us to place locale in URL
  # without messing with the rest of the rails routing mechanism
  # config.gem "routing_filter" # using plugin for the moment
  # config.gem "oembed_provider"
  config.plugin_locators << TestGemLocator

  # Only load the plugins named here, in the order given (default is alphabetical).
  # :all can be used as a placeholder for all plugins not explicitly named
  # config.plugins = [ :exception_notification, :ssl_requirement, :all ]

  # Skip frameworks you're not going to use. To use Rails without a database,
  # you must remove the Active Record framework.
  # config.frameworks -= [ :active_record, :active_resource, :action_mailer ]

  # Activate observers that should always be running
  # config.active_record.observers = :cacher, :garbage_collector, :forum_observer

  # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
  # Run "rake -D time" for a list of tasks for finding time zone names.
  config.time_zone = 'UTC'

  # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
  # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
  # config.i18n.default_locale = :de
end


text:
import { combineReducers } from 'redux'

import flashMessages from './reducers/flashMessages'

export default combineReducers({
  flashMessages,
})


text:
package com.nagopy.android.callconfirm.receiver.helper;

import android.app.Application;
import android.content.Intent;

import com.nagopy.android.callconfirm.di.ReceiverScope;
import com.nagopy.android.callconfirm.view.ConfirmActivity;

import javax.inject.Inject;

@ReceiverScope
public class Navigator {

    @Inject
    Application context;

    @Inject
    Navigator() {
    }

    public void startConfirmActivity(String phoneNumber) {
        Intent intent = new Intent(context, ConfirmActivity.class);
        intent.putExtra(Intent.EXTRA_PHONE_NUMBER, phoneNumber);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

}


text:
.class public Lcom/htc/weather/animations/Anim16;
.super Lcom/htc/weather/animations/WeatherAnimationData;
.source "Anim16.java"

# instance fields
.field private cloud01:Lcom/htc/weather/animations/ImageViewAndAnimationSets;

.field private cloud02:Lcom/htc/weather/animations/ImageViewAndAnimationSets;

.field private cloud03:Lcom/htc/weather/animations/ImageViewAndAnimationSets;

.field private lightning:Lcom/htc/weather/animations/LightningV1;

.field private raindrops:Lcom/htc/weather/animations/Raindrops;

.field private shower:Lcom/htc/weather/animations/Shower;

.field private sun3:Lcom/htc/weather/animations/Sun3;

# direct methods
.method public constructor <init>(Landroid/content/Context;Lcom/htc/weather/EnvSetting$Env;)V
    .locals 10
    .parameter "context"
    .parameter "env"

    .prologue
    .line 23
    invoke-direct {p0, p1, p2}, Lcom/htc/weather/animations/WeatherAnimationData;-><init>(Landroid/content/Context;Lcom/htc/weather/EnvSetting$Env;)V

    .line 67
    new-instance v0, Lcom/htc/weather/animations/Anim16$1;

    invoke-direct {v0, p0}, Lcom/htc/weather/animations/Anim16$1;-><init>(Lcom/htc/weather/animations/Anim16;)V

    iput-object v0, p0, Lcom/htc/weather/animations/Anim16;->cloud01:Lcom/htc/weather/animations/ImageViewAndAnimationSets;

    .line 150
    new-instance v0, Lcom/htc/weather/animations/Anim16$2;

    invoke-direct {v0, p0}, Lcom/htc/weather/animations/Anim16$2;-><init>(Lcom/htc/weather/animations/Anim16;)V

    iput-object v0, p0, Lcom/htc/weather/animations/Anim16;->cloud02:Lcom/htc/weather/animations/ImageViewAndAnimationSets;

    .line 233
    new-instance v0, Lcom/htc/weather/animations/Anim16$3;

    invoke-direct {v0, p0}, Lcom/htc/weather/animations/Anim16$3;-><init>(Lcom/htc/weather/animations/Anim16;)V

    iput-object v0, p0, Lcom/htc/weather/animations/Anim16;->cloud03:Lcom/htc/weather/animations/ImageViewAndAnimationSets;

    .line 24
    new-instance v0, Lcom/htc/weather/animations/Sun3;

    const/4 v3, 0x0

    const/16 v4, -0xa

    const/high16 v5, 0x3f80

    const/high16 v6, 0x3f80

    const/high16 v7, 0x3f80

    const-wide/16 v8, 0x0

    move-object v1, p1

    move-object v2, p2

    invoke-direct/range {v0 .. v9}, Lcom/htc/weather/animations/Sun3;-><init>(Landroid/content/Context;Lcom/htc/weather/EnvSetting$Env;IIFFFJ)V

    iput-object v0, p0, Lcom/htc/weather/animations/Anim16;->sun3:Lcom/htc/weather/animations/Sun3;

    .line 25
    new-instance v0, Lcom/htc/weather/animations/Shower;

    const/16 v3, 0x14

    const/4 v4, 0x0

    const/high16 v5, 0x3f80

    const/high16 v6, 0x3f80

    const/high16 v7, 0x3f80

    const-wide/16 v8, 0x0

    move-object v1, p1

    move-object v2, p2

    invoke-direct/range {v0 .. v9}, Lcom/htc/weather/animations/Shower;-><init>(Landroid/content/Context;Lcom/htc/weather/EnvSetting$Env;IIFFFJ)V

    iput-object v0, p0, Lcom/htc/weather/animations/Anim16;->shower:Lcom/htc/weather/animations/Shower;

    .line 26
    new-instance v0, Lcom/htc/weather/animations/LightningV1;

    const/16 v3, -0x14

    const/16 v4, -0xf

    const/high16 v5, 0x3f80

    const/high16 v6, 0x3f80

    const/high16 v7, 0x3f80

    const-wide/16 v8, 0x0

    move-object v1, p1

    move-object v2, p2

    invoke-direct/range {v0 .. v9}, Lcom/htc/weather/animations/LightningV1;-><init>(Landroid/content/Context;Lcom/htc/weather/EnvSetting$Env;IIFFFJ)V

    iput-object v0, p0, Lcom/htc/weather/animations/Anim16;->lightning:Lcom/htc/weather/animations/LightningV1;

    .line 27
    new-instance v0, Lcom/htc/weather/animations/Raindrops;

    const/4 v3, 0x0

    const/4 v4, 0x0

    const/high16 v5, 0x3f80

    const/high16 v6, 0x3f80

    const/high16 v7, 0x3f80

    const-wide/16 v8, 0x0

    move-object v1, p1

    move-object v2, p2

    invoke-direct/range {v0 .. v9}, Lcom/htc/weather/animations/Raindrops;-><init>(Landroid/content/Context;Lcom/htc/weather/EnvSetting$Env;IIFFFJ)V

    iput-object v0, p0, Lcom/htc/weather/animations/Anim16;->raindrops:Lcom/htc/weather/animations/Raindrops;

    .line 28
    return-void
.end method

# virtual methods
.method public getImageViewsAndAnimations()[Lcom/htc/weather/animations/ImageViewAndAnimationSets;
    .locals 10

    .prologue
    .line 36
    iget-object v8, p0, Lcom/htc/weather/animations/Anim16;->sun3:Lcom/htc/weather/animations/Sun3;

    invoke-virtual {v8}, Lcom/htc/weather/animations/Sun3;->getImageViewsAndAnimations()[Lcom/htc/weather/animations/ImageViewAndAnimationSets;

    move-result-object v7

    .line 37
    .local v7, sunSets:[Lcom/htc/weather/animations/ImageViewAndAnimationSets;
    iget-object v8, p0, Lcom/htc/weather/animations/Anim16;->shower:Lcom/htc/weather/animations/Shower;

    invoke-virtual {v8}, Lcom/htc/weather/animations/Shower;->getImageViewsAndAnimations()[Lcom/htc/weather/animations/ImageViewAndAnimationSets;

    move-result-object v6

    .line 38
    .local v6, showerSets:[Lcom/htc/weather/animations/ImageViewAndAnimationSets;
    iget-object v8, p0, Lcom/htc/weather/animations/Anim16;->lightning:Lcom/htc/weather/animations/LightningV1;

    invoke-virtual {v8}, Lcom/htc/weather/animations/LightningV1;->getImageViewsAndAnimations()[Lcom/htc/weather/animations/ImageViewAndAnimationSets;

    move-result-object v3

    .line 39
    .local v3, lightningSets:[Lcom/htc/weather/animations/ImageViewAndAnimationSets;
    iget-object v8, p0, Lcom/htc/weather/animations/Anim16;->raindrops:Lcom/htc/weather/animations/Raindrops;

    invoke-virtual {v8}, Lcom/htc/weather/animations/Raindrops;->getImageViewsAndAnimations()[Lcom/htc/weather/animations/ImageViewAndAnimationSets;

    move-result-object v4

    .line 41
    .local v4, raindropsSets:[Lcom/htc/weather/animations/ImageViewAndAnimationSets;
    array-length v8, v7

    array-length v9, v6

    add-int/2addr v8, v9

    array-length v9, v3

    add-int/2addr v8, v9

    add-int/lit8 v8, v8, 0x3

    array-length v9, v4

    add-int/2addr v8, v9

    new-array v5, v8, [Lcom/htc/weather/animations/ImageViewAndAnimationSets;

    .line 44
    .local v5, sets:[Lcom/htc/weather/animations/ImageViewAndAnimationSets;
    const/4 v1, 0x0

    .local v1, index:I
    :goto_0
    array-length v8, v7

    if-ge v1, v8, :cond_0

    .line 45
    aget-object v8, v7, v1

    aput-object v8, v5, v1

    .line 44
    add-int/lit8 v1, v1, 0x1

    goto :goto_0

    .line 47
    :cond_0
    iget-object v8, p0, Lcom/htc/weather/animations/Anim16;->cloud03:Lcom/htc/weather/animations/ImageViewAndAnimationSets;

    aput-object v8, v5, v1

    .line 48
    add-int/lit8 v1, v1, 0x1

    .line 49
    const/4 v0, 0x0

    .local v0, i:I
    :goto_1
    array-length v8, v6

    if-ge v0, v8, :cond_1

    .line 50
    aget-object v8, v6, v0

    aput-object v8, v5, v1

    .line 49
    add-int/lit8 v0, v0, 0x1

    add-int/lit8 v1, v1, 0x1

    goto :goto_1

    .line 52
    :cond_1
    iget-object v8, p0, Lcom/htc/weather/animations/Anim16;->cloud02:Lcom/htc/weather/animations/ImageViewAndAnimationSets;

    aput-object v8, v5, v1

    .line 53
    add-int/lit8 v1, v1, 0x1

    .line 55
    const/4 v0, 0x0

    :goto_2
    array-length v8, v3

    if-ge v0, v8, :cond_2

    .line 56
    aget-object v8, v3, v0

    aput-object v8, v5, v1

    .line 55
    add-int/lit8 v0, v0, 0x1

    add-int/lit8 v1, v1, 0x1

    goto :goto_2

    .line 58
    :cond_2
    iget-object v8, p0, Lcom/htc/weather/animations/Anim16;->cloud01:Lcom/htc/weather/animations/ImageViewAndAnimationSets;

    aput-object v8, v5, v1

    .line 59
    add-int/lit8 v1, v1, 0x1

    .line 60
    const/4 v0, 0x0

    :goto_3
    array-length v8, v4

    if-ge v0, v8, :cond_3

    .line 61
    add-int/lit8 v2, v1, 0x1

    .end local v1           #index:I
    .local v2, index:I
    aget-object v8, v4, v0

    aput-object v8, v5, v1

    .line 60
    add-int/lit8 v0, v0, 0x1

    move v1, v2

    .end local v2           #index:I
    .restart local v1       #index:I
    goto :goto_3

    .line 65
    :cond_3
    return-object v5
.end method


text:
<link rel="import" href="../bower_components/polymer/polymer.html">

<dom-module id="custom-element-demo">

  <link rel="import" type="css" href="../bower_components/github-markdown-css/github-markdown.css">
  <template>

        <spinner-lite id="demo-spinner" active></paper>

        <template is="dom-if" if="[[_showFirstTimeMessage()]]">

            <svg viewBox="0 0 100 100">
              <use xlink:href="/sprite.octicons.svg#pencil"></use>
            </svg>

Tap to edit

              Demo will live update as you edit.

        </template>

          <button id="exportSource" title="Export Markdown" on-tap="_exportSource">
            <template is="dom-if" if="[[example]]">
              <svg viewBox="0 0 100 100">
                <use xlink:href="/sprite.octicons.svg#markdown"></use>
              </svg>
              Markdown
            </template>
          </button>
          <button id="expandSource" title="Expand source" on-tap="_expandSource">
            <svg viewBox="0 0 100 100">
              <use xlink:href="/sprite.octicons.svg#gist"></use>
            </svg>
            Expand
          </button>
          <form action="https://jsfiddle.net/api/post/library/pure/" method="post" target="_blank">
            <input type="hidden" id="html" name="html">
            <button title="Export to JSFiddle" on-tap="_openAsFiddle">
              <svg viewBox="0 0 100 100">
                <use xlink:href="/sprite.octicons.svg#cloud-upload"></use>
              </svg>
              Export
            </button>
          </form>

  </template>

</dom-module>


text:
import { Mongo } from 'meteor/mongo';

const mongoOptionStr = process.env.MONGO_OPTIONS;
if (typeof mongoOptionStr !== 'undefined') {
	const mongoOptions = JSON.parse(mongoOptionStr);

	Mongo.setConnectionOptions(mongoOptions);
}


text:
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import cx from 'classnames'
import TextareaAutosize from 'react-autosize-textarea'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faPaperPlane, faTrashAlt } from '@fortawesome/free-regular-svg-icons'
import _ from 'lodash'

import './ToolEditor.css'
import Answers from './Answers'
import AnswerOption from './AnswerOption'

import InputTrigger from '../../components/InputTrigger'

class Step extends Component {
  static propTypes = {
    sIdx: PropTypes.number.isRequired,
    step: PropTypes.object.isRequired,
    stepCount: PropTypes.number.isRequired,
    onSetStepToPronouns: PropTypes.func.isRequired,
    onUpdateStep: PropTypes.func.isRequired,
    onRemoveStep: PropTypes.func.isRequired,
    onAddStep: PropTypes.func.isRequired,
    onPromptVariable: PropTypes.func.isRequired,
    onRef: PropTypes.func.isRequired,
    onRegisterUnpromptVariable: PropTypes.func.isRequired,
  }
  componentDidMount() {
    this.props.onRef(this)
  }
  shouldComponentUpdate(nextProps) {
    return (
      !_.isEqual(this.props.step, nextProps.step) ||
      this.props.sIdx !== nextProps.sIdx ||
      this.props.stepCount !== nextProps.stepCount
    )
  }
  componentWillUnmount() {
    this.props.onRef(null)
  }

  render() {
    const {
      step,
      sIdx,
      stepCount,
      onPromptVariable,
      onRegisterUnpromptVariable,
    } = this.props
    return (
      <div key={sIdx} id={`step-${sIdx}`} className='step'>

              <InputTrigger
                onStart={obj => {
                  onPromptVariable({
                    sIdx,
                    key: 'title',
                    promptIdx: obj.cursor.selectionStart - 1,
                  })
                }}
                endTrigger={endTriggerHandler =>
                  onRegisterUnpromptVariable(endTriggerHandler, sIdx, 'title')
                }
                elementRef={this.elems.title}
              >
                <input
                  style={{ width: '100%', border: 0, marginBottom: 20 }}
                  ref={el => {
                    this.elems.title = el
                  }}
                  className='h2'
                  placeholder='Step title'
                  value={step.title}
                  onChange={this.changeStepKey('title')}
                />
              </InputTrigger>

              <InputTrigger
                onStart={obj => {
                  onPromptVariable({
                    sIdx,
                    key: 'description',
                    promptIdx: obj.cursor.selectionStart - 1,
                  })
                }}
                endTrigger={endTriggerHandler =>
                  onRegisterUnpromptVariable(
                    endTriggerHandler,
                    sIdx,
                    'description',
                  )
                }
                elementRef={this.elems.description}
              >
                <TextareaAutosize
                  style={{ width: '100%', border: 0 }}
                  required
                  className='form-control'
                  placeholder='Step description'
                  value={step.description}
                  onChange={this.changeStepKey('description')}
                  innerRef={el => {
                    this.elems.description = el
                  }}
                />
              </InputTrigger>

              <InputTrigger
                onStart={obj => {
                  onPromptVariable({
                    sIdx,
                    key: 'notes',
                    promptIdx: obj.cursor.selectionStart - 1,
                  })
                }}
                endTrigger={endTriggerHandler =>
                  onRegisterUnpromptVariable(endTriggerHandler, sIdx, 'notes')
                }
                elementRef={this.elems.notes}
              >
                <TextareaAutosize
                  style={{ width: '100%', border: 0 }}
                  required
                  className='form-control text-muted tool-note'
                  placeholder='Step notes'
                  value={step.notes}
                  onChange={this.changeStepKey('notes')}
                  innerRef={el => {
                    this.elems.notes = el
                  }}
                />
              </InputTrigger>

              {sIdx}/{stepCount}{' '}

                <FontAwesomeIcon icon={faTrashAlt} />

            <select
              className={cx('select', 'stepRevealable')}
              style={{ marginRight: 5 }}
              value={step.type}
              onChange={this.changeStepKey('type')}
              required
            >
              <option value='radio'>Radio</option>
              <option value='pronouns'>Pronouns</option>
              <option value='checkbox'>Checkbox</option>
              <option value='short'>Short</option>
              <option value='long'>Long</option>
              <option value='flash'>flash</option>
            </select>

        {this.renderShortAnswer()}
        {this.renderLongAnswer()}
        {this.renderFlashAnswer()}
        <Answers
          onUpdateStepAnswers={this.updateStepAnswers}
          sIdx={sIdx}
          type={step.type}
          answers={step.answers}
        />

          + Step

    )
  }

  renderShortAnswer() {
    const { step } = this.props
    if (step.type !== 'short') {
      return null
    }
    return (

        <input
          className='form-control'
          value={step.inputPlaceholder}
          placeholder='Short answer placeholder'
          onChange={this.changeStepKey('inputPlaceholder')}
        />

          <AnswerOption
            icon={faPaperPlane}
            toggleId='hasGoToStep'
            toggleValue={step.hasGoToStep}
            fieldId='goToStepByNum'
            fieldValue={step.goToStepByNum}
            onToggle={this.toggleStepKey('hasGoToStep')}
            onFieldChange={this.changeStepKey('goToStepByNum')}
          />

    )
  }

  renderLongAnswer() {
    const { step } = this.props
    if (step.type !== 'long') {
      return null
    }
    return (

        <textarea
          className='form-control'
          value={step.inputPlaceholder}
          placeholder='Long answer placeholder'
          onChange={this.changeStepKey('inputPlaceholder')}
        />

          <AnswerOption
            icon={faPaperPlane}
            toggleId='hasGoToStep'
            toggleValue={step.hasGoToStep}
            fieldId='goToStepByNum'
            fieldValue={step.goToStepByNum}
            onToggle={this.toggleStepKey('hasGoToStep')}
            onFieldChange={this.changeStepKey('goToStepByNum')}
          />

    )
  }

  renderFlashAnswer() {
    const { step, sIdx } = this.props
    if (step.type !== 'flash') {
      return null
    }
    return (

            <label className='sr-only' htmlFor={`flash-step-${sIdx}`}>
              Flash Step

Flash Step

              <input
                type='text'
                className='form-control'
                id={`flash-step-${sIdx}`}
                placeholder='Flash Step'
                value={step.flashStepNum}
                onChange={this.changeStepKey('flashStepNum')}
              />

            <label className='sr-only' htmlFor={`flash-speed-${sIdx}`}>
              Flash speed

Flash speed

              <input
                type='text'
                className='form-control'
                id={`flash-speed-${sIdx}`}
                placeholder='Flash speed'
                value={step.flashSpeed}
                onChange={this.changeStepKey('flashSpeed')}
              />

    )
  }

  elems = {}

  changeStepKey = key => evt => {
    if (key === 'type') return this.changeStepType(evt)

    this.props.onUpdateStep(this.props.sIdx, {
      ...this.props.step,
      [key]: evt.target.value,
    })
  }

  changeStepType = evt => {
    const shouldContinue = window.confirm(
      `Set step type to ${evt.target.value}?`,
    )
    if (!shouldContinue) return
    if (evt.target.value === 'pronouns') {
      return this.props.onSetStepToPronouns(this.props.sIdx)
    }
    this.props.onUpdateStep(this.props.sIdx, {
      ...this.props.step,
      type: evt.target.value,
      isPronouns: false,
    })
  }

  toggleStepKey = key => () => {
    this.props.onUpdateStep(this.props.sIdx, {
      ...this.props.step,
      [key]: !this.props.step[key],
    })
  }

  removeStep = () => {
    if (!global.confirm(`really delete step ${this.props.sIdx}?`)) {
      return
    }
    this.props.onRemoveStep(this.props.sIdx)
  }

  addStep = () => {
    this.props.onAddStep(this.props.sIdx)
  }

  updateStepAnswers = answers => {
    this.props.onUpdateStep(this.props.sIdx, { ...this.props.step, answers })
  }
}

export default Step


text:
import { AbstractExerciseFeedback } from '../AbstractExerciseFeedbackPage';

/**
 * A class which encapsulates UI selectors and actions for a text exercise feedback page.
 */
export class ModelingExerciseFeedbackPage extends AbstractExerciseFeedback {
    shouldShowComponentFeedback(component: number, points: number, feedback: string) {
        cy.get('#component-feedback-table').children().eq(1).children().eq(component).should('contain.text', feedback).and('contain.text', `${points}`);
    }
}


text:
import unittest
from controllers.controller import Controller
from models.collection import Collection
from models.keyword import Keyword
from models.document import Document
from config import DOCUMENT_DIRECTORY_PATH
import uuid
import datetime
import time
import os

class TestController(unittest.TestCase):

    def setUp(self):
        self.controller = Controller()
        self.address = self.controller.connection.create_address('Controller Test address', True)

        coll_address = str(uuid.uuid1())
        doc_hash_1 = str(uuid.uuid1())
        doc_hash_2 = str(uuid.uuid1())
        doc_hash_3 = str(uuid.uuid1())
        self.test_collection = Collection(
            title="Test",
            description="This is a collection!",
            address=self.address,
            btc="123456789",
            keywords=[
                Keyword(name="Keyword A", id=1099),
                Keyword(name="Keyword B", id=111),
            ],
            documents=[
                Document(
                    description="Test document A",
                    hash=doc_hash_1,
                    title="Test A",
                    accesses=0,
                    filename="joe.txt",
                    collection_address="afgagahhsgh"
                    ),
                Document(
                    description="Test document B",
                    hash=doc_hash_2,
                    title="Test B",
                    accesses=3,
                    filename="gile.txt",
                    collection_address="afgagasghhhss"
                    ),
            ],
            creation_date=datetime.datetime.now(),
            oldest_date=datetime.datetime.now(),
            latest_broadcast_date=datetime.datetime.now(),
            latest_btc_tx="btctx1",
            oldest_btc_tx="btctx12",
            accesses=2,
            votes=3,
            votes_last_checked=datetime.datetime.now()
        )

        self.test_collection_updated = Collection(
            title="Test",
            description="This is a collection! and its updated",
            address=self.address,
            btc="123456789",
            keywords=[
                Keyword(name="Keyword A", id=1099),
                Keyword(name="Keyword B", id=111),
                Keyword(name="key3", id=222)
            ],
            documents=[
                Document(
                    description="Test document A",
                    hash=doc_hash_1,
                    title="Test A",
                    accesses=0,
                    filename="joe.txt",
                    collection_address="afgagahhsgh"
                    ),
                Document(
                    description="Test document B",
                    hash=doc_hash_2,
                    title="Test B",
                    accesses=3,
                    filename="gile.txt",
                    collection_address="afgagasghhhss"
                    ),
                 Document(
                    description="Test document B",
                    hash=doc_hash_3,
                    title="Test C",
                    accesses=5,
                    filename="gileww.txt",
                    collection_address="afgagawwwsghhhss"
                    ),
            ],
            creation_date=datetime.datetime.now(),
            oldest_date=datetime.datetime.now(),
            latest_broadcast_date=datetime.datetime.now(),
            latest_btc_tx="btctx1",
            oldest_btc_tx="btctx12",
            accesses=2,
            votes=3,
            votes_last_checked=datetime.datetime.now()
        )

    def tearDown(self):
        self.controller = None

    def test_publish_and_import_collection(self):
        self.controller.publish_collection(self.test_collection, self.address, self.address)
        timeout = 600  # 10 minutes
        start_time = time.time()
        curr_time = time.time()

        sent = False
        while curr_time - start_time < timeout:
            sent = self.controller.import_collection(self.address)
            if sent:
                break
            curr_time = time.time()
            time.sleep(1)
        coll = self.controller.cache.get_collection_with_address(self.address)
        self.assertEqual(coll.title, 'Test')
        self.assertEqual(coll.btc, '123456789')
        self.assertEqual(coll.description, 'This is a collection!')
        self.assertEqual(coll.address, self.address)
        self.controller.publish_collection(self.test_collection_updated, self.address, self.address)

        timeout = 600  # 10 minutes
        start_time = time.time()
        curr_time = time.time()

        sent = False
        while curr_time - start_time < timeout:
            sent = self.controller.import_collection(self.address)
            if sent:
                break
            curr_time = time.time()
            time.sleep(1)
        coll = self.controller.cache.get_collection_with_address(self.address)
        self.assertEqual(coll.title, 'Test')
        self.assertEqual(coll.btc, '123456789')
        self.assertEqual(coll.description, 'This is a collection! and its updated')
        self.assertEqual(coll.address, self.address)
        self.assertEqual(3, len(coll.documents))
        self.assertEqual(3, len(coll.keywords))

    def test_save_document(self):
        data = open('unittests/Test1.txt', 'r').read()
        file_name = "Test1.txt"

        self.controller._save_document(data, file_name, testing_mode=True)
        self.assertTrue(os.path.exists(os.path.expanduser("Test1.txt")))

suite = unittest.TestLoader().loadTestsFromTestCase(TestController)
unittest.TextTestRunner(verbosity=2).run(suite)


text:
package my.liewjuntung.daggerviperusage.dagger;

import android.app.Application;
import android.content.Context;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;

/**
 * Created by pandawarrior on 24/10/2017.
 */
@Module
public class AppModule {

    /**
     * Provides application level context
     * @param application
     * @return
     */
    @Provides
    @Singleton
    public Context provideContext(Application application) {
        return application;
    }
}


text:
package alien4cloud.rest.orchestrator.resources;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import alien4cloud.rest.orchestrator.AbstractLocationResourcesSecurityController;
import io.swagger.annotations.Api;

@RestController
@RequestMapping({ "/rest/orchestrators/{orchestratorId}/locations/{locationId}/resources/{resourceId}/security/",
        "/rest/v1/orchestrators/{orchestratorId}/locations/{locationId}/resources/{resourceId}/security/",
        "/rest/latest/orchestrators/{orchestratorId}/locations/{locationId}/resources/{resourceId}/security/" })
@Api(value = "", description = "Location resource security operations")
public class LocationResourcesSecurityController extends AbstractLocationResourcesSecurityController {

    // Nothing here for now, this controller is just to bind another entry endpoint to common resources security controller

}


text:
package com.haulmont.cuba.gui.components.filter;

import com.google.common.base.Splitter;
import com.haulmont.cuba.client.ClientConfig;
import com.haulmont.cuba.gui.UiComponents;
import com.haulmont.cuba.gui.components.LookupField;
import com.haulmont.cuba.gui.theme.ThemeConstants;
import com.haulmont.cuba.gui.theme.ThemeConstantsManager;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;

@org.springframework.stereotype.Component(MaxResultsFieldHelper.NAME)
public class MaxResultsFieldHelper {
    public static final String NAME = "cuba_MaxResultsFieldHelper";

    @Inject
    protected UiComponents uiComponents;
    @Inject
    protected FilterHelper filterHelper;
    @Inject
    protected ThemeConstantsManager themeConstantsManager;
    @Inject
    protected ClientConfig clientConfig;

    public LookupField<Integer> createMaxResultsLookupField() {
        LookupField<Integer> maxResultsLookupField = uiComponents.create(LookupField.of(Integer.class));
        setUpMaxResultsLookupField(maxResultsLookupField);

        return maxResultsLookupField;
    }

    public LookupField<Integer> setUpMaxResultsLookupField(LookupField<Integer> maxResultsLookupField) {
        ThemeConstants theme = themeConstantsManager.getConstants();

        maxResultsLookupField.setWidth(theme.get("cuba.gui.Filter.maxResults.lookup.width"));
        filterHelper.setLookupTextInputAllowed(maxResultsLookupField, false);
        filterHelper.setLookupNullSelectionAllowed(maxResultsLookupField, false);

        List<Integer> maxResultOptions = new ArrayList<>();
        String maxResultOptionsStr = clientConfig.getGenericFilterMaxResultsOptions();
        Iterable<String> split = Splitter.on(",").trimResults().split(maxResultOptionsStr);
        for (String option : split) {
            if ("NULL".equals(option)) {
                filterHelper.setLookupNullSelectionAllowed(maxResultsLookupField, true);
            } else {
                try {
                    Integer value = Integer.valueOf(option);
                    maxResultOptions.add(value);
                } catch (NumberFormatException ignored) {
                }
            }
        }
        maxResultsLookupField.setOptionsList(maxResultOptions);

        return maxResultsLookupField;
    }
}


text:
//Write a program that finds the maximal sequence of equal elements in an array.

using System;
class MaximalSequence
{
    static void Main()
    {
        Console.Write("Enter sequence of elements:");
        string input = Console.ReadLine();
        char[] delimeters = { ' ', ',' };
        string[] seqArray = input.Split(delimeters, StringSplitOptions.RemoveEmptyEntries);

        int countSameElement = 1;
        int maxSameElement = 0;
        int sameElement = int.Parse(seqArray[0]);

        for (int i = 1; i < seqArray.Length; i++)
        {
            int current = int.Parse(seqArray[i]);
            int previous = int.Parse(seqArray[i - 1]);

            if (current == previous)
            {
                countSameElement++;
            }
            else
            {
                countSameElement = 1;
            }
            if (maxSameElement <= countSameElement)
            {
                maxSameElement = countSameElement;
                sameElement = int.Parse(seqArray[i - 1]);
            }
        }
        Console.WriteLine("Max sequence is: {0}", maxSameElement);
        for (int i = 0; i < maxSameElement; i++)
        {
            Console.Write("{0}", sameElement);
            if (i < maxSameElement - 1)
            {
                Console.Write(", ");
            }
        }
        Console.WriteLine();
    }

}


text:
package uk.ac.ebi.atlas.model;

import com.google.common.collect.ImmutableSet;
import org.junit.Test;

import java.util.Collections;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

public class BiologicalReplicateTest {

    @Test(expected = RuntimeException.class)
    public void replicateIdCantBeAnAssayId() {
        new BiologicalReplicate("Foobar", ImmutableSet.of("Foo", "Foobar", "Bar"));
    }

    @Test(expected = RuntimeException.class)
    public void replicateNeedsAtLeastOneAssayId() {
        new BiologicalReplicate("Foobar", Collections.emptySet());
    }

    @Test
    public void retrievesAssayIdsAndItself() {
        ImmutableSet<String> assayIds = ImmutableSet.of("assayId1", "assayId2", "assayId3");
        BiologicalReplicate subject = new BiologicalReplicate("replicateId", assayIds);

        assertThat(subject.biologicalReplicatesForThisDataColumn().iterator().next(), is(equalTo(subject)));
        assertThat(subject.assaysAnalyzedForThisDataColumn(), is(equalTo(assayIds)));
    }

    @Test
    public void toStringIsNice() {
        assertThat(
                new BiologicalReplicate("assay").toString(),
                is("BiologicalReplicate {id=assay}")
        );
    }
}


text:
/*	$NetBSD: xcfb.c,v 1.23.10.2 1999/04/12 21:27:06 pk Exp $	*/

/*-
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Ralph Campbell and Rick Macklem.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)xcfb.c	8.1 (Berkeley) 6/10/93
 */

/*
 * Mach Operating System
 * Copyright (c) 1991,1990,1989 Carnegie Mellon University
 * All Rights Reserved.
 *
 * Permission to use, copy, modify and distribute this software and its
 * documentation is hereby granted, provided that both the copyright
 * notice and this permission notice appear in all copies of the
 * software, derivative works or modified versions, and any portions
 * thereof, and that both notices appear in supporting documentation.
 *
 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
 * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
 * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
 *
 * Carnegie Mellon requests users of this software to return to
 *
 *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
 *  School of Computer Science
 *  Carnegie Mellon University
 *  Pittsburgh PA 15213-3890
 *
 * any improvements or extensions that they make and grant Carnegie the
 * rights to redistribute these changes.
 */
/*
 *  devGraphics.c --
 *
 *     	This file contains machine-dependent routines for the graphics device.
 *
 *	Copyright (C) 1989 Digital Equipment Corporation.
 *	Permission to use, copy, modify, and distribute this software and
 *	its documentation for any purpose and without fee is hereby granted,
 *	provided that the above copyright notice appears in all copies.
 *	Digital Equipment Corporation makes no representations about the
 *	suitability of this software for any purpose.  It is provided "as is"
 *	without express or implied warranty.
 *
 * from: Header: /sprite/src/kernel/dev/ds3100.md/RCS/devGraphics.c,
 *	v 9.2 90/02/13 22:16:24 shirriff Exp  SPRITE (DECWRL)";
 */

#include "fb.h"

#include "xcfb.h"
#include "dtop.h"
#if NXCFB > 0
#if NDTOP == 0
xcfb needs dtop device
#else

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/time.h>
#include <sys/kernel.h>
#include <sys/ioctl.h>
#include <sys/file.h>
#include <sys/errno.h>
#include <sys/proc.h>
#include <sys/mman.h>
#include <sys/malloc.h>

#include <vm/vm.h>

#include <sys/device.h>
#include <dev/tc/tcvar.h>
#include <machine/autoconf.h>
#include <mips/cpuregs.h>		/* mips cached->uncached */

#include <machine/pmioctl.h>
#include <machine/fbio.h>
#include <machine/fbvar.h>

#include <pmax/pmax/cons.h>

#include <pmax/dev/xcfbreg.h>
#include <pmax/dev/xcfbvar.h>
#include <pmax/dev/ims332.h>
#include <pmax/pmax/maxine.h>

#include <pmax/dev/dtopreg.h>

#include <pmax/dev/fbreg.h>

/*
 * These need to be mapped into user space.
 */
struct fbuaccess xcfbu;

/*
 * rcons methods and globals.
 */
struct pmax_fbtty xcfbfb;

struct fbinfo	xcfbfi;	/*XXX*/

#define CMAP_BITS	(3 * 256)		/* 256 entries, 3 bytes per. */
static u_char cmap_bits [CMAP_BITS];		/* colormap for console... */

#define XCFB_FB_SIZE 0x100000	/* size of raster (mapped into userspace) */

struct fbdriver xcfb_driver = {
	ims332_video_on,
	ims332_video_off,
	ims332InitColorMap,
	ims332GetColorMap,
	ims332LoadColorMap,
	ims332PosCursor,
	ims332LoadCursor,
	ims332CursorColor
};

/*
 * Forward references.
 */
extern u_short defCursor[32];

/*
 * Autoconfiguration data for config.new.
 * Use static-sized softc until config.old and old autoconfig
 * code is completely gone.
 */

int xcfbmatch __P((struct device *, struct cfdata *, void *));
void xcfbattach __P((struct device *, struct device *, void *));

struct cfattach xcfb_ca = {
	sizeof(struct device), xcfbmatch, xcfbattach
};

int
xcfbmatch(parent, match, aux)
	struct device *parent;
	struct cfdata *match;
	void *aux;
{
	struct tc_attach_args *ta = aux;

	/* Make sure that it's an xcfb. */
	if (!TC_BUS_MATCHNAME(ta, "PMAG-DV ")  &&
	    strcmp(ta->ta_modname, "xcfb") != 0)
		return (0);

	return (1);
}

void
xcfbattach(parent, self, aux)
	struct device *parent;
	struct device *self;
	void *aux;
{
	struct tc_attach_args *ta = aux;

	if (!xcfbinit(NULL, (caddr_t)ta->ta_addr, self->dv_unit, 0))
		return;

	/* no interrupts for XCFB */
	/*BUS_INTR_ESTABLISH(ca, xcfbintr, self->dv_unit);*/
	printf("\n");
}

/*
 * Initialization
 */
int
xcfbinit(fi, base, unit, silent)
	struct fbinfo *fi;
	caddr_t base;
	int unit;
	int silent;
{
	/*XXX*/
	/*
	 * If this device is being intialized as the console, malloc()
	 * is not yet up and we must use statically-allocated space.
	 */
	if (fi == NULL) {
		fi = &xcfbfi;	/* XXX */
  		fi->fi_cmap_bits = (caddr_t)cmap_bits;
	} else {
    		fi->fi_cmap_bits = malloc(CMAP_BITS, M_DEVBUF, M_NOWAIT);
		if (fi->fi_cmap_bits == NULL) {
			printf("cfb%d: no memory for cmap\n", unit);
			return (0);
		}
	}

	/*XXX*/
	/*
	 * Or Cached? A comment in the Mach driver suggests that the X server
	 * runs faster in cached address space, but the X server is going
	 * to blow away the data cache whenever it updates the screen, so..
	 */
	base = (char *) MIPS_PHYS_TO_KSEG1(XINE_PHYS_CFB_START);

	/* Fill in main frame buffer info struct. */
	fi->fi_unit = unit;
	fi->fi_pixels = (caddr_t)(base + VRAM_OFFSET);
	fi->fi_pixelsize = 1024 * 768;
	fi->fi_base = (caddr_t)IMS332_RESET_ADDRESS;
	fi->fi_vdac = (caddr_t)IMS332_ADDRESS;
	fi->fi_size = 0x100000;
	fi->fi_linebytes = 1024;
	fi->fi_driver = &xcfb_driver;
	fi->fi_blanked = 0;

	/* Fill in Frame Buffer Type struct. */
	fi->fi_type.fb_boardtype = PMAX_FBTYPE_XCFB;
	fi->fi_type.fb_width = 1024;
	fi->fi_type.fb_height = 768;
	fi->fi_type.fb_depth = 8;
	fi->fi_type.fb_cmsize = 256;
	fi->fi_type.fb_size = XCFB_FB_SIZE;

	/*
	 * qvss/pm-style mmap()ed event queue compatibility glue
	 */
	/*
	 * Must be in Uncached space since the fbuaccess structure is
	 * mapped into the user's address space uncached.
	 */
	fi->fi_fbu = (struct fbuaccess *)
		MIPS_PHYS_TO_KSEG1(MIPS_KSEG0_TO_PHYS(&xcfbu));

	/* This is glass-tty state but it's in the shared structure. Ick. */
	fi->fi_fbu->scrInfo.max_row = 50;
	fi->fi_fbu->scrInfo.max_col = 80;

	init_pmaxfbu(fi);

	/*
	 * Initialize old-style pmax glass-tty screen info.
	 */
	fi->fi_glasstty = &xcfbfb;

	/*XXX*/
	/* dimensions translated -15 pixels, for sprite origin? */
	fi->fi_fbu->scrInfo.max_cur_x = 1008;
	fi->fi_fbu->scrInfo.max_cur_y = 752;

	fi->fi_fbu->scrInfo.min_cur_x = -15;
	fi->fi_fbu->scrInfo.min_cur_y = -15;

	/* Initialize the RAMDAC. */
	ims332init (fi);

	/* Connect serial device(s) */
	if (tb_kbdmouseconfig(fi)) {
		printf(" (mouse/keyboard config failed)");
		return (0);
	}

	/*
	 * Connect to the raster-console pseudo-driver
	 */
	fbconnect("PMAG-DV", fi, silent);

#ifdef	fpinitialized
	fp->initialized = 1;
#endif
	return (1);
}

#endif /* NDTOP */
#endif /* NXCFB */


text:
/* Userman
   Index user documents by username.
   Value: null.
*/
function(doc) {
    if (doc.userman_doctype !== 'user') return;
    if (doc.username) emit(doc.username, null);
}


text:
#ifndef CAPU_MINIMAL_WINDOWSH_H
#define CAPU_MINIMAL_WINDOWSH_H

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#ifndef NOGDICAPMASKS
#define NOGDICAPMASKS
#endif
#ifndef NOVIRTUALKEYCODES
#define NOVIRTUALKEYCODES
#endif
#ifndef NOWINMESSAGES
#define NOWINMESSAGES
#endif
#ifndef NOWINSTYLES
#define NOWINSTYLES
#endif
#ifndef NOSYSMETRICS
#define NOSYSMETRICS
#endif
#ifndef NOMENUS
#define NOMENUS
#endif
#ifndef NOICONS
#define NOICONS
#endif
#ifndef NOKEYSTATES
#define NOKEYSTATES
#endif
#ifndef NOSYSCOMMANDS
#define NOSYSCOMMANDS
#endif
#ifndef NORASTEROPS
#define NORASTEROPS
#endif
#ifndef NOSHOWWINDOW
#define NOSHOWWINDOW
#endif
#ifndef OEMRESOURCE
#define OEMRESOURCE
#endif
#ifndef NOATOM
#define NOATOM
#endif
#ifndef NOCLIPBOARD
#define NOCLIPBOARD
#endif
#ifndef NOCOLOR
#define NOCOLOR
#endif
#ifndef NOCTLMGR
#define NOCTLMGR
#endif
#ifndef NODRAWTEXT
#define NODRAWTEXT
#endif
#ifndef NOKERNEL
#define NOKERNEL
#endif
#ifndef NONLS
#define NONLS
#endif
#ifndef NOMB
#define NOMB
#endif
#ifndef NOMEMMGR
#define NOMEMMGR
#endif
#ifndef NOMETAFILE
#define NOMETAFILE
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#ifndef NOMSG
#define NOMSG
#endif
#ifndef NOOPENFILE
#define NOOPENFILE
#endif
#ifndef NOSCROLL
#define NOSCROLL
#endif
#ifndef NOSERVICE
#define NOSERVICE
#endif
#ifndef NOSOUND
#define NOSOUND
#endif
#ifndef NOTEXTMETRIC
#define NOTEXTMETRIC
#endif
#ifndef NOWH
#define NOWH
#endif
#ifndef NOWINOFFSETS
#define NOWINOFFSETS
#endif
#ifndef NOCOMM
#define NOCOMM
#endif
#ifndef NOKANJI
#define NOKANJI
#endif
#ifndef NOHELP
#define NOHELP
#endif
#ifndef NOPROFILER
#define NOPROFILER
#endif
#ifndef NODEFERWINDOWPOS
#define NODEFERWINDOWPOS
#endif
#ifndef NOMCX
#define NOMCX
#endif

#include <windows.h>

#undef min
#undef max

#endif


text:
Tutorial 2: SCVs and Supply Depots
==================================

The goal in this tutorial will be to build scvs and supply depots.

1. Building SCVs.
2. Building Supply Depots.
3. Managing idle SCVs.

As a starting point you should have the code from the end of tutorial 1 compiling and running.
This tutorial will start where the last one left off.

Building SCVs
-------------

The library provides many events for your convenience, a big one we will use for this tutorial is
the OnUnitIdle event. This function will get called each time a unit has been built and has no orders
or the unit had orders in the previous step and currently does not.

> In both the Starcraft 2 engine and library both buildings and units are considered units and
> are represented with a Unit object.

Add the following code to your Bot class.

```C++
// In your bot class.
virtual void OnUnitIdle(const Unit* unit) final {
    switch (unit->unit_type.ToType()) {
        case UNIT_TYPEID::TERRAN_COMMANDCENTER: {
            Actions()->UnitCommand(unit, ABILITY_ID::TRAIN_SCV);
            break;
        }
        default: {
            break;
        }
    }
}
```

As you can see we are going to try to build an SCV with the idle unit if it is a Command Center.

> The UNIT_TYPEID enum holds the ids of common units you are likely to find in 1v1 matches.
> Feel free to look at sc2_typeenums.h to see a list of units and their corresponding id.

Building Supply Depots
----------------------

Compile and run your bot now. You will see the Command Center making scvs up until the supply cap.
That seems pretty good! We just need to build some supply depots now, lets replace the code in OnStep
with the following.

```C++
virtual void OnStep() {
    TryBuildSupplyDepot();
}
```

Implement TryBuildSupplyDepot and TryBuildStructure as functions of our bot class.

```C++
bool TryBuildStructure(ABILITY_ID ability_type_for_structure, UNIT_TYPEID unit_type = UNIT_TYPEID::TERRAN_SCV) {
    const ObservationInterface* observation = Observation();

    // If a unit already is building a supply structure of this type, do nothing.
    // Also get an scv to build the structure.
    const Unit* unit_to_build = nullptr;
    Units units = observation->GetUnits(Unit::Alliance::Self);
    for (const auto& unit : units) {
        for (const auto& order : unit->orders) {
            if (order.ability_id == ability_type_for_structure) {
                return false;
            }
        }

        if (unit->unit_type == unit_type) {
           unit_to_build = unit;
        }
    }

    float rx = GetRandomScalar();
    float ry = GetRandomScalar();

    Actions()->UnitCommand(unit_to_build,
        ability_type_for_structure,
        Point2D(unit_to_build->pos.x + rx * 15.0f, unit_to_build->pos.y + ry * 15.0f));

    return true;
}

bool TryBuildSupplyDepot() {
    const ObservationInterface* observation = Observation();

    // If we are not supply capped, don't build a supply depot.
    if (observation->GetFoodUsed() <= observation->GetFoodCap() - 2)
        return false;

    // Try and build a depot. Find a random SCV and give it the order.
    return TryBuildStructure(ABILITY_ID::BUILD_SUPPLYDEPOT);
}
```

Compile and run your bot now. It's mining and building supply depots, it's almost ready for ladder!
You'll notice when the SCV is done building a supply depot it sits idle, how useless. Lets fix that now.

Managing Idle SCVs
------------------

We have already hooked into the on idle event for building SCVs, we can use that same function to manage idle ones.
Refactor your OnUnitIdle function with the following.

```C++
virtual void OnUnitIdle(const Unit* unit) final {
    switch (unit->unit_type.ToType()) {
        case UNIT_TYPEID::TERRAN_COMMANDCENTER: {
            Actions()->UnitCommand(unit, ABILITY_ID::TRAIN_SCV);
            break;
        }
        case UNIT_TYPEID::TERRAN_SCV: {
            const Unit* mineral_target = FindNearestMineralPatch(unit->pos);
            if (!mineral_target) {
                break;
            }
            Actions()->UnitCommand(unit, ABILITY_ID::SMART, mineral_target);
            break;
        }
        default: {
            break;
        }
    }
}
```

> The ability type of SMART is equivalent to a right click in Starcraft 2 when you have a unit selected.

Now we just need to implement FindNearestMineralPatch and we can fix our lazy SCV.

```C++
const Unit* FindNearestMineralPatch(const Point2D& start) {
    Units units = Observation()->GetUnits(Unit::Alliance::Neutral);
    float distance = std::numeric_limits<float>::max();
    const Unit* target = nullptr;
    for (const auto& u : units) {
        if (u->unit_type == UNIT_TYPEID::NEUTRAL_MINERALFIELD) {
            float d = DistanceSquared2D(u->pos, start);
            if (d < distance) {
                distance = d;
                target = u;
            }
        }
    }
    return target;
}

```

Exercises
---------

> These exercises are very optional, so feel free to move onto the next tutorial.
> Otherwise, they act as a fun way to discover more about the API.

1. As you build more scvs you'll want to start building supply depots at a higher rate. Try modifying the code to build multiple
supply depots instead of just 1 at a time.
2. (Challenging) Build two refineries and start mining gas. You can use code similar to FindNearestMineralPatch to
find a geyser. You'll then want to detect when the refinery is either created or becomes idle and begin gathering gas with 3 scvs.

Full Source Code
----------------

```C++
#include <sc2api/sc2_api.h>

#include <iostream>

using namespace sc2;

class Bot : public Agent {
public:
    virtual void OnGameStart() final {
        std::cout << "Hello, World!" << std::endl;
    }

    virtual void OnStep() final {
        TryBuildSupplyDepot();
    }

    virtual void OnUnitIdle(const Unit* unit) final {
        switch (unit->unit_type.ToType()) {
            case UNIT_TYPEID::TERRAN_COMMANDCENTER: {
                Actions()->UnitCommand(unit, ABILITY_ID::TRAIN_SCV);
                break;
            }
            case UNIT_TYPEID::TERRAN_SCV: {
                const Unit* mineral_target = FindNearestMineralPatch(unit->pos);
                if (!mineral_target) {
                    break;
                }
                Actions()->UnitCommand(unit, ABILITY_ID::SMART, mineral_target);
                break;
            }
            default: {
                break;
            }
        }
    }
private:
    bool TryBuildStructure(ABILITY_ID ability_type_for_structure, UNIT_TYPEID unit_type = UNIT_TYPEID::TERRAN_SCV) {
        const ObservationInterface* observation = Observation();

        // If a unit already is building a supply structure of this type, do nothing.
        // Also get an scv to build the structure.
        const Unit* unit_to_build = nullptr;
        Units units = observation->GetUnits(Unit::Alliance::Self);
        for (const auto& unit : units) {
            for (const auto& order : unit->orders) {
                if (order.ability_id == ability_type_for_structure) {
                    return false;
                }
            }

            if (unit->unit_type == unit_type) {
                unit_to_build = unit;
            }
        }

        float rx = GetRandomScalar();
        float ry = GetRandomScalar();

        Actions()->UnitCommand(unit_to_build,
            ability_type_for_structure,
            Point2D(unit_to_build->pos.x + rx * 15.0f, unit_to_build->pos.y + ry * 15.0f));

        return true;
    }

    bool TryBuildSupplyDepot() {
        const ObservationInterface* observation = Observation();

        // If we are not supply capped, don't build a supply depot.
        if (observation->GetFoodUsed() <= observation->GetFoodCap() - 2)
            return false;

        // Try and build a depot. Find a random SCV and give it the order.
        return TryBuildStructure(ABILITY_ID::BUILD_SUPPLYDEPOT);
    }

    const Unit* FindNearestMineralPatch(const Point2D& start) {
        Units units = Observation()->GetUnits(Unit::Alliance::Neutral);
        float distance = std::numeric_limits<float>::max();
        const Unit* target = nullptr;
        for (const auto& u : units) {
            if (u->unit_type == UNIT_TYPEID::NEUTRAL_MINERALFIELD) {
                float d = DistanceSquared2D(u->pos, start);
                if (d < distance) {
                    distance = d;
                    target = u;
                }
            }
        }
        return target;
    }
};

int main(int argc, char* argv[]) {
    Coordinator coordinator;
    coordinator.LoadSettings(argc, argv);

    Bot bot;
    coordinator.SetParticipants({
        CreateParticipant(Race::Terran, &bot),
        CreateComputer(Race::Zerg)
    });

    coordinator.LaunchStarcraft();
    coordinator.StartGame(sc2::kMapBelShirVestigeLE);

    while (coordinator.Update()) {
    }

    return 0;
}
```


text:
COMPONENT=AppC
include $(MAKERULES)


text:
title: Getting Started
page_title: Getting Started - WinForms MultiColumnComboBox
description: WinForms MultiColumnComboBox is a special case of combo box control with RadGridView integrated in its drop-down.
slug: winforms/multicolumncombobox/getting-started
tags: multicolumncombobox, design time
published: True
position: 3
---

# Getting Started

The following tutorial demonstrates how to setup **RadMultiColumnComboBox** and retrieve the selected text and image.

1\. Add a **RadMultiColumnComboBox** and a **RadStatusStrip** to a **RadForm**.
2\. By using the Visual Studio *Properties* grid and the *Data Source Configuration Wizard*, set the **DataSource**, **ValueMember** and **DisplayMember** properties of **RadMultiColumnComboBox**. Thus, **RadMultiColumnComboBox** will be bound to the Northwind.Employees table.

![multicolumncombobox-getting-started 001](images/multicolumncombobox-getting-started001.png)

3\. Add a **RadImageButtonElement** and a **RadLabelElement** to the **RadStatusStrip**.
4\. In the Visual Studio *Properties* grid, select the **Events** tab and double click the **SelectedIndexChanged** event in order to generate an event handler.

{{source=..\SamplesCS\MultiColumnComboBox\MCCBgettingStarted.cs region=GettingStarted}}
{{source=..\SamplesVB\MultiColumnComboBox\MCCBgettingStarted.vb region=GettingStarted}}

````C#

private void radMultiColumnComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (this.radMultiColumnComboBox1.SelectedIndex > -1)
    {
        Image img = GetImageFromBytes(this.radMultiColumnComboBox1.EditorControl.CurrentRow.Cells["Photo"].Value as byte[]);
        this.radImageButtonElement1.Image = img.GetThumbnailImage(32, 32, null, IntPtr.Zero);
        this.radLabelElement1.Text = this.radMultiColumnComboBox1.Text;
    }
}

private Image GetImageFromBytes(byte[] bytes)
{
    Image result = null;
    System.IO.MemoryStream stream = null;
    try
    {
        stream = new System.IO.MemoryStream(bytes, 78, bytes.Length - 78);
        result = Image.FromStream(stream);
    }
    catch
    {
        try
        {
            stream = new System.IO.MemoryStream(bytes, 0, bytes.Length);
            result = Image.FromStream(stream);
        }
        catch
        {
            result = null;
        }
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }
    return result;
}

````
````VB.NET
Private Sub RadMultiColumnComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RadMultiColumnComboBox1.SelectedIndexChanged
    If Me.RadMultiColumnComboBox1.SelectedIndex > -1 Then
        Dim img As Image = GetImageFromBytes(TryCast(Me.RadMultiColumnComboBox1.EditorControl.CurrentRow.Cells("Photo").Value, Byte()))
        Me.RadImageButtonElement1.Image = img.GetThumbnailImage(32, 32, Nothing, IntPtr.Zero)
        Me.RadLabelElement1.Text = Me.RadMultiColumnComboBox1.Text
    End If
End Sub
Private Function GetImageFromBytes(bytes As Byte()) As Image
    Dim result As Image = Nothing
    Dim stream As System.IO.MemoryStream = Nothing
    Try
        stream = New System.IO.MemoryStream(bytes, 78, bytes.Length - 78)
        result = Image.FromStream(stream)
    Catch
        Try
            stream = New System.IO.MemoryStream(bytes, 0, bytes.Length)
            result = Image.FromStream(stream)
        Catch
            result = Nothing
        End Try
    Finally
        If stream IsNot Nothing Then
            stream.Close()
        End If
    End Try
    Return result
End Function

````

{{endregion}}

5\. Open the **Property Builder** by using the **Smart Tag** and uncheck some of the columns in order to control which columns to be visible.
6\. Press `F5` to run the application and change the selection in **RadMultiColumnComboBox**.

![multicolumncombobox-getting-started 002](images/multicolumncombobox-getting-started002.gif)

# See Also

* [Design Time]({%slug winforms/multicolumncombobox/design-time%})
* [Data Binding]({%slug winforms/multicolumncombobox/databinding%})


text:
<!DOCTYPE html>

<textArea th:replace="fragment/common :: questionTemplate"/>

                <form th:action="@{/questions/Wellness}" method="POST">

                    <input id="timeOnPage" name="timeOnPage" type="hidden"/>

All things considered, how satisfied are you with your life as a whole?

                        <input id="slider"  type="text" name="satisfaction" required ="true"/>

                            <input id="slider-enabled" type="checkbox" name="satisfaction" value="555"/>
                            Prefer not to answer

                        <button type="submit"> Continue</button>

                </form>


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

namespace ManaPHP\Commands;

use ManaPHP\Cli\Command;
use ManaPHP\Helper\LocalFS;

class ExcelCommand extends Command
{
    /**
     * generate ods from content.xml file
     *
     * @param string $file ods content file path
     *
     * @return void
     */
    public function odsAction(string $file): void
    {
        if (LocalFS::dirExists($file)) {
            $file .= '/content.xml';
        }

        $content = LocalFS::fileGet($file);

        $content = preg_replace('#table:formula="[^\"]+" #', '', $content);
        $content = preg_replace('#table:number-rows-repeated="\d+"#', 'table:number-rows-repeated="100"', $content);
        $content = preg_replace('#office:value-type="float" office:value=".*?" #', '', $content);

        LocalFS::filePut($file . '.xml', $content);
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer;

namespace Microsoft.CodeAnalysis.EditorFeatures.Cocoa.Lsp;

/// <summary>
/// Implementation of the workspace registration service exported to be included in the VSMac composition.
/// </summary>
[Export(typeof(LspWorkspaceRegistrationService)), Shared]
internal class VSMacWorkspaceRegistrationService : LspWorkspaceRegistrationService
{
    [ImportingConstructor]
    [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
    public VSMacWorkspaceRegistrationService()
    {
    }

    /// <summary>
    /// VSMac uses <see cref="WorkspaceKind.Host"/> for their MonoDevelopWorkspace.
    /// </summary>
    public override string GetHostWorkspaceKind() => WorkspaceKind.Host;
}


text:
package protocgen

import protocbridge.ProtocCodeGenerator
import com.google.protobuf.ExtensionRegistry
import com.google.protobuf.CodedInputStream
import com.google.protobuf.compiler.PluginProtos.CodeGeneratorRequest
import com.google.protobuf.compiler.PluginProtos.CodeGeneratorResponse
import com.google.protobuf.Descriptors.FileDescriptor
import com.google.protobuf.compiler.PluginProtos
import com.google.protobuf.DescriptorProtos.FileDescriptorProto

/** CodeGenApp provides a higher-level Scala API to build protoc code generators.
  *
  * As a code generator author, you need to optionally provide a `registerExtensions`
  * function to register any extensions needed for parsing the CodeGeneratorRequest.
  *
  * The implement the function process that takes a CodeGenRequest and returns a
  * CodeGenResponse. These classes provides higher-level, idiomatic access to the
  * request and response used by protoc.
  */
trait CodeGenApp extends ProtocCodeGenerator {
  def registerExtensions(registry: ExtensionRegistry): Unit = {}

  def process(request: CodeGenRequest): CodeGenResponse

  final def main(args: Array[String]): Unit = {
    System.out.write(run(CodedInputStream.newInstance(System.in)))
  }

  final override def run(req: Array[Byte]): Array[Byte] =
    run(CodedInputStream.newInstance(req))

  private def errorMessage(t: Throwable) = {
    val sw = new java.io.StringWriter()
    t.printStackTrace(new java.io.PrintWriter(sw, true))
    sw.toString
  }

  final def run(input: CodedInputStream): Array[Byte] = {
    try {
      val registry = ExtensionRegistry.newInstance()
      registerExtensions(registry)
      val request = CodeGenRequest(
        CodeGeneratorRequest.parseFrom(input, registry)
      )
      process(request).toCodeGeneratorResponse.toByteArray()
    } catch {
      case t: Throwable =>
        CodeGeneratorResponse
          .newBuilder()
          .setError(errorMessage(t))
          .build()
          .toByteArray
    }
  }
}


text:
export { AngularMultiSelect } from './multiselect.component';
export { ClickOutsideDirective } from './clickOutside';
export { ListFilterPipe } from './list-filter';
export { Item } from './menu-item';
export { TemplateRenderer } from './menu-item';
export { VirtualScrollerComponent } from './virtual-scroll/virtual-scroll';
export { AngularMultiSelectModule } from './multiselect.component';


text:
external help file: Microsoft.Azure.Commands.RedisCache.dll-Help.xml
Module Name: AzureRM.RedisCache
ms.assetid: 2EA765B8-D82B-4789-8F10-88F79BDF44D0
online version: https://docs.microsoft.com/en-us/powershell/module/azurerm.rediscache/remove-azurermrediscachepatchschedule
schema: 2.0.0
---

# Remove-AzureRmRedisCachePatchSchedule

## SYNOPSIS
Removes the patch schedule.

## SYNTAX

```
Remove-AzureRmRedisCachePatchSchedule [-ResourceGroupName <String>] -Name <String> [-PassThru]
 [-DefaultProfile <IAzureContextContainer>] [-WhatIf] [-Confirm] [<CommonParameters>]
```

## DESCRIPTION
The **Remove-AzureRmRedisCachePatchSchedule** cmdlet removes the patch schedule from a cache in Azure Redis Cache.

## EXAMPLES

### Example 1: Remove the patch schedule
```
PS C:\>Remove-AzureRmRedisCachePatchSchedule -ResourceGroupName "ResourceGroup13" -Name "RedisCache06"
```

This command removes the patch schedule from the cache named RedisCache06.

## PARAMETERS

### -DefaultProfile
The credentials, account, tenant, and subscription used for communication with azure.

```yaml
Type: Microsoft.Azure.Commands.Common.Authentication.Abstractions.IAzureContextContainer
Parameter Sets: (All)
Aliases: AzureRmContext, AzureCredential

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -Name
Specifies the name of a cache.

```yaml
Type: System.String
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -PassThru
{{Fill PassThru Description}}

```yaml
Type: System.Management.Automation.SwitchParameter
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -ResourceGroupName
Specifies the name of the resource group which contains the cache.

```yaml
Type: System.String
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -Confirm
Prompts you for confirmation before running the cmdlet.

```yaml
Type: System.Management.Automation.SwitchParameter
Parameter Sets: (All)
Aliases: cf

Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```

### -WhatIf
Shows what would happen if the cmdlet runs.
The cmdlet is not run.

```yaml
Type: System.Management.Automation.SwitchParameter
Parameter Sets: (All)
Aliases: wi

Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

### System.String

## OUTPUTS

### System.Boolean

## NOTES
* Keywords: azure, azurerm, arm, resource, management, manager, redis, cache, web, webapp, website

## RELATED LINKS

[Get-AzureRmRedisCachePatchSchedule](./Get-AzureRmRedisCachePatchSchedule.md)

[New-AzureRmRedisCachePatchSchedule](./New-AzureRmRedisCachePatchSchedule.md)

[New-AzureRmRedisCacheScheduleEntry](./New-AzureRmRedisCacheScheduleEntry.md)


text:
package im.actor.messenger.app.fragment.chat.adapter;

import android.view.View;

import im.actor.messenger.R;
import im.actor.messenger.app.fragment.chat.MessagesAdapter;
import im.actor.core.entity.Message;

public class UnsupportedHolder extends TextHolder {

    private String text;

    public UnsupportedHolder(MessagesAdapter fragment, View itemView) {
        super(fragment, itemView, false);

        text = fragment.getMessagesFragment().getResources().getString(R.string.chat_unsupported);
    }

    @Override
    protected void bindData(Message message, boolean isUpdated) {
        bindRawText(text, message, true);
    }
}


text:
PACKAGE="gateone"
DNAME="GateOne"

# Others
INSTALL_DIR="/usr/local/${PACKAGE}"
PYTHON_DIR="/usr/local/python"
PATH="${INSTALL_DIR}/bin:${INSTALL_DIR}/env/bin:${PYTHON_DIR}/bin:/usr/local/bin:/bin:/usr/bin:/usr/syno/bin"
PYTHON="${INSTALL_DIR}/env/bin/python"
VIRTUALENV="${PYTHON_DIR}/bin/virtualenv"
CFG_FILE="${INSTALL_DIR}/var/config.ini"
TMP_DIR="${SYNOPKG_PKGDEST}/../../@tmp"

preinst ()
{
    exit 0
}

postinst ()
{
    # Link
    ln -s ${SYNOPKG_PKGDEST} ${INSTALL_DIR}

    # Create a Python virtualenv
    ${VIRTUALENV} --system-site-packages ${INSTALL_DIR}/env > /dev/null

    # Install the bundle
    ${INSTALL_DIR}/env/bin/pip install -U -b ${INSTALL_DIR}/var/build ${INSTALL_DIR}/share/requirements.pybundle > /dev/null
    rm -fr ${INSTALL_DIR}/var/build

    PATH=${PATH} ${PYTHON} ${INSTALL_DIR}/share/GateOne/setup.py install --prefix=${INSTALL_DIR}

    exit 0
}

preuninst ()
{
    exit 0
}

postuninst ()
{
    # Remove link
    rm -f ${INSTALL_DIR}

    exit 0
}

preupgrade ()
{
    # Save some stuff
    rm -fr ${TMP_DIR}/${PACKAGE}
    mkdir -p ${TMP_DIR}/${PACKAGE}
    mv ${INSTALL_DIR}/var ${TMP_DIR}/${PACKAGE}/

    exit 0
}

postupgrade ()
{
    # Restore some stuff
    rm -fr ${INSTALL_DIR}/var
    mv ${TMP_DIR}/${PACKAGE}/var ${INSTALL_DIR}/
    rm -fr ${TMP_DIR}/${PACKAGE}

    exit 0
}


text:
namespace SPS.Model
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Data;
    using SPS.Model.AutoGen;
    using System.Xml;
    using System.IO;
    using CS.SL.Common.Extensions;
    using System.Runtime.Serialization;
    /// <summary>
    /// ContentIndex
    /// </summary>
    public class ContentIndexInfo : A_ContentIndexInfo
    {

        [DataMember]
        public new MediaType MediaType { get; set; }
        #region OnReadDB
        protected override bool OnReadDB(IDataRecord reader, int index)
        {
            ///TODO: override base Read DB
            if (string.Equals("MediaType", reader.GetName(index), StringComparison.CurrentCultureIgnoreCase))
            {
                if (reader[index] != System.DBNull.Value)
                {
                    this.MediaType = (MediaType)reader[index];
                }
                return true;
            }
            return false;
        }
        #endregion

        #region XML
        public string ToXml()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<entry>");
            sb.AppendFormat("<id>{0}</id>", this.IndexID.ToString());
            sb.AppendFormat("<title type=\"text\">{0}</title>", this.Title.EscapeXml());
            sb.AppendFormat("<updated>{0}</updated>", this.IndexTime.ToString());
            sb.AppendFormat("<link rel=\"self\" href=\"{0}\" />", this.Link.EscapeXml());
            //sb.AppendFormat("<link rel=\"alternate\" href=\"{0}\" />", this.Link.EscapeXml());
            if (!string.IsNullOrWhiteSpace(this.ThumbUri))
            {
                sb.AppendFormat("<link rel=\"enclosure\" type=\"thumbnail\" title=\"{1}\" href=\"{0}\" />", this.ThumbUri.EscapeXml(), this.ThumbTips.EscapeXml());
            }
            sb.AppendFormat("<content type=\"text\">{0}</content>", this.Summary);
            sb.AppendFormat("<vf:media-type xmlns:vf=\"http://vf.pscsport.com/schemas/search\">{0}</vf:media-type>", this.MediaType.ToString());
            sb.Append("</entry>");
            return sb.ToString();
        }
        public void ParseXml(XmlReader reader)
        {
            while (!reader.EOF)
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    if (String.Equals(reader.Name, "author"))
                    {
                        this.Author = reader.ReadElementContentAsString();
                    }
                    if (String.Equals(reader.Name, "entry"))
                    {
                        this.ContentID = reader.GetAttribute("id").ToInt();
                        reader.Read();
                    }
                    if (String.Equals(reader.Name, "link") && string.Equals(reader.GetAttribute("type"), "thumbnail", StringComparison.OrdinalIgnoreCase))
                    {
                        this.ThumbUri = reader.GetAttribute("href");
                        this.ThumbTips = reader.GetAttribute("title");
                        reader.Read();

                    }
                    if (String.Equals(reader.Name, "link") && string.Equals(reader.GetAttribute("rel"), "self", StringComparison.OrdinalIgnoreCase))
                    {
                        this.Link = reader.GetAttribute("href");
                        reader.Read();

                    }
                    if (String.Equals(reader.Name, "content"))
                    {
                        this.MainContent = reader.ReadElementContentAsString();
                    }
                    if (String.Equals(reader.Name, "type"))
                    {
                        this.MediaType = (MediaType)reader.ReadElementContentAsInt();
                    }
                    if (String.Equals(reader.Name, "publisher"))
                    {
                        this.Publisher = reader.ReadElementContentAsString();
                    }
                    if (String.Equals(reader.Name, "summary"))
                    {
                        this.Summary = reader.ReadElementContentAsString();
                    }
                    if (String.Equals(reader.Name, "title"))
                    {
                        this.Title = reader.ReadElementContentAsString();
                    }
                }
                else
                {
                    reader.Read();
                }
            }
        }
        public void ParseXml(string xmlString)
        {
            using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
            {
                ParseXml(reader);
            }
        }
        #endregion
    }
    public enum MediaType
    {
        Article=0,
        Video=1
    }
}


text:
'use strict';

/**
 * @class
 * @example
 * eventApi.request('messages.post')
 *         .data({
 *             message: 'test'
 *          })
 *         .timeout(300)
 *         .send()
 *         .then((responseEvent) => {
 *             // ...
 *         })
 *         .catch((error) => {
 *             // ...
 *         })
 */
class RequestChain {

    /**
     * @param  {String} name
     * @param  {EventApi} eventApi
     */
    constructor(name, eventApi, batchRequestChain) {
        this._event = {
            name: name
        };

        this._timeout = null;

        this._eventApi = null;
        this._batchRequestChain = null;

        if (eventApi) {
            this._eventApi = eventApi;
        }

        if (batchRequestChain) {
            this._batchRequestChain = batchRequestChain;
        }
    }

    /**
     * set event data
     * @param  {Object} data
     * @return {this}
     */
    data(data) {
        this._event.data = data;
        return this;
    }

    /**
     * set timeout for event response
     *
     * @param  {Number} timeout in ms
     * @return {this}
     */
    timeout(timeout) {
        this._timeout = timeout;
        return this;
    }

    /**
     * get event object
     *
     * @return {EventObject}
     */
    get() {
        return this._event;
    }

    /**
     * emit event to Eman
     *
     * @return {Promise}
     */
    send() {
        if (this._batchRequestChain) {
            throw new Error('RequestChain created in batch mode use add method');
        }

        return this._send();
    }

    /**
     * @private
     *
     * @return {Promise}
     */
    _send() {
        return this._eventApi.sendRequest(this._event, this._timeout)
    }

    /**
     * using only in batchRequest
     */
    add() {
        if (this._batchRequestChain) {
            this._batchRequestChain.add(this._send());
            return this._batchRequestChain;
        } else {
            throw new Error('RequestChain not in BatchRequestChain, dont use method "add"');
        }
    }

}

module.exports = RequestChain;


text:
import tweepy
import datetime

# Authentication:
consumer_key = '********'
consumer_secret = '********'
access_token = '********'
access_token_secret = '********'

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

def add_tomori_nao(status_object):
    splited_array = status_object.text.split()
    url = 'https://twitter.com/kokodeikku_bot/status/' + str(status_object.id)
    return splited_array[1] + ' ' + splited_array[2] + ' ' + u'友利奈緒' + url.decode('utf8')

recent_tweets = api.user_timeline('kokodeikku_bot')
new_tweets = []

now_minute = datetime.datetime.now().minute

for i in recent_tweets:
    post_minute = i.created_at.minute
    if post_minute == now_minute - 1:
        tweet = add_tomori_nao(i)
        api.update_status(status=tweet.encode('utf8'))
    elif post_minute < now_minute - 1:
        break


text:
package acceptance;

import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;

/**
 * @author Stefan Penndorf <stefan@cyphoria.net>
 */
@RunWith(Cucumber.class)
@Cucumber.Options(format = {"pretty", "html:target/cucumber"}, monochrome = false, features = "test/resources/features" , tags = "@current")
public class CurrentAcceptanceTests {
}


text:
// Copyright 2000-2018 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 git4idea.ui;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.ChangeListAdapter;
import com.intellij.openapi.vcs.changes.ChangeListManager;
import com.intellij.openapi.vcs.changes.RemoteRevisionsCache;
import com.intellij.openapi.vcs.changes.actions.RollbackDialogAction;
import com.intellij.openapi.vcs.changes.ui.ChangesBrowserBase;
import com.intellij.openapi.vcs.changes.ui.RemoteStatusChangeNodeDecorator;
import com.intellij.openapi.vcs.changes.ui.TreeModelBuilder;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.update.MergingUpdateQueue;
import com.intellij.util.ui.update.Update;
import org.jetbrains.annotations.NotNull;

import javax.swing.tree.DefaultTreeModel;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * {@link ChangesBrowser} extension with Rollback/Revert action added to the toolbar.
 * After the revert completes, the changes list is automatically refreshed according to the actual changes
 * retrieved from the {@link ChangeListManager}.
 */
public class ChangesBrowserWithRollback extends ChangesBrowserBase implements Disposable {
  private final Set<Change> myOriginalChanges;

  public ChangesBrowserWithRollback(@NotNull Project project, @NotNull List<Change> changes) {
    super(project, false, true);
    myOriginalChanges = new HashSet<>(changes);

    new RollbackDialogAction().registerCustomShortcutSet(this, null);

    ChangeListManager.getInstance(myProject).addChangeListListener(new MyChangeListListener(), this);
    init();

    myViewer.rebuildTree();
  }

  @Override
  public void dispose() {
  }

  @NotNull
  @Override
  protected List<AnAction> createToolbarActions() {
    return ContainerUtil.append(
      super.createToolbarActions(),
      new RollbackDialogAction()
    );
  }

  @NotNull
  @Override
  protected List<AnAction> createPopupMenuActions() {
    return ContainerUtil.append(
      super.createPopupMenuActions(),
      new RollbackDialogAction()
    );
  }

  @NotNull
  @Override
  protected DefaultTreeModel buildTreeModel() {
    Collection<Change> allChanges = ChangeListManager.getInstance(myProject).getAllChanges();
    List<Change> newChanges = ContainerUtil.filter(allChanges, myOriginalChanges::contains);

    RemoteStatusChangeNodeDecorator decorator = RemoteRevisionsCache.getInstance(myProject).getChangesNodeDecorator();
    return TreeModelBuilder.buildFromChanges(myProject, getGrouping(), newChanges, decorator);
  }

  private class MyChangeListListener extends ChangeListAdapter {
    @NotNull private final MergingUpdateQueue myUpdateQueue =
      new MergingUpdateQueue("ChangesBrowserWithRollback", 300, true,
                             ChangesBrowserWithRollback.this, ChangesBrowserWithRollback.this);

    private void doUpdate() {
      myUpdateQueue.queue(new Update("update") {
        @Override
        public void run() {
          myViewer.rebuildTree();
        }
      });
    }

    @Override
    public void changeListsChanged() {
      doUpdate();
    }
  }
}


text:
The Map of Life is a web application that integrates information about species distributions in an effort to support global understanding of the world's biodiversity. The resulting product will provide access to species distribution maps and a a set of tools for querying, accessing, downloading, and summarizing them.

![](http://i.imgur.com/R4WEC.jpg)

![](http://i.imgur.com/Qx869.jpg)

# Implementation

The application rides on the following projects:

1. [CartoDB](https://github.com/vizzuality/cartodb) - An open source tool for accessing and visualizing geospatial data on the web.
2. [Google Earth Engine](http://earthengine.google.org) - A platform for detecting changes, mapping trends, and quantifying differences on the earth's surface.
3. [Google App Engine](http://code.google.com/appengine) - A scalable application hosting service.

# Contributors

Here's [the list](https://github.com/MapofLife/MOL/contributors) of contributors.


text:
using System.Data.Entity.ModelConfiguration;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace AdventureWorksModel.Mapping
{
    public class CurrencyMap : EntityTypeConfiguration<Currency>
    {
        public CurrencyMap()
        {
            // Primary Key
            HasKey(t => t.CurrencyCode);

            // Properties
            Property(t => t.CurrencyCode)
                .IsRequired()
                .IsFixedLength()
                .HasMaxLength(3);

            Property(t => t.Name)
                .IsRequired()
                .HasMaxLength(50);

            // Table & Column Mappings
            ToTable("Currency", "Sales");
            Property(t => t.CurrencyCode).HasColumnName("CurrencyCode");
            Property(t => t.Name).HasColumnName("Name");
            Property(t => t.ModifiedDate).HasColumnName("ModifiedDate").IsConcurrencyToken(false);
        }
    }

    public static partial class Mapper
    {
        public static void Map(this EntityTypeBuilder<Currency> builder)
        {
            builder.HasKey(t => t.CurrencyCode);

            // Properties
            builder.Property(t => t.CurrencyCode)
                   .IsRequired()
                   .IsFixedLength()
                   .HasMaxLength(3);

            builder.Property(t => t.Name)
                   .IsRequired()
                   .HasMaxLength(50);

            // Table & Column Mappings
            builder.ToTable("Currency", "Sales");
            builder.Property(t => t.CurrencyCode).HasColumnName("CurrencyCode");
            builder.Property(t => t.Name).HasColumnName("Name");
            builder.Property(t => t.ModifiedDate).HasColumnName("ModifiedDate").IsConcurrencyToken(false);
        }
    }
}


text:
/**
 * Created by Logos on 2017-06-05.
 */
// Load the http module to create an http server.
var http = require('http');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.end("Hello World deploy test\n");
});

// Listen on port 8000, IP defaults to 127.0.0.1
const port = process.env.PORT || 5000
server.listen(port);

// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:/"+port);


text:
using namespace LEARNER;

namespace BINARY {

  template <bool is_learn>
  void predict_or_learn(float&, learner& base, example& ec) {
    if (is_learn)
      base.learn(ec);
    else
      base.predict(ec);

    if ( ec.l.simple.prediction > 0)
      ec.l.simple.prediction = 1;
    else
      ec.l.simple.prediction = -1;

    if (ec.l.simple.label == ec.l.simple.prediction)
      ec.loss = 0.;
    else
      ec.loss = ec.l.simple.weight;
  }

  learner* setup(vw& all, po::variables_map& vm)
  {//parse and set arguments
    all.sd->binary_label = true;
    //Create new learner
    learner* ret = new learner(NULL, all.l);
    ret->set_learn<float, predict_or_learn<true> >();
    ret->set_predict<float, predict_or_learn<false> >();
    return ret;
  }
}


text:
Got tired of building a whole application just for making static sites non-redundant?  There's an app for that, It's fairly simple to use and takes away the fiddly bits.

Moving on, let's get into it all.

How to use
-------------------------

Basic HTML files like `name.html` will be rendered as [Mustache](http://mustache.github.io/) templates when `example.com/name` is requested. Files ending in `name.php` will be `required`. It's expected that those PHP pages will return their content as a string.

Error files will also be looked for in the pages directory; to add a custom 404 page, for example, make `pages/404.html`.

If you put a config.php alongside the index.php, the parameters in the config will be passed along to the template. Note that you should *not* use this for data operations. Instead, make a PHP page than renders a template passing in the data.

This is *not* made to be an MVC replacement, just a simple system for easily making static websites sane.

The application is based on the [Slim](http://www.slimframework.com/) framework.

Download links!
-------------------------------
Versions will be listed here when they are released/archived.

Thanking people for stuff
------------------------

This is a list of people who helped somehow with the project:

    Name	Contribution	Twitter Handle

    Connor	Built it all.
@ConnorPeet

    Andrew	Contributor
@CypherServers

    Jonathan	Fixed the bloody README ;)
@JFKingsley

Licensing
------------
This project is licensed under the MIT license so use it how you want, just don't sue me, and we can all be happy.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ann. Rep. N. Y. St. Mus. nat. Hist. 53: 949 (1901)

#### Original name
Pleurotus minutus Peck

### Remarks
null