text:
import re
import time
import psycopg2

from scrapy.spiders import CrawlSpider
from scrapy.selector import Selector
from scrapy.loader import ItemLoader
from scrapy.http import Request

from LjSpider.items import *
from LjSpider.Db.Postgresql import *

class DealCountSpider(CrawlSpider):
    name = 'lj_get_count2'
    start_urls = [
        'https://nj.lianjia.com/chengjiao/'
    ]
    custom_settings = {
        # 'JOBDIR': 'crawls/lj_get_deal-1000-5000',
        # 'LOG_FILE': 'logs/lj_esf_transaction.log',
        'DOWNLOADER_MIDDLEWARES':{
            # 'LjSpider.middlewares.ProxyMiddleware': 202,
        },
        'ITEM_PIPELINES':{
        #    'LjSpider.pipelines.InsertPostgresqlPipeline': 300,
        #    'LjSpider.pipelines.JsonPipeline': 301,
        }
    }

    def start_requests(self):
        deal_new = Postgresql().query_by_sql('''select co.id,co.cn_name,co.route
                                                from lj_district d,lj_community co
                                                where d.id=co.district_id and d.city_id=3
                                        ''')

        for c_id, name, route in deal_new:
            yield Request(
                self.start_urls[0] + route + '/',
                meta={'id': c_id, 'route': route, 'name': name},
                callback=self.get_count2,
                dont_filter=True
            )

    def get_count2(self,response):
        count = Selector(response).xpath('//*[@class="total fl"]//span/text()').extract_first().strip()
        page = Selector(response).xpath('//*[@class="page-box house-lst-page-box"]/@page-data').extract_first()
        if page:
            page = eval(page)['totalPage']
        item = DealNewCountItem()
        item['name']         = response.request.meta['name']
        item['route']        = response.request.meta['route']
        item['count']        = str(count)
        item['page']         = str(page)
        item['url']          = response.url
        item['community_id'] = response.request.meta['id']
        yield item


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

import java.util.List;
import javax.annotation.Generated;

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

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

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

    private static final MarshallingInfo<Boolean> CRAWLATTACHMENTS_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("CrawlAttachments").build();
    private static final MarshallingInfo<List> INCLUDEATTACHMENTFILEPATTERNS_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("IncludeAttachmentFilePatterns").build();
    private static final MarshallingInfo<List> EXCLUDEATTACHMENTFILEPATTERNS_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ExcludeAttachmentFilePatterns").build();
    private static final MarshallingInfo<String> DOCUMENTDATAFIELDNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("DocumentDataFieldName").build();
    private static final MarshallingInfo<String> DOCUMENTTITLEFIELDNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("DocumentTitleFieldName").build();
    private static final MarshallingInfo<List> FIELDMAPPINGS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("FieldMappings").build();

    private static final ServiceNowServiceCatalogConfigurationMarshaller instance = new ServiceNowServiceCatalogConfigurationMarshaller();

    public static ServiceNowServiceCatalogConfigurationMarshaller getInstance() {
        return instance;
    }

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

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

        try {
            protocolMarshaller.marshall(serviceNowServiceCatalogConfiguration.getCrawlAttachments(), CRAWLATTACHMENTS_BINDING);
            protocolMarshaller.marshall(serviceNowServiceCatalogConfiguration.getIncludeAttachmentFilePatterns(), INCLUDEATTACHMENTFILEPATTERNS_BINDING);
            protocolMarshaller.marshall(serviceNowServiceCatalogConfiguration.getExcludeAttachmentFilePatterns(), EXCLUDEATTACHMENTFILEPATTERNS_BINDING);
            protocolMarshaller.marshall(serviceNowServiceCatalogConfiguration.getDocumentDataFieldName(), DOCUMENTDATAFIELDNAME_BINDING);
            protocolMarshaller.marshall(serviceNowServiceCatalogConfiguration.getDocumentTitleFieldName(), DOCUMENTTITLEFIELDNAME_BINDING);
            protocolMarshaller.marshall(serviceNowServiceCatalogConfiguration.getFieldMappings(), FIELDMAPPINGS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
@interface LWNavigationController : UINavigationController

@end


text:
TEST(NinjaScriptTargetWriter, WriteOutputFilesForBuildLine) {
  TestWithScope setup;
  setup.build_settings()->SetBuildDir(SourceDir("//out/Debug/"));
  Target target(setup.settings(), Label(SourceDir("//foo/"), "bar"));

  target.script_values().outputs().push_back(
      SourceFile("//out/Debug/gen/a b{{source_name_part}}.h"));
  target.script_values().outputs().push_back(
      SourceFile("//out/Debug/gen/{{source_name_part}}.cc"));

  std::ostringstream out;
  NinjaScriptTargetWriter writer(&target, out);

  FileTemplate output_template = writer.GetOutputTemplate();

  SourceFile source("//foo/bar.in");
  std::vector<OutputFile> output_files;
  writer.WriteOutputFilesForBuildLine(output_template, source, &output_files);

  std::string out_str = out.str();
#if defined(OS_WIN)
  std::replace(out_str.begin(), out_str.end(), '\\', '/');
#endif
  EXPECT_EQ(" gen/a$ bbar.h gen/bar.cc", out_str);
}

TEST(NinjaScriptTargetWriter, WriteArgsSubstitutions) {
  TestWithScope setup;
  setup.build_settings()->SetBuildDir(SourceDir("//out/Debug/"));
  Target target(setup.settings(), Label(SourceDir("//foo/"), "bar"));

  std::ostringstream out;
  NinjaScriptTargetWriter writer(&target, out);

  std::vector<std::string> args;
  args.push_back("-i");
  args.push_back("{{source}}");
  args.push_back("--out=foo bar{{source_name_part}}.o");
  FileTemplate args_template(args);

  writer.WriteArgsSubstitutions(SourceFile("//foo/b ar.in"), args_template);

  std::string out_str = out.str();
#if defined(OS_WIN)
  std::replace(out_str.begin(), out_str.end(), '\\', '/');
#endif
  EXPECT_EQ("  source = ../../foo/b$ ar.in\n  source_name_part = b$ ar\n",
            out_str);
}

// Tests the "run script over multiple source files" mode.
TEST(NinjaScriptTargetWriter, InvokeOverSources) {
  TestWithScope setup;
  setup.build_settings()->SetBuildDir(SourceDir("//out/Debug/"));
  Target target(setup.settings(), Label(SourceDir("//foo/"), "bar"));
  target.set_output_type(Target::CUSTOM);

  target.sources().push_back(SourceFile("//foo/input1.txt"));
  target.sources().push_back(SourceFile("//foo/input2.txt"));

  target.script_values().set_script(SourceFile("//foo/script.py"));

  target.script_values().args().push_back("-i");
  target.script_values().args().push_back("{{source}}");
  target.script_values().args().push_back(
      "--out=foo bar{{source_name_part}}.o");

  target.script_values().outputs().push_back(SourceFile("//out/Debug/{{source_name_part}}.out"));

  target.source_prereqs().push_back(SourceFile("//foo/included.txt"));

  // Posix.
  {
    setup.settings()->set_target_os(Settings::LINUX);

    std::ostringstream out;
    NinjaScriptTargetWriter writer(&target, out);
    writer.Run();

    const char expected_linux[] =
        "rule __foo_bar___rule\n"
        "  command = cd ../../foo; $pythonpath ../../foo/script.py -i ${source} \"--out=foo$ bar${source_name_part}.o\"\n"
        "  description = CUSTOM //foo:bar()\n"
        "  restat = 1\n"
        "\n"
        "build input1.out: __foo_bar___rule../../foo/input1.txt | ../../foo/included.txt\n"
        "  source = ../../foo/input1.txt\n"
        "  source_name_part = input1\n"
        "build input2.out: __foo_bar___rule../../foo/input2.txt | ../../foo/included.txt\n"
        "  source = ../../foo/input2.txt\n"
        "  source_name_part = input2\n"
        "\n"
        "build obj/foo/bar.stamp: tc_stamp input1.out input2.out\n";

    std::string out_str = out.str();
#if defined(OS_WIN)
    std::replace(out_str.begin(), out_str.end(), '\\', '/');
#endif
    EXPECT_EQ(expected_linux, out_str);
  }

  // Windows.
  {
    setup.settings()->set_target_os(Settings::WIN);

    std::ostringstream out;
    NinjaScriptTargetWriter writer(&target, out);
    writer.Run();

    // TODO(brettw) I think we'll need to worry about backslashes here
    // depending if we're on actual Windows or Linux pretending to be Windows.
    const char expected_win[] =
        "arch = environment.x86\n"
        "rule __foo_bar___rule\n"
        "  command = $pythonpath gyp-win-tool action-wrapper $arch __foo_bar___rule.$unique_name.rsp\n"
        "  description = CUSTOM //foo:bar()\n"
        "  restat = 1\n"
        "  rspfile = __foo_bar___rule.$unique_name.rsp\n"
        "  rspfile_content = $pythonpath ../../foo/script.py -i ${source} \"--out=foo$ bar${source_name_part}.o\"\n"
        "\n"
        "build input1.out: __foo_bar___rule../../foo/input1.txt | ../../foo/included.txt\n"
        "  unique_name = 0\n"
        "  source = ../../foo/input1.txt\n"
        "  source_name_part = input1\n"
        "build input2.out: __foo_bar___rule../../foo/input2.txt | ../../foo/included.txt\n"
        "  unique_name = 1\n"
        "  source = ../../foo/input2.txt\n"
        "  source_name_part = input2\n"
        "\n"
        "build obj/foo/bar.stamp: tc_stamp input1.out input2.out\n";
    std::string out_str = out.str();
#if defined(OS_WIN)
    std::replace(out_str.begin(), out_str.end(), '\\', '/');
#endif
    EXPECT_EQ(expected_win, out_str);
  }
}


text:
---
date: "2015-12-05"
title: "ES6, ES2015 : les classes"
tags:
  - javascript
  - ES6
  - ES2015
authors:
  - magsout
---

Les classes introduites par `ES2015` ne sont clairement que du sucre syntaxique.
Elles n'apportent rien de plus en terme de fonctionnalité. Toutefois, l'objectif
de cette évolution est de rendre le code plus lisible et plus facilement
accessible.

## Déclaration de classes

Oubliez les fonctions anonymes et les prototypes, la sémantique a pris le
relais, comme vous pouvez le constater dans l'exemple de déclaration de la
classe `User` :

```js
class User {
  // méthode constructor
  constructor(firstname, lastname) {
    this.firstname = firstname;
    this.lastname = lastname;
  }

  sayName() {
    return `${this.firstname} ${this.lastname}`
  }
}

// instanciation
const user = new User("John", "Doe")

// appel de la méthode sayName()
console.log(user.sayName()) // John Doe
```

Pour rappel, voici une [façon possible
d'écrire](https://gist.github.com/magsout/a876b2fa8240a987e523) cette classe en
`es5` :

```js
function User(firstname, lastname) {
  if(!(this instanceof User)) {
    throw new TypeError("Class constructors cannot be invoked without 'new'")
  }
  this.firstname = firstname
  this.lastname = lastname
}

User.prototype.sayName = function() {
  return this.firstname + " " + this.lastname
}

// instanciation
var user = new User("John", "Doe")

// appel de la méthode sayName()
console.log(user.sayName()) // John Doe
```

## Expressions de classes

Toutes les méthodes s'écrivent comme de simples fonctions à l'intérieur de la
classe. Bien entendu, les getter/setter sont toujours de la partie mais bien
plus simples à utiliser :

```JS
class User {
  // constructor
  constructor(firstname, lastname, type) {
    this.firstname = firstname
    this.lastname = lastname
    this.type = type
  }

  // méthode
  sayName() {
   return `${this.firstname}  ${this.lastname}`
  }

  // getter
  get role() {
    return this.type
  }

  // setter
  set role(value) {
    return this.type = value
  }
}

// le `new` est obligatoire pour appeler une classe
const user = new User("John", "Doe", "Contributor")

console.log(user.sayName()) // John Doe
console.log(user.role) // Contributor
user.role = "owner"
console.log(user.role) // Owner
```

## L'héritage

Pour qu'une sous-classe hérite d'une autre classe on utilisera le mot
clé `extends`.

En utilisant notre exemple précédent :

```js
class Contributor extends User {
  constructor(firstname, lastname, numberCommit) {

    // le mot clé super est utilisé comme super contructeur. Il permet d'appeler
    // et d'avoir accès aux méthodes du parent
    super(firstname, lastname)
    this.numberCommit = numberCommit
  }

  sayNameWithCommit() {
    // on peut appeler une méthode de la classe parente avec `super.method`
    return super.sayName() + " " + this.sayNumberCommit()
  }

  sayNumberCommit() {
    return this.numberCommit
  }
}

// instanciation
const contributor = new Contributor('Jane', 'Smith', 10)

// appel de la méthode sayName()
console.log(contributor.sayName())
console.log(contributor.sayNumberCommit())

```

**Rappel : [préférez la composition à l'héritage](https://www.youtube.com/watch?v=wfMtDGfHWpA).**

## That's it

Concrètement, tout ce qui est possible de faire avec cette nouvelle notation
l'était bien entendu
[avant](https://gist.github.com/bloodyowl/7edc9c973d2236ed17e1).

Au final, on gagne en clarté, en lisibilité et donc en maintenabilité.

À l'heure actuelle, il est nécessaire de passer par un transpileur comme
[babel](https://babeljs.io/) pour utiliser les classes.

Une dernière petite chose, le
[mode strict](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Strict_mode)
est automatiquement activé dans le corps des classes et leurs déclarations.
Il n'est donc pas nécessaire de le rajouter manuellement.

```js
/* Mode strict initial */
class MyClass {
  someMethod() {
    /* Ici le mode strict est implicitement activé */
  }
}
/* Mode strict inchangé */
```


text:
============
Rally v0.8.1
============

Overview
--------

+------------------+-----------------------+
| Release date     |      **1/27/2017**    |
+------------------+-----------------------+

Details
-------

Fix for python requirements list.

Plugins
~~~~~~~

**Scenarios**:

* *Updated*:

 - Use new network for each subnet at
   `NeutronNetworks.create_and_list_subnets
   <http://rally.readthedocs.io/en/0.8.1/plugins/plugin_reference.html#neutronnetworks-create-and-list-subnets-scenario>`_
   scenario.

* *NEW!!*:

 - `CinderVolumeTypes.create_and_list_encryption_type
   <http://rally.readthedocs.io/en/0.8.1/plugins/plugin_reference.html#cindervolumetypes-create-and-list-encryption-type-scenario>`_

 - `Quotas.cinder_get
   <http://rally.readthedocs.io/en/0.8.1/plugins/plugin_reference.html#quotas-cinder-get-scenario>`_

Thanks
~~~~~~

 2 Everybody!


text:
Luis E. S. Dias
smartbyte.systems@gmail.com

## About
Silverstripe module to create a timeline

## Github repository
https://github.com/luisdias/Timeline-Silverstripe-Module

## Notes
jQuery libray loaded from Google at TimelineHolder.ss file

The Timeline Silverstripe Module uses:

[Timeline jQuery Plugin](http://timeline.verite.co/)

[CSS Theme by Tutorialzine](http://tutorialzine.com/2012/04/timeline-portfolio/)

## Installation
* Unpack the files in a folder called timeline
* Run dev/build
* on the javascript folder you can find the translation files for the following idioms: french, italian,
portuguese and spanish. Remove the comment from the line 33 of the templates/TimelineHolder.ss file
and set it for your idiom.

## Usage
* At the CMS add a new page of "Timeline Holder" type
* Select the cascade style sheet file to use ( Default from verite or dark template from tutorialzine )
* Add children pages of "Timeline Page" type
* Set the fields Event Date, End of Event, Article.
* In the Content field you can insert images, links to youtube videos, vimeo videos and more.
See the [Timeline jQuery Plugin documentation](http://timeline.verite.co/#about) for more info.
* You can also set the Credit and Caption for the media ( Content field )


text:
class AnAppleADay::CLI

 def call
   greeting
   ask_for_input
   list_hospitals
   list_hospitals_by_one
 end

 def greeting
   puts "Welcome to the AnAppleADay gem! Here you can type in 'list' for a full list of hospitals."
 end

 def ask_for_input
   input = gets.strip
   while input.downcase != "exit"
     if input.downcase == 'list'
       list_hospitals
       puts "You can take a look at a specific hospital by typing in its corressponding number. After you can type exit to leave the gem."
       input = gets.strip
     elsif input.to_i > 0
       list_hospitals_by_one(input)
       puts "Would you like to see more hospital selections? Type list if so, type exit to exit."
       input = gets.strip
    end
    puts "An Apple a day keeps the doctor away! See you next time!"
end

 def list_hospitals
   input = gets.strip
   puts "Hospital Facilities in DC"
   puts "Name - Address - Ward - Phone Num"
   if input.downcase == "list"
     AnAppleADay::Scrapper.grab_site_contents
     AnAppleADay::Location.all.each.with_index(1) do |provider, i|
       puts "#{i} - #{provider.name} - #{provider.address} - #{provider.ward} - #{provider.num}"
   end
 end

 # list hospital

 def list_hospitals_by_one(input)
  #  puts "You can take a look at a specific hospital by typing in its corressponding number. After you can type exit to leave the gem."
  #  input = input.to_i
  #  while input != "exit"
  #    input = gets.strip
  #    if input.to_i > 0
       provider_selected = AnAppleADay::Location.all[input.to_i-1]
       puts "#{provider_selected.name} - #{provider_selected.address} - #{provider_selected.ward} - #{provider_selected.num}"

    #  elsif input == "list
    #    list_hospitals
    #  else
    #    puts "An Apple a day keeps the doctor away! See you next time!"
    #  end
  #  end
 end
end
end
end


text:
! ###################################################################
! Copyright (c) 2013-2015, Marc De Graef/Carnegie Mellon University
! All rights reserved.
!
! Redistribution and use in source and binary forms, with or without modification, are
! permitted provided that the following conditions are met:
!
!     - Redistributions of source code must retain the above copyright notice, this list
!        of conditions and the following disclaimer.
!     - 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.
!     - Neither the names of Marc De Graef, Carnegie Mellon 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 COPYRIGHT HOLDERS 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 COPYRIGHT HOLDER 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.
! ###################################################################

!--------------------------------------------------------------------------
! EMsoft:error.f90
!--------------------------------------------------------------------------
!
! MODULE: error
!
!> @author Marc De Graef, Carnegie Mellon University
!
!> @brief error handling routines
!
!> @details  Just a simple routine that reports errors and aborts the program
!
!> @date 01/05/99 MDG 1.0 original
!> @date 05/19/01 MDG 2.0 f90 version
!> @date 11/27/01 MDG 2.1 added kind support
!> @date 03/19/13 MDG 3.0 minor changes
!> @date 06/05/14 MDG 4.0 minor changes
!--------------------------------------------------------------------------

module error

use local

contains

!--------------------------------------------------------------------------
!
! SUBROUTINE: FatalError
!
!> @author Marc De Graef, Carnegie Mellon University
!
!> @brief Write error message and abort program
!
!> @param var1 routine name string
!> @param var2 explanation string
!> @param stdout optional output unit identifier
!
!> @date   10/13/98 MDG 1.0 original
!> @date    5/19/01 MDG 2.0 f90 version
!> @date   11/27/01 MDG 2.1 added kind support
!> @date   03/19/13 MDG 3.0 updated for new io routines
!> @date   06/05/14 MDG 4.0 added stdout argument
! ###################################################################
subroutine FatalError(var1,var2,stdout)

use io

IMPLICIT NONE

character(*), INTENT(IN)                        :: var1         !< first part of error message (routine name)
character(*), INTENT(IN)                        :: var2         !< second part of error message (brief explanation)
integer(kind=irg), INTENT(IN),OPTIONAL          :: stdout       !< output unit identifier

integer(kind=irg)                               :: std

 std = 6
 if (PRESENT(stdout)) std=stdout

 call Message(' ----> Fatal error in routine '//var1//': '//var2, frm='(//A//)', stdout=std)
 stop '  Progam ended abnormally'

end subroutine

end module


text:
package com.meizhuo.etips.db;

import com.meizhuo.etips.common.ETipsContants;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class MsgCenterDBHelper extends SQLiteOpenHelper {
	public MsgCenterDBHelper(Context context) {
		super(context, ETipsContants.DB_NAME_MsgCenter, null, 1);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		String sql = "create table msg(id integer primary key,type varchar(16),content varchar(256),addTime varchar(32))";
		db.execSQL(sql);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub

	}

}


text:
---

The Eve Starter is designed to help you hit the ground running with Eve. It includes a number of simple demo programs, a CLI that lets you test Eve programs in node or the browser, and a server that handles most of the frustrations of packaging node modules for the web for you. When you're ready to start building with Eve, you can either modify this framework to suit or just include the runtime into an existing project.

If you're an experienced Eve user looking to include it in your existing app, you can find the runtime at [witheve/eve](https://github.com/witheve/eve).

## Install the Eve v0.3 Preview Starter

First install [Node](https://nodejs.org/en/download/) for your platform.

Then, clone and build the Eve starter repository:

```sh
git clone git@github.com:witheve/eve-starter.git
```

To run the latest stable version:

```sh
cd eve-starter
git checkout release
npm install
```

To run the latest nightly version:

```sh
cd eve-starter
git checkout master
npm install
```

## Using the Starter

If you want to explore the bundled examples you can start the program switcher, which allows you to explore them from your browser. Any `*.eve` files places into the `eve-starter/programs` directory will be shown here.

```sh
npm start
```

Or you can run a specific `.eve` or `.js` program by providing its path as an argument:

```sh
npm start -- path/to/program.js
```

To view other functionality of the starter, run
```sh
npm start -- --help
```


text:
'use strict';

let createRenderer;
let PropTypes;
let React;

describe('ReactShallowRenderer', () => {
  beforeEach(() => {
    createRenderer = require('react-test-renderer/shallow').createRenderer;
    PropTypes = require('prop-types');
    React = require('react');
  });

  it('should call all of the lifecycle hooks', () => {
    const logs = [];
    const logger = message => () => logs.push(message) || true;

    class SomeComponent extends React.Component {
      componentWillMount = logger('componentWillMount');
      componentDidMount = logger('componentDidMount');
      componentWillReceiveProps = logger('componentWillReceiveProps');
      shouldComponentUpdate = logger('shouldComponentUpdate');
      componentWillUpdate = logger('componentWillUpdate');
      componentDidUpdate = logger('componentDidUpdate');
      componentWillUnmount = logger('componentWillUnmount');
      render() {
        return
;
      }
    }

    const shallowRenderer = createRenderer();
    shallowRenderer.render(<SomeComponent foo={1} />);

    // Calling cDU might lead to problems with host component references.
    // Since our components aren't really mounted, refs won't be available.
    expect(logs).toEqual(['componentWillMount']);

    logs.splice(0);

    const instance = shallowRenderer.getMountedInstance();
    instance.setState({});

    expect(logs).toEqual(['shouldComponentUpdate', 'componentWillUpdate']);

    logs.splice(0);

    shallowRenderer.render(<SomeComponent foo={2} />);

    // The previous shallow renderer did not trigger cDU for props changes.
    expect(logs).toEqual([
      'componentWillReceiveProps',
      'shouldComponentUpdate',
      'componentWillUpdate',
    ]);
  });

  it('should only render 1 level deep', () => {
    function Parent() {
      return (

          <Child />

      );
    }
    function Child() {
      throw Error('This component should not render');
    }

    const shallowRenderer = createRenderer();
    shallowRenderer.render(React.createElement(Parent));
  });

  it('should have shallow rendering', () => {
    class SomeComponent extends React.Component {
      render() {
        return (

        );
      }
    }

    const shallowRenderer = createRenderer();
    const result = shallowRenderer.render(<SomeComponent />);

    expect(result.type).toBe('div');
    expect(result.props.children).toEqual([
      ,
      ,
    ]);
  });

  it('should enable shouldComponentUpdate to prevent a re-render', () => {
    let renderCounter = 0;
    class SimpleComponent extends React.Component {
      state = {update: false};
      shouldComponentUpdate(nextProps, nextState) {
        return this.state.update !== nextState.update;
      }
      render() {
        renderCounter++;
        return
{`${renderCounter}`}
;
      }
    }

    const shallowRenderer = createRenderer();
    shallowRenderer.render(<SimpleComponent />);
    expect(shallowRenderer.getRenderOutput()).toEqual(
1
);

    const instance = shallowRenderer.getMountedInstance();
    instance.setState({update: false});
    expect(shallowRenderer.getRenderOutput()).toEqual(
1
);

    instance.setState({update: true});
    expect(shallowRenderer.getRenderOutput()).toEqual(
2
);
  });

  it('should enable PureComponent to prevent a re-render', () => {
    let renderCounter = 0;
    class SimpleComponent extends React.PureComponent {
      state = {update: false};
      render() {
        renderCounter++;
        return
{`${renderCounter}`}
;
      }
    }

    const shallowRenderer = createRenderer();
    shallowRenderer.render(<SimpleComponent />);
    expect(shallowRenderer.getRenderOutput()).toEqual(
1
);

    const instance = shallowRenderer.getMountedInstance();
    instance.setState({update: false});
    expect(shallowRenderer.getRenderOutput()).toEqual(
1
);

    instance.setState({update: true});
    expect(shallowRenderer.getRenderOutput()).toEqual(
2
);
  });

  it('should not run shouldComponentUpdate during forced update', () => {
    let scuCounter = 0;
    class SimpleComponent extends React.Component {
      state = {count: 1};
      shouldComponentUpdate() {
        scuCounter++;
        return false;
      }
      render() {
        return
{`${this.state.count}`}
;
      }
    }

    const shallowRenderer = createRenderer();
    shallowRenderer.render(<SimpleComponent />);
    expect(scuCounter).toEqual(0);
    expect(shallowRenderer.getRenderOutput()).toEqual(
1
);

    // Force update the initial state. sCU should not fire.
    const instance = shallowRenderer.getMountedInstance();
    instance.forceUpdate();
    expect(scuCounter).toEqual(0);
    expect(shallowRenderer.getRenderOutput()).toEqual(
1
);

    // Setting state updates the instance, but doesn't re-render
    // because sCU returned false.
    instance.setState(state => ({count: state.count + 1}));
    expect(scuCounter).toEqual(1);
    expect(instance.state.count).toEqual(2);
    expect(shallowRenderer.getRenderOutput()).toEqual(
1
);

    // A force update updates the render output, but doesn't call sCU.
    instance.forceUpdate();
    expect(scuCounter).toEqual(1);
    expect(instance.state.count).toEqual(2);
    expect(shallowRenderer.getRenderOutput()).toEqual(
2
);
  });

  it('should rerender when calling forceUpdate', () => {
    let renderCounter = 0;
    class SimpleComponent extends React.Component {
      render() {
        renderCounter += 1;
        return
;
      }
    }

    const shallowRenderer = createRenderer();
    shallowRenderer.render(<SimpleComponent />);
    expect(renderCounter).toEqual(1);

    const instance = shallowRenderer.getMountedInstance();
    instance.forceUpdate();
    expect(renderCounter).toEqual(2);
  });

  it('should shallow render a functional component', () => {
    function SomeComponent(props, context) {
      return (

{props.foo}

{context.bar}

      );
    }

    const shallowRenderer = createRenderer();
    const result = shallowRenderer.render(<SomeComponent foo={'FOO'} />, {
      bar: 'BAR',
    });

    expect(result.type).toBe('div');
    expect(result.props.children).toEqual([

FOO
,

BAR
,
      ,
      ,
    ]);
  });

  it('should shallow render a component returning strings directly from render', () => {
    const Text = ({value}) => value;

    const shallowRenderer = createRenderer();
    const result = shallowRenderer.render(<Text value="foo" />);
    expect(result).toEqual('foo');
  });

  it('should shallow render a component returning numbers directly from render', () => {
    const Text = ({value}) => value;

    const shallowRenderer = createRenderer();
    const result = shallowRenderer.render(<Text value={10} />);
    expect(result).toEqual(10);
  });

  it('should shallow render a fragment', () => {
    class SomeComponent extends React.Component {
      render() {
        return
;
      }
    }
    class Fragment extends React.Component {
      render() {
        return [
, , <SomeComponent />];
      }
    }
    const shallowRenderer = createRenderer();
    const result = shallowRenderer.render(<Fragment />);
    expect(result).toEqual([

,
      ,
      <SomeComponent />,
    ]);
  });

  it('should throw for invalid elements', () => {
    class SomeComponent extends React.Component {
      render() {
        return
;
      }
    }

    const shallowRenderer = createRenderer();
    expect(() => shallowRenderer.render(SomeComponent)).toThrowError(
      'ReactShallowRenderer render(): Invalid component element. Instead of ' +
        'passing a component class, make sure to instantiate it by passing it ' +
        'to React.createElement.',
    );
    expect(() => shallowRenderer.render(
)).toThrowError(
      'ReactShallowRenderer render(): Shallow rendering works only with ' +
        'custom components, not primitives (div). Instead of calling ' +
        '`.render(el)` and inspecting the rendered output, look at `el.props` ' +
        'directly instead.',
    );
  });

  it('should have shallow unmounting', () => {
    const componentWillUnmount = jest.fn();

    class SomeComponent extends React.Component {
      componentWillUnmount = componentWillUnmount;
      render() {
        return
;
      }
    }

    const shallowRenderer = createRenderer();
    shallowRenderer.render(<SomeComponent />);
    shallowRenderer.unmount();

    expect(componentWillUnmount).toBeCalled();
  });

  it('can shallow render to null', () => {
    class SomeComponent extends React.Component {
      render() {
        return null;
      }
    }

    const shallowRenderer = createRenderer();
    const result = shallowRenderer.render(<SomeComponent />);

    expect(result).toBe(null);
  });

  it('can shallow render with a ref', () => {
    class SomeComponent extends React.Component {
      render() {
        return
;
      }
    }

    const shallowRenderer = createRenderer();
    // Shouldn't crash.
    shallowRenderer.render(<SomeComponent />);
  });

  it('lets you update shallowly rendered components', () => {
    class SomeComponent extends React.Component {
      state = {clicked: false};

      onClick = () => {
        this.setState({clicked: true});
      };

      render() {
        const className = this.state.clicked ? 'was-clicked' : '';

        if (this.props.aNew === 'prop') {
          return (

              Test link

          );
        } else {
          return (

          );
        }
      }
    }

    const shallowRenderer = createRenderer();
    const result = shallowRenderer.render(<SomeComponent />);
    expect(result.type).toBe('div');
    expect(result.props.children).toEqual([
      ,
      ,
    ]);

    const updatedResult = shallowRenderer.render(<SomeComponent aNew="prop" />);
    expect(updatedResult.type).toBe('a');

    const mockEvent = {};
    updatedResult.props.onClick(mockEvent);

    const updatedResultCausedByClick = shallowRenderer.getRenderOutput();
    expect(updatedResultCausedByClick.type).toBe('a');
    expect(updatedResultCausedByClick.props.className).toBe('was-clicked');
  });

  it('can access the mounted component instance', () => {
    class SimpleComponent extends React.Component {
      someMethod = () => {
        return this.props.n;
      };

      render() {
        return
{this.props.n}
;
      }
    }

    const shallowRenderer = createRenderer();
    shallowRenderer.render(<SimpleComponent n={5} />);
    expect(shallowRenderer.getMountedInstance().someMethod()).toEqual(5);
  });

  it('can shallowly render components with contextTypes', () => {
    class SimpleComponent extends React.Component {
      static contextTypes = {
        name: PropTypes.string,
      };

      render() {
        return
;
      }
    }

    const shallowRenderer = createRenderer();
    const result = shallowRenderer.render(<SimpleComponent />);
    expect(result).toEqual(
);
  });

  it('passes expected params to component lifecycle methods', () => {
    const componentDidUpdateParams = [];
    const componentWillReceivePropsParams = [];
    const componentWillUpdateParams = [];
    const setStateParams = [];
    const shouldComponentUpdateParams = [];

    const initialProp = {prop: 'init prop'};
    const initialState = {state: 'init state'};
    const initialContext = {context: 'init context'};
    const updatedState = {state: 'updated state'};
    const updatedProp = {prop: 'updated prop'};
    const updatedContext = {context: 'updated context'};

    class SimpleComponent extends React.Component {
      constructor(props, context) {
        super(props, context);
        this.state = initialState;
      }
      componentDidUpdate(...args) {
        componentDidUpdateParams.push(...args);
      }
      componentWillReceiveProps(...args) {
        componentWillReceivePropsParams.push(...args);
        this.setState((...innerArgs) => {
          setStateParams.push(...innerArgs);
          return updatedState;
        });
      }
      componentWillUpdate(...args) {
        componentWillUpdateParams.push(...args);
      }
      shouldComponentUpdate(...args) {
        shouldComponentUpdateParams.push(...args);
        return true;
      }
      render() {
        return null;
      }
    }

    const shallowRenderer = createRenderer();

    // No lifecycle hooks should be invoked on initial render
    shallowRenderer.render(
      React.createElement(SimpleComponent, initialProp),
      initialContext,
    );
    expect(componentDidUpdateParams).toEqual([]);
    expect(componentWillReceivePropsParams).toEqual([]);
    expect(componentWillUpdateParams).toEqual([]);
    expect(setStateParams).toEqual([]);
    expect(shouldComponentUpdateParams).toEqual([]);

    // Lifecycle hooks should be invoked with the correct prev/next params on update.
    shallowRenderer.render(
      React.createElement(SimpleComponent, updatedProp),
      updatedContext,
    );
    expect(componentWillReceivePropsParams).toEqual([
      updatedProp,
      updatedContext,
    ]);
    expect(setStateParams).toEqual([initialState, initialProp]);
    expect(shouldComponentUpdateParams).toEqual([
      updatedProp,
      updatedState,
      updatedContext,
    ]);
    expect(componentWillUpdateParams).toEqual([
      updatedProp,
      updatedState,
      updatedContext,
    ]);
    expect(componentDidUpdateParams).toEqual([]);
  });

  it('can shallowly render components with ref as function', () => {
    class SimpleComponent extends React.Component {
      state = {clicked: false};

      handleUserClick = () => {
        this.setState({clicked: true});
      };

      render() {
        return (

 {}}
            onClick={this.handleUserClick}
            className={this.state.clicked ? 'clicked' : ''}
          />
        );
      }
    }

    const shallowRenderer = createRenderer();
    shallowRenderer.render(<SimpleComponent />);
    let result = shallowRenderer.getRenderOutput();
    expect(result.type).toEqual('div');
    expect(result.props.className).toEqual('');
    result.props.onClick();

    result = shallowRenderer.getRenderOutput();
    expect(result.type).toEqual('div');
    expect(result.props.className).toEqual('clicked');
  });

  it('can setState in componentWillMount when shallow rendering', () => {
    class SimpleComponent extends React.Component {
      componentWillMount() {
        this.setState({groovy: 'doovy'});
      }

      render() {
        return
{this.state.groovy}
;
      }
    }

    const shallowRenderer = createRenderer();
    const result = shallowRenderer.render(<SimpleComponent />);
    expect(result).toEqual(
doovy
);
  });

  it('can setState in componentWillMount repeatedly when shallow rendering', () => {
    class SimpleComponent extends React.Component {
      state = {
        separator: '-',
      };

      componentWillMount() {
        this.setState({groovy: 'doovy'});
        this.setState({doovy: 'groovy'});
      }

      render() {
        const {groovy, doovy, separator} = this.state;

        return
{`${groovy}${separator}${doovy}`}
;
      }
    }

    const shallowRenderer = createRenderer();
    const result = shallowRenderer.render(<SimpleComponent />);
    expect(result).toEqual(
doovy-groovy
);
  });

  it('can setState in componentWillMount with an updater function repeatedly when shallow rendering', () => {
    class SimpleComponent extends React.Component {
      state = {
        separator: '-',
      };

      componentWillMount() {
        this.setState(state => ({groovy: 'doovy'}));
        this.setState(state => ({doovy: state.groovy}));
      }

      render() {
        const {groovy, doovy, separator} = this.state;

        return
{`${groovy}${separator}${doovy}`}
;
      }
    }

    const shallowRenderer = createRenderer();
    const result = shallowRenderer.render(<SimpleComponent />);
    expect(result).toEqual(
doovy-doovy
);
  });

  it('can setState in componentWillReceiveProps when shallow rendering', () => {
    class SimpleComponent extends React.Component {
      state = {count: 0};

      componentWillReceiveProps(nextProps) {
        if (nextProps.updateState) {
          this.setState({count: 1});
        }
      }

      render() {
        return
{this.state.count}
;
      }
    }

    const shallowRenderer = createRenderer();
    let result = shallowRenderer.render(
      <SimpleComponent updateState={false} />,
    );
    expect(result.props.children).toEqual(0);

    result = shallowRenderer.render(<SimpleComponent updateState={true} />);
    expect(result.props.children).toEqual(1);
  });

  it('can setState with an updater function', () => {
    let instance;

    class SimpleComponent extends React.Component {
      state = {
        counter: 0,
      };

      render() {
        instance = this;
        return (
          <button ref="button" onClick={this.onClick}>
            {this.state.counter}
          </button>
        );
      }
    }

    const shallowRenderer = createRenderer();
    let result = shallowRenderer.render(<SimpleComponent defaultCount={1} />);
    expect(result.props.children).toEqual(0);

    instance.setState((state, props) => {
      return {counter: props.defaultCount + 1};
    });

    result = shallowRenderer.getRenderOutput();
    expect(result.props.children).toEqual(2);
  });

  it('can setState with a callback', () => {
    let instance;

    class SimpleComponent extends React.Component {
      state = {
        counter: 0,
      };
      render() {
        instance = this;
        return
{this.state.counter}
;
      }
    }

    const shallowRenderer = createRenderer();
    const result = shallowRenderer.render(<SimpleComponent />);
    expect(result.props.children).toBe(0);

    const callback = jest.fn(function() {
      expect(this).toBe(instance);
    });

    instance.setState({counter: 1}, callback);

    const updated = shallowRenderer.getRenderOutput();
    expect(updated.props.children).toBe(1);
    expect(callback).toHaveBeenCalled();
  });

  it('can replaceState with a callback', () => {
    let instance;

    class SimpleComponent extends React.Component {
      state = {
        counter: 0,
      };
      render() {
        instance = this;
        return
{this.state.counter}
;
      }
    }

    const shallowRenderer = createRenderer();
    const result = shallowRenderer.render(<SimpleComponent />);
    expect(result.props.children).toBe(0);

    const callback = jest.fn(function() {
      expect(this).toBe(instance);
    });

    // No longer a public API, but we can test that it works internally by
    // reaching into the updater.
    shallowRenderer._updater.enqueueReplaceState(
      instance,
      {counter: 1},
      callback,
    );

    const updated = shallowRenderer.getRenderOutput();
    expect(updated.props.children).toBe(1);
    expect(callback).toHaveBeenCalled();
  });

  it('can forceUpdate with a callback', () => {
    let instance;

    class SimpleComponent extends React.Component {
      state = {
        counter: 0,
      };
      render() {
        instance = this;
        return
{this.state.counter}
;
      }
    }

    const shallowRenderer = createRenderer();
    const result = shallowRenderer.render(<SimpleComponent />);
    expect(result.props.children).toBe(0);

    const callback = jest.fn(function() {
      expect(this).toBe(instance);
    });

    instance.forceUpdate(callback);

    const updated = shallowRenderer.getRenderOutput();
    expect(updated.props.children).toBe(0);
    expect(callback).toHaveBeenCalled();
  });

  it('can pass context when shallowly rendering', () => {
    class SimpleComponent extends React.Component {
      static contextTypes = {
        name: PropTypes.string,
      };

      render() {
        return
{this.context.name}
;
      }
    }

    const shallowRenderer = createRenderer();
    const result = shallowRenderer.render(<SimpleComponent />, {
      name: 'foo',
    });
    expect(result).toEqual(
foo
);
  });

  it('should track context across updates', () => {
    class SimpleComponent extends React.Component {
      static contextTypes = {
        foo: PropTypes.string,
      };

      state = {
        bar: 'bar',
      };

      render() {
        return
{`${this.context.foo}:${this.state.bar}`}
;
      }
    }

    const shallowRenderer = createRenderer();
    let result = shallowRenderer.render(<SimpleComponent />, {
      foo: 'foo',
    });
    expect(result).toEqual(
foo:bar
);

    const instance = shallowRenderer.getMountedInstance();
    instance.setState({bar: 'baz'});

    result = shallowRenderer.getRenderOutput();
    expect(result).toEqual(
foo:baz
);
  });

  it('can fail context when shallowly rendering', () => {
    spyOnDev(console, 'error');

    class SimpleComponent extends React.Component {
      static contextTypes = {
        name: PropTypes.string.isRequired,
      };

      render() {
        return
{this.context.name}
;
      }
    }

    const shallowRenderer = createRenderer();
    shallowRenderer.render(<SimpleComponent />);
    if (__DEV__) {
      expect(console.error.calls.count()).toBe(1);
      expect(
        console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)'),
      ).toBe(
        'Warning: Failed context type: The context `name` is marked as ' +
          'required in `SimpleComponent`, but its value is `undefined`.\n' +
          '    in SimpleComponent (at **)',
      );
    }
  });

  it('should warn about propTypes (but only once)', () => {
    spyOnDev(console, 'error');

    class SimpleComponent extends React.Component {
      render() {
        return React.createElement('div', null, this.props.name);
      }
    }

    SimpleComponent.propTypes = {
      name: PropTypes.string.isRequired,
    };

    const shallowRenderer = createRenderer();
    shallowRenderer.render(React.createElement(SimpleComponent, {name: 123}));

    if (__DEV__) {
      expect(console.error.calls.count()).toBe(1);
      expect(
        console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)'),
      ).toBe(
        'Warning: Failed prop type: Invalid prop `name` of type `number` ' +
          'supplied to `SimpleComponent`, expected `string`.\n' +
          '    in SimpleComponent',
      );
    }
  });

  it('should enable rendering of cloned element', () => {
    class SimpleComponent extends React.Component {
      constructor(props) {
        super(props);

        this.state = {
          bar: 'bar',
        };
      }

      render() {
        return
{`${this.props.foo}:${this.state.bar}`}
;
      }
    }

    const shallowRenderer = createRenderer();
    const el = <SimpleComponent foo="foo" />;
    let result = shallowRenderer.render(el);
    expect(result).toEqual(
foo:bar
);

    const cloned = React.cloneElement(el, {foo: 'baz'});
    result = shallowRenderer.render(cloned);
    expect(result).toEqual(
baz:bar
);
  });

  it('this.state should be updated on setState callback inside componentWillMount', () => {
    let stateSuccessfullyUpdated = false;

    class Component extends React.Component {
      constructor(props, context) {
        super(props, context);
        this.state = {
          hasUpdatedState: false,
        };
      }

      componentWillMount() {
        this.setState(
          {hasUpdatedState: true},
          () => (stateSuccessfullyUpdated = this.state.hasUpdatedState),
        );
      }

      render() {
        return
{this.props.children}
;
      }
    }

    const shallowRenderer = createRenderer();
    shallowRenderer.render(<Component />);
    expect(stateSuccessfullyUpdated).toBe(true);
  });

  it('should handle multiple callbacks', () => {
    const mockFn = jest.fn();
    const shallowRenderer = createRenderer();

    class Component extends React.Component {
      constructor(props, context) {
        super(props, context);
        this.state = {
          foo: 'foo',
        };
      }

      componentWillMount() {
        this.setState({foo: 'bar'}, () => mockFn());
        this.setState({foo: 'foobar'}, () => mockFn());
      }

      render() {
        return
{this.state.foo}
;
      }
    }

    shallowRenderer.render(<Component />);

    expect(mockFn.mock.calls.length).toBe(2);

    // Ensure the callback queue is cleared after the callbacks are invoked
    const mountedInstance = shallowRenderer.getMountedInstance();
    mountedInstance.setState({foo: 'bar'}, () => mockFn());
    expect(mockFn.mock.calls.length).toBe(3);
  });

  it('should call the setState callback even if shouldComponentUpdate = false', done => {
    const mockFn = jest.fn().mockReturnValue(false);

    class Component extends React.Component {
      constructor(props, context) {
        super(props, context);
        this.state = {
          hasUpdatedState: false,
        };
      }

      shouldComponentUpdate() {
        return mockFn();
      }

      render() {
        return
{this.state.hasUpdatedState}
;
      }
    }

    const shallowRenderer = createRenderer();
    shallowRenderer.render(<Component />);

    const mountedInstance = shallowRenderer.getMountedInstance();
    mountedInstance.setState({hasUpdatedState: true}, () => {
      expect(mockFn).toBeCalled();
      expect(mountedInstance.state.hasUpdatedState).toBe(true);
      done();
    });
  });

  it('throws usefully when rendering badly-typed elements', () => {
    spyOnDev(console, 'error');
    const shallowRenderer = createRenderer();

    var Undef = undefined;
    expect(() => shallowRenderer.render(<Undef />)).toThrowError(
      'ReactShallowRenderer render(): Shallow rendering works only with custom ' +
        'components, but the provided element type was `undefined`.',
    );

    var Null = null;
    expect(() => shallowRenderer.render(<Null />)).toThrowError(
      'ReactShallowRenderer render(): Shallow rendering works only with custom ' +
        'components, but the provided element type was `null`.',
    );

    var Arr = [];
    expect(() => shallowRenderer.render(<Arr />)).toThrowError(
      'ReactShallowRenderer render(): Shallow rendering works only with custom ' +
        'components, but the provided element type was `array`.',
    );

    var Obj = {};
    expect(() => shallowRenderer.render(<Obj />)).toThrowError(
      'ReactShallowRenderer render(): Shallow rendering works only with custom ' +
        'components, but the provided element type was `object`.',
    );

    if (__DEV__) {
      // One warning for each element creation
      expect(console.error.calls.count()).toBe(4);
    }
  });
});


text:
package org.consec.federationdb.model;

import javax.persistence.*;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.List;

@Entity
@Table(name = "role")
@NamedQueries({
        @NamedQuery(name = "Role.findAll", query = "SELECT r FROM Role r")})
public class Role implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "role_id", nullable = false)
    private Integer roleId;
    @Size(max = 45)
    @Column(name = "name", length = 45)
    private String name;
    @Size(max = 255)
    @Column(name = "description", length = 255)
    private String description;
    @Lob
    @Size(max = 65535)
    @Column(name = "acl", length = 65535)
    private String acl;
    @JoinTable(name = "user_has_role", joinColumns = {
            @JoinColumn(name = "role_id", referencedColumnName = "role_id", nullable = false)}, inverseJoinColumns = {
            @JoinColumn(name = "user_id", referencedColumnName = "user_id", nullable = false)})
    @ManyToMany
    private List<User> userList;

    public Role() {
    }

    public Role(Integer roleId) {
        this.roleId = roleId;
    }

    public Integer getRoleId() {
        return roleId;
    }

    public void setRoleId(Integer roleId) {
        this.roleId = roleId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getAcl() {
        return acl;
    }

    public void setAcl(String acl) {
        this.acl = acl;
    }

    public List<User> getUserList() {
        return userList;
    }

    public void setUserList(List<User> userList) {
        this.userList = userList;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (roleId != null ? roleId.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Role)) {
            return false;
        }
        Role other = (Role) object;
        if ((this.roleId == null && other.roleId != null) || (this.roleId != null && !this.roleId.equals(other.roleId))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.consec.federationdb.model.Role[ roleId=" + roleId + " ]";
    }

}


text:
JAVACMD="$JAVA_HOME/bin/java";

# Tries to use readlink or realpath. If not installed, falls back to no conversion.
my_realpath() {
    readlink -f "$1" 2>/dev/null || realpath "$1" 2>/dev/null || echo "$1"
}

FS_CLI_DIR="$( cd "$(dirname "$(my_realpath "$0")")/../" ; pwd -P )/"

BYTECODE_VERSION=$("${JAVA_HOME}"/bin/javap -verbose java.lang.Object | grep major | cut -d " " -f5)
if [ "${BYTECODE_VERSION}" -gt 52 ]; then
  VM_ARGS="--add-opens=java.base/sun.reflect.annotation=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED"
fi

$JAVACMD $VM_ARGS -Xmx512m -Dlog4j.configurationFile="${FS_CLI_DIR}conf/log4j2.xml" -cp "${FS_CLI_DIR}/lib/*" com.espirit.moddev.cli.Main "$@";
RETVAL=$?;
exit ${RETVAL};


text:
class DIVESearch():

    def __init__(self, config):
        self.config = config

    def search(self):
        return None


text:
#include "config.h"
#include "XMLDocumentParser.h"

#include "CDATASection.h"
#include "Comment.h"
#include "Document.h"
#include "DocumentFragment.h"
#include "DocumentType.h"
#include "Frame.h"
#include "FrameLoader.h"
#include "FrameView.h"
#include "HTMLLinkElement.h"
#include "HTMLNames.h"
#include "HTMLStyleElement.h"
#include "ImageLoader.h"
#include "PendingScript.h"
#include "ProcessingInstruction.h"
#include "ResourceError.h"
#include "ResourceRequest.h"
#include "ResourceResponse.h"
#include "SVGNames.h"
#include "SVGStyleElement.h"
#include "ScriptElement.h"
#include "ScriptSourceCode.h"
#include "StyleScope.h"
#include "TextResourceDecoder.h"
#include "TreeDepthLimit.h"
#include <wtf/Ref.h>
#include <wtf/StringExtras.h>
#include <wtf/Threading.h>
#include <wtf/Vector.h>

namespace WebCore {

using namespace HTMLNames;

void XMLDocumentParser::pushCurrentNode(ContainerNode* n)
{
    ASSERT(n);
    ASSERT(m_currentNode);
    if (n != document())
        n->ref();
    m_currentNodeStack.append(m_currentNode);
    m_currentNode = n;
    if (m_currentNodeStack.size() > maxDOMTreeDepth)
        handleError(XMLErrors::fatal, "Excessive node nesting.", textPosition());
}

void XMLDocumentParser::popCurrentNode()
{
    if (!m_currentNode)
        return;
    ASSERT(m_currentNodeStack.size());

    if (m_currentNode != document())
        m_currentNode->deref();

    m_currentNode = m_currentNodeStack.last();
    m_currentNodeStack.removeLast();
}

void XMLDocumentParser::clearCurrentNodeStack()
{
    if (m_currentNode && m_currentNode != document())
        m_currentNode->deref();
    m_currentNode = nullptr;
    m_leafTextNode = nullptr;

    if (m_currentNodeStack.size()) { // Aborted parsing.
        for (size_t i = m_currentNodeStack.size() - 1; i != 0; --i)
            m_currentNodeStack[i]->deref();
        if (m_currentNodeStack[0] && m_currentNodeStack[0] != document())
            m_currentNodeStack[0]->deref();
        m_currentNodeStack.clear();
    }
}

void XMLDocumentParser::insert(SegmentedString&&)
{
    ASSERT_NOT_REACHED();
}

void XMLDocumentParser::append(RefPtr<StringImpl>&& inputSource)
{
    String source { WTFMove(inputSource) };

    if (m_sawXSLTransform || !m_sawFirstElement)
        m_originalSourceForTransform.append(source);

    if (isStopped() || m_sawXSLTransform)
        return;

    if (m_parserPaused) {
        m_pendingSrc.append(source);
        return;
    }

    doWrite(source);

    // After parsing, dispatch image beforeload events.
    ImageLoader::dispatchPendingBeforeLoadEvents();
}

void XMLDocumentParser::handleError(XMLErrors::ErrorType type, const char* m, TextPosition position)
{
    if (!m_xmlErrors)
        m_xmlErrors = std::make_unique<XMLErrors>(*document());
    m_xmlErrors->handleError(type, m, position);
    if (type != XMLErrors::warning)
        m_sawError = true;
    if (type == XMLErrors::fatal)
        stopParsing();
}

void XMLDocumentParser::createLeafTextNode()
{
    if (m_leafTextNode)
        return;

    ASSERT(m_bufferedText.size() == 0);
    ASSERT(!m_leafTextNode);
    m_leafTextNode = Text::create(m_currentNode->document(), "");
    m_currentNode->parserAppendChild(*m_leafTextNode);
}

bool XMLDocumentParser::updateLeafTextNode()
{
    if (isStopped())
        return false;

    if (!m_leafTextNode)
        return true;

    // This operation might fire mutation event, see below.
    m_leafTextNode->appendData(String::fromUTF8(reinterpret_cast<const char*>(m_bufferedText.data()), m_bufferedText.size()));
    m_bufferedText = { };

    m_leafTextNode = nullptr;

    // Hence, we need to check again whether the parser is stopped, since mutation
    // event handlers executed by appendData might have detached this parser.
    return !isStopped();
}

void XMLDocumentParser::detach()
{
    clearCurrentNodeStack();
    ScriptableDocumentParser::detach();
}

void XMLDocumentParser::end()
{
    // XMLDocumentParserLibxml2 will do bad things to the document if doEnd() is called.
    // I don't believe XMLDocumentParserQt needs doEnd called in the fragment case.
    ASSERT(!m_parsingFragment);

    doEnd();

    // doEnd() call above can detach the parser and null out its document.
    // In that case, we just bail out.
    if (isDetached())
        return;

    // doEnd() could process a script tag, thus pausing parsing.
    if (m_parserPaused)
        return;

    if (m_sawError) {
        insertErrorMessageBlock();
        if (isDetached()) // Inserting an error message may have ran arbitrary scripts.
            return;
    } else {
        updateLeafTextNode();
        document()->styleScope().didChangeStyleSheetEnvironment();
    }

    if (isParsing())
        prepareToStopParsing();
    document()->setReadyState(Document::Interactive);
    clearCurrentNodeStack();
    document()->finishedParsing();
}

void XMLDocumentParser::finish()
{
    // FIXME: We should ASSERT(!m_parserStopped) here, since it does not
    // makes sense to call any methods on DocumentParser once it's been stopped.
    // However, FrameLoader::stop calls DocumentParser::finish unconditionally.

    Ref<XMLDocumentParser> protectedThis(*this);

    if (m_parserPaused)
        m_finishCalled = true;
    else
        end();
}

void XMLDocumentParser::insertErrorMessageBlock()
{
    ASSERT(m_xmlErrors);
    m_xmlErrors->insertErrorMessageBlock();
}

void XMLDocumentParser::notifyFinished(PendingScript& pendingScript)
{
    ASSERT(&pendingScript == m_pendingScript.get());

    // JavaScript can detach this parser, make sure it's kept alive even if detached.
    Ref<XMLDocumentParser> protectedThis(*this);

    m_pendingScript = nullptr;
    pendingScript.clearClient();

    pendingScript.element().executePendingScript(pendingScript);

    if (!isDetached() && !m_requestingScript)
        resumeParsing();
}

bool XMLDocumentParser::isWaitingForScripts() const
{
    return m_pendingScript;
}

void XMLDocumentParser::pauseParsing()
{
    ASSERT(!m_parserPaused);

    if (m_parsingFragment)
        return;

    m_parserPaused = true;
}

bool XMLDocumentParser::parseDocumentFragment(const String& chunk, DocumentFragment& fragment, Element* contextElement, ParserContentPolicy parserContentPolicy)
{
    if (!chunk.length())
        return true;

    // FIXME: We need to implement the HTML5 XML Fragment parsing algorithm:
    // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-xhtml-syntax.html#xml-fragment-parsing-algorithm
    // For now we have a hack for script/style innerHTML support:
    if (contextElement && (contextElement->hasLocalName(HTMLNames::scriptTag->localName()) || contextElement->hasLocalName(HTMLNames::styleTag->localName()))) {
        fragment.parserAppendChild(fragment.document().createTextNode(chunk));
        return true;
    }

    RefPtr<XMLDocumentParser> parser = XMLDocumentParser::create(fragment, contextElement, parserContentPolicy);
    bool wellFormed = parser->appendFragmentSource(chunk);
    // Do not call finish(). The finish() and doEnd() implementations touch the main document and loader and can cause crashes in the fragment case.
    parser->detach(); // Allows ~DocumentParser to assert it was detached before destruction.
    return wellFormed; // appendFragmentSource()'s wellFormed is more permissive than Document::wellFormed().
}

} // namespace WebCore


text:
/**
 *
 */
package org.ringr.tally.controller.admin;

import java.util.Arrays;

import org.ringr.tally.exception.RestBizException;
import org.ringr.tally.po.Role;
import org.ringr.tally.service.RoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author ptzhuf
 *
 */
@Controller
public class RoleAdminController {

	/**
	 * logger.
	 */
	private static final Logger LOG = LoggerFactory
			.getLogger(RoleAdminController.class);
	@Autowired
	private RoleService roleService;

	/**
	 * 新增角色.
	 *
	 * @param rolename
	 *            角色串
	 * @return
	 */
	@RequestMapping(value = "/admin/role", method = RequestMethod.POST)
	public @ResponseBody Role saveRole(String rolename) {

		try {
			Role result = roleService.save(rolename);
			return result;
		} catch (Exception e) {
			String msg = "调用saveRole出错 : {" + e.getMessage() + "}";
			String errMsg = new StringBuilder(msg).append(", 请求参数为:[{}]")
					.toString();
			LOG.error(errMsg, Arrays.asList(new Object[] { rolename }));
			LOG.error("错误信息:", e);
			throw new RestBizException(msg, e);
		}
	}
}


text:
package com.kaja.openmbta;

import android.webkit.WebView;
import android.app.Activity;
import android.content.Intent;

import android.os.Bundle;

import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class WebViewer extends Activity {

	private String ext_URL;
	private String ext_title;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.webview);

        ext_URL = "http://openmbta.org/mobile";

        Bundle extras = getIntent().getExtras();
		if (extras !=null){
			ext_URL = extras.getString("sURL");
			ext_title = extras.getString("sTitle");
		}

		setTitle(ext_title);
       WebView webview = (WebView) findViewById(R.id.webview);
       webview.loadUrl(ext_URL);

    }
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:background="@drawable/bg_border"
              android:orientation="vertical"
              tools:context="hearsilent.fragment.FirstFragment">

	<android.support.v7.widget.AppCompatButton
		android:id="@+id/button"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_gravity="center"
		android:text="First Fragment"/>

	<LinearLayout
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:layout_gravity="center"
		android:layout_marginTop="30sp"
		android:gravity="center"
		android:orientation="horizontal">

		<android.support.v7.widget.AppCompatTextView
			android:id="@+id/textView1"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:layout_weight="1"
			android:textSize="21sp"/>

		<android.support.v7.widget.AppCompatTextView
			android:id="@+id/textView2"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:layout_weight="1"
			android:textSize="21sp"/>
	</LinearLayout>
</LinearLayout>


text:
stx_db_postgres Cookbook
========================
TODO: Enter the cookbook description here.

e.g.
This cookbook makes your favorite breakfast sandwhich.

Requirements
------------
TODO: List your cookbook requirements. Be sure to include any requirements this cookbook has on platforms, libraries, other cookbooks, packages, operating systems, etc.

e.g.
#### packages
- `toaster` - stx_db_postgres needs toaster to brown your bagel.

Attributes
----------
TODO: List you cookbook attributes here.

e.g.
#### stx_db_postgres::default

    Key
    Type
    Description
    Default

    <tt>['stx_db_postgres']['bacon']</tt>
    Boolean
    whether to include bacon
    <tt>true</tt>

Usage
-----
#### stx_db_postgres::default
TODO: Write usage instructions for each cookbook.

e.g.
Just include `stx_db_postgres` in your node's `run_list`:

```json
{
  "name":"my_node",
  "run_list": [
    "recipe[stx_db_postgres]"
  ]
}
```

Contributing
------------
TODO: (optional) If this is a public cookbook, detail the process for contributing. If this is a private cookbook, remove this section.

e.g.
1. Fork the repository on Github
2. Create a named feature branch (like `add_component_x`)
3. Write you change
4. Write tests for your change (if applicable)
5. Run the tests, ensuring they all pass
6. Submit a Pull Request using Github

License and Authors
-------------------
Authors: TODO: List authors


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace EchonestApi.Core
{
    /// <summary>
    /// An object that performs request to echonest server
    /// </summary>
    internal class EchoRequest
    {
        private readonly Uri _uri;
        private readonly string _method;
        private readonly Dictionary<string, object> _parameters;

        public EchoRequest(Uri uri)
        {
            _uri = uri;
            _method = "GET";
        }

        public EchoRequest(Uri uri, Dictionary<string, object> parameters, string method = "GET")
        {
            _uri = uri;
            _method = method;
            _parameters = parameters;
        }

        public async Task<JObject> Execute()
        {
            if (!NetworkInterface.GetIsNetworkAvailable())
                throw new Exception("Network is not available.");

            var uri = GetFullUri();
#if DEBUG
            Debug.WriteLine("Invoking " + uri);
#endif

            JObject response = null;

            var httpClient = new HttpClient();
            if (_method == "GET")
            {
                HttpResponseMessage responseMessage = await httpClient.GetAsync(uri);
                var content = await responseMessage.Content.ReadAsStringAsync();
                if (!string.IsNullOrEmpty(content))
                    response = JObject.Parse(content);
            }

            return response;
        }

        private Uri GetFullUri()
        {
            if (_method == "GET" && _parameters != null && _parameters.Count > 0)
            {
                var paramStr = string.Join("&",
                                           _parameters.Select(
                                               kp =>
                                               {
                                                   if (kp.Value is IEnumerable && !(kp.Value is string))
                                                   {
                                                       var l = new List<string>();
                                                       foreach (var v in (IEnumerable)kp.Value)
                                                       {
                                                           l.Add(string.Format("{0}={1}",
                                                               Uri.EscapeDataString(kp.Key),
                                                               Uri.EscapeDataString(v.ToString())));
                                                       }

                                                       return string.Join("&", l);
                                                   }
                                                   else return string.Format("{0}={1}", Uri.EscapeDataString(kp.Key),
                                                           Uri.EscapeDataString(kp.Value.ToString()));
                                               }));

                return new Uri(string.Concat(_uri, "?", paramStr));
            }

            return _uri;
        }
    }
}


text:
/**
* jsProScheSim.js
* Javascript (Simple) Process Scheduling Simulator

var sim = new Simulator();

sim.loadData(json);

sim.setProcessors(3);

sim.addQueue('hola', 1, 'FCFS');

sim.addProcess('A', 'hola', 1, 3, [0,1,0,0,1,1,1,0]);

var status = sim.getStatus();

var result = sim.nextStep();

Process status {
-1 - Not arrived yet
0 - Prepared
1 - Executing
2 - I/O
3 - Blocked
4 - Finished
}
*/

$.arrayIntersect = function(a, b) {
  return $.grep(a, function(i) {
    return $.inArray(i, b) > -1;
  });
};

var Process = function(name, queue, arrivalTime, priority, execs) {
  this.name = name;
  this.queue = queue;
  this.arrivalTime = arrivalTime;
  this.priority = priority;
  this.execs = execs;
  this.status = -1;
};

var Policy = function(name, algorithm) {
  this.name = name;
  this.algorithm = algorithm;
};

var Queue = function(name, priority, policy, quantum) {
  this.name = name;
  this.priority = priority;
  this.policy = policy;
  this.finished = false;
  this.quantum = typeof quantum !== 'undefined' ? quantum : 1;
};

var fcfs_algorithm = function(processes) {
  processes.sort(function(a, b) {
    if(a.arrivalTime < b.arrivalTime) {
      return -1;
    }
    if(a.arrivalTime > b.arrivalTime) {
      return 1;
    }
    if(a.arrivalTime == b.arrivalTime) {
      if(a.priority < b.priority) {
        return -1;
      }
      if(a.priority > b.priority) {
        return 1;
      }
    }
    return 0;
  });
};

var roundRobin_algorithm = function(processes) {
  if(processes.length > 0) {
    processes.push(processes[0]);
    processes.shift();
  }
};

var srt_algorithm = function(processes) {
  processes.sort(function(a, b) {
    if(a.execs.length < b.execs.length) {
      return -1;
    }
    if(a.execs.length > b.execs.length) {
      return 1;
    }
    if(a.execs.length == b.execs.length) {
      if(a.priority < b.priority) {
        return -1;
      }
      if(a.priority > b.priority) {
        return 1;
      }
    }
    return 0;
  });
};

var Simulation = function() {
  this.processors = 1;
  this.processes = [];
  this.isPreemptive = true;
  this.queues = [];
  this.policies = {};
  this.currentTime = 0;
  this.finished = false;

  this.policies['FCFS'] = fcfs_algorithm;
  this.policies['RoundRobin'] = roundRobin_algorithm;
  this.policies['SRT'] = srt_algorithm;

  this.setProcessors = function(n) {
    this.processors = n;
  };

  this.addQueue = function(name, priority, policy) {
    var q = new Queue(name, priority, this.getPolicy(policy));
    this.queues.push(q);
  };

  this.addQueue = function(name, priority, policy, quantum) {
    var q = new Queue(name, priority, this.getPolicy(policy), quantum);
    this.queues.push(q);
  };

  this.addProcess = function(name, queue, arrivalTime, priority, execs) {
    var p = new Process(name, this.getQueue(queue), arrivalTime, priority, execs);
    this.processes.push(p);
  };

  this.getStatus = function() {
    return {
      'finished': this.finished,
      'currentTime': this.currentTime,
      'processes': this.processes,
      'queues': this.queues
    };
  };

  this.nextStep = function() {
    this.currentTime += 1;
    var currentTime = this.currentTime;
    var isSimFinished = true;
    var usedCPU = 0;

    for(var i in this.queues) {
      var queue = this.queues[i];
      var isQueueFinished = true;
      //console.log("Checking queue " + queue.name);
      if(queue.finished) continue;

      var allProcessesInQueue = this.processes.filter(function(p) {
        return p.queue.name == queue.name && p.status != 4;
      });
      if(allProcessesInQueue.length > 0) {
        isQueueFinished = false;
        isSimFinished = false;
        isAllFinished = false;
      }

      var processesInQueue = this.processes.filter(function(p) {
        return p.queue.name == queue.name && p.arrivalTime <= currentTime && p.status != 4;
      });
      //console.log("\tThere are " + processesInQueue.length + " processes in queue");
      queue.policy(processesInQueue);

      if(processesInQueue.length == 0) continue;

      for(p in processesInQueue) {
        //console.log("\tChecking process " + processesInQueue[p].name);
        if(processesInQueue[p].execs.length == 0) {
          processesInQueue[p].status = 4;
          continue;
        }

        if(processesInQueue[p].status != 4) {
          isQueueFinished = false;
          isSimFinished = false;
          isAllFinished = false;
        }

        if(processesInQueue[p].execs[0] == 1) {
          processesInQueue[p].execs.shift();
          processesInQueue[p].status = 2;
          console.log("Process " + processesInQueue[p].name + " goes I/O");
          continue;
        }
        if(usedCPU < this.processors) {
          console.log("Process " + processesInQueue[p].name + " goes CPU");
          processesInQueue[p].execs.shift();
          processesInQueue[p].status = 1;
          usedCPU += 1;
        }
        else if(processesInQueue[p].status == 1 || processesInQueue[p].status == 3) {
          console.log("Process " + processesInQueue[p].name + " goes Blocked");
          processesInQueue[p].status = 3;
        }
        else {
          console.log("Process " + processesInQueue[p].name + " goes Prepared");
          processesInQueue[p].status = 0;
        }
      }
      if(isQueueFinished) queue.finished = true;
    }
    if(isSimFinished) this.finished = true;
  };

  this.getQueue = function(name) {
    for(var i in this.queues) {
      if(this.queues[i].name == name) return this.queues[i];
    }
  }

  this.getPolicy = function(name) {
    return this.policies[name];
  };

  this.newPolicy = function(name, algorithm) {
    this.policies[name] = algorithm;
  };

};


text:
id: 5900f4841000cf542c50ff97
challengeType: 5
title: 'Problem 280: Ant and seeds'
---

## Description

A laborious ant walks randomly on a 5x5 grid. The walk starts from the central square. At each step, the ant moves to an adjacent square at random, without leaving the grid; thus there are 2, 3 or 4 possible moves at each step depending on the ant's position.

At the start of the walk, a seed is placed on each square of the lower row. When the ant isn't carrying a seed and reaches a square of the lower row containing a seed, it will start to carry the seed. The ant will drop the seed on the first empty square of the upper row it eventually reaches.

What's the expected number of steps until all seeds have been dropped in the top row?
Give your answer rounded to 6 decimal places.

## Instructions

## Tests

```yml
tests:
  - text: <code>euler280()</code> should return 430.088247.
    testString: assert.strictEqual(euler280(), 430.088247, '<code>euler280()</code> should return 430.088247.');

```

## Challenge Seed

```js
function euler280() {
  // Good luck!
  return true;
}

euler280();
```

## Solution

```js
// solution required
```


text:
***

## Noise Alert

The app connects to the microphone and sends out an alert to specified phone number if the volume is above the set threshold for a second

[Demo](http://valex-tech.com/sendhub/#/home)

***
Used ngBoilerplate


text:
namespace kepler {
namespace gl {

/// RenderState controls the fixed-function GL states and functions when rendering a primitive.
///
/// RenderState remembers the previous global state and will make changes only when needed.
/// That means you shouldn't change GL states without using RenderState.
///
/// For example, if you call glDepthMask(GL_FALSE), the next primitive to draw won't know that depth writing was disabled.
/// GL_DITHER is not managed by RenderState so you can call glDisable(GL_DITHER).
class RenderState {
public:
    RenderState();
    virtual ~RenderState() noexcept = default;

    /// Binds the RenderState and applies its changes to the global GL state.
    void bind() const noexcept;

    /// Sets the blend color.
    void setBlendColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);

    /// Sets the equation used for both the RGB blend equation and the Alpha blend equation.
    /// @param[in] mode Specifies how source and destination colors are combined. Must be GL_FUNC_ADD, GL_FUNC_SUBTRACT, GL_FUNC_REVERSE_SUBTRACT, GL_MIN, GL_MAX.
    void setBlendEquation(GLenum mode);
    /// Sets the RGB blend equation and the alpha blend equation separately.
    void setBlendEquationSeparate(GLenum modeRGB, GLenum modeAlpha);

    /// Sets pixel arithmetic for blending.
    /// @param[in] sfactor Source RGBA factor.
    /// @param[in] dfactor Destination RGBA factor.
    void setBlendFunc(GLenum sfactor, GLenum dfactor);

    /// Sets the pixel arithmetic for RGB and alpha components separately.
    /// @param[in] srcRGB   Source RGB.
    /// @param[in] dstRGB   Destination RGB.
    /// @param[in] srcAlpha Source alpha.
    /// @param[in] dstAlpha Destination alpha.
    void setBlendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);

    /// Sets which color channels are writable.
    void setColorMask(bool red, bool green, bool blue, bool alpha);

    /// Sets which polygon face should be culled if culling is enabled.
    /// @param[in] mode GL_FRONT, GL_BACK, or GL_FRONT_AND_BACK.
    void setCullFace(GLenum mode);

    /// Sets the depth comparison function.
    /// GL_NEVER, GL_LESS, GL_EQUAL, GL_LEQUAL, GL_GREATER, GL_NOTEQUAL, GL_GEQUAL, GL_ALWAYS.
    /// @param[in] func
    void setDepthFunc(GLenum func);

    /// Enables or disables the writing into the depth buffer.
    /// @param[in] flag True to enable the depth buffer; false to disable.
    void setDepthMask(bool flag);

    void setDepthRange(GLfloat near, GLfloat far);

    /// Sets which winding is the front face of then polygon.
    void setFrontFace(GLenum mode);

    /// Sets the line width.
    /// Line widths greather than 1 may not be supported. Query GL_ALIASED_LINE_WIDTH_RANGE to find the supported line widths.
    void setLineWidth(GLfloat width);
    void setPolygonOffset(GLfloat factor, GLfloat units);

    /// Sets the scissor box.
    /// Be sure to enable the scissor test.
    void setScissor(GLint x, GLint y, GLsizei width, GLsizei height);

    // Togglable states

    bool isBlendEnabled() const noexcept;
    bool isCullingEnabled() const noexcept;
    bool isDepthTestEnabled() const noexcept;
    bool isPolygonOffsetFillEnabled() const noexcept;
    bool isPrimitiveRestartFixedIndexEnabled() const noexcept;
    bool isRasterizerDiscardEnabled() const noexcept;
    bool isSampleAlphaToCoverageEnabled() const noexcept;
    bool isSampleCoverageEnabled() const noexcept;
    bool isSampleMaskEnabled() const noexcept;
    bool isScissorTestEnabled() const noexcept;
    bool isStencilTestEnabled() const noexcept;

    void setBlend(bool value);
    void setCulling(bool value);
    void setDepthTest(bool value);
    void setPolygonOffsetFill(bool value);
    void setPrimitiveRestartFixedIndex(bool value);
    void setRasterizerDiscard(bool value);
    void setSampleAlphaToCoverage(bool value);
    void setSampleCoverage(bool value);
    void setSampleMask(bool value);
    void setScissorTest(bool value);
    void setStencilTest(bool value);

    /// Sets the global depth mask.
    /// This is useful for setting the depth mask before clearing the depth buffer.
    static void setGlobalDepthMask(bool flag);

private:
    RenderState(const RenderState&) = delete;
    RenderState& operator=(const RenderState&) = delete;
private:

    void bindStateBlock() const noexcept;

    struct BlendState {
        GLenum modeRGB;
        GLenum modeAlpha;
        GLenum srcRGB;
        GLenum dstRGB;
        GLenum srcAlpha;
        GLenum dstAlpha;
        GLfloat red;
        GLfloat green;
        GLfloat blue;
        GLfloat alpha;
        BlendState();
        void bind() const noexcept;
    };

    struct DepthState {
        GLenum func;
        GLfloat near;
        GLfloat far;
        GLboolean mask;
        DepthState();
        void bind() const noexcept;
    };

    struct CullState {
        GLenum cullFace;
        GLenum frontFace;
        CullState();
        void bind() const noexcept;
    };

    struct PolygonOffset {
        GLfloat factor;
        GLfloat units;
        PolygonOffset();
        void bind() const noexcept;
    };

    struct Scissor {
        GLint x;
        GLint y;
        GLsizei width;
        GLsizei height;
        Scissor();
    };

private:
    int _state;
    GLubyte _colorMask;
    GLfloat _lineWidth;

    BlendState _blend;
    DepthState _depth;
    CullState _cull;
    PolygonOffset _polygonOffset;
    Scissor _scissor;
};
}
}


text:
title: Telerik.Web.UI.CheckBoxListSelectedIndexChangedEventArgs
description:
slug: Telerik.Web.UI.CheckBoxListSelectedIndexChangedEventArgs
---

# Telerik.Web.UI.CheckBoxListSelectedIndexChangedEventArgs : Sys.EventArgs

## Methods

###  get_newSelectedIndex

Returns the index of the selected item.

#### Parameters

#### Returns

`Number`


text:
package helpdesk.utils;

import helpdesk.beans.Equipamento;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;

public class EquipamentoTableModel extends AbstractTableModel {

    private List<Equipamento>equipamentos;
    private String[]colunas={"Código","Descricao","Marca","Endereço IP","Nº de Série","Setor"};
    private static final int CODIGO=0;
    private static final int DESCRICAO=1;
    private static final int MARCA=2;
    private static final int ENDERECOIP=3;
    private static final int NUMEROSERIE=4;
    private static final int SETOR=5;

    public EquipamentoTableModel() {
        equipamentos=new ArrayList<>();
    }
    public EquipamentoTableModel(List<Equipamento>listaDeEquipamentos) {
        equipamentos=new ArrayList<>(listaDeEquipamentos);
    }

    public void addChamado(Equipamento e){
        equipamentos.add(e);
    }

    @Override
    public int getRowCount() {
        return this.equipamentos.size();
    }

    @Override
    public int getColumnCount() {
        return colunas.length;
    }

    @Override
    public String getColumnName(int columnIndex){
        return colunas[columnIndex];
    }

    @Override
    public Class<?>getColumnClass(int columnIndex){
        switch(columnIndex){
            case CODIGO:
                return String.class;
            case DESCRICAO:
                return String.class;
            case MARCA:
                return String.class;
            case ENDERECOIP:
                return String.class;
            case NUMEROSERIE:
                return String.class;
            case SETOR:
                return String.class;
            default:
                return String.class;
        }
    }

    @Override
    public boolean isCellEditable(int rowIndex,int columnIndex){
        return false;
    }

    @Override
    public Object getValueAt(int rowIndex,int columnIndex){
        Equipamento e= equipamentos.get(rowIndex);
        switch(columnIndex){
            case CODIGO:
                return e.getId();
            case DESCRICAO:
                return e.getDescricao();
            case MARCA:
               return e.getNomeMarca();
            case ENDERECOIP:
               return e.getIp();
            case NUMEROSERIE:
               return e.getNumeroSerie();
            case SETOR:
               return e.getNomeSetor();
            default:
                 //throw new IndexOutOfBoundsException("columnIndex out of bounds");
                return new Integer(0);
        }

    }
    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex){

        Equipamento e=equipamentos.get(rowIndex);
        switch(columnIndex){
            case CODIGO:
               e.setId((Long)aValue);
            case DESCRICAO:
                e.setDescricao((String)aValue);
            case MARCA:
                e.setNomeMarca((String)aValue);
            case ENDERECOIP:
                e.setIp((String)aValue);
            case NUMEROSERIE:
                e.setNumeroSerie((String)aValue);
            case SETOR:
                e.setNomeSetor((String)aValue);
            default:
                throw new IndexOutOfBoundsException("columnIndex out of bounds");

        }
        //fireTableCellUpdated(rowIndex, columnIndex);

    }

    public List<Equipamento> remove(Equipamento c){
        equipamentos.remove(c);
        return equipamentos;
    }
    public Equipamento getProduto(int rowIndex,int columnIndex){
        return equipamentos.get(rowIndex);
    }

}