text:
<TITLE>Review for What Lies Beneath (2000)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

What Lies Beneath (2000)

reviewed by
Shannon Patrick Sullivan

WHAT LIES BENEATH (2000) / ***

Directed by Robert Zemeckis. Screenplay by Clark Gregg, from a story by
Sarah Kernochan and Gregg. Starring Michelle Pfeiffer, Harrison Ford,
Diana Scarwid. Running time: 129 minutes. Rated AA by the MFCB. Reviewed
on July 25th, 2000.

By SHANNON PATRICK SULLIVAN

When I went to see "The Sixth Sense" for the first time last year, I was
dismayed by how much of the first two-thirds of the film was spoiled by
the trailer. The movie was obviously constructed with the assumption that
the viewer was unaware Haley Joel Osment's character could see dead
people. Otherwise, the entire opening act constituted a thinly-veiled
exercise in misdirection, and I have more respect for the picture than
to believe that. In the end, although I was very much entertained "The
Sixth Sense", I was left wondering how much more enthralled I would have
been had so much not been revealed to me in the promotional material.

A year later, and wouldn't you know that history has repeated itself.
This time, the offending party is the preview for "What Lies Beneath", the
new thriller starring Michelle Pfeiffer and Harrison Ford, and directed by
Robert Zemeckis ("Back To The Future", "Forrest Gump"). As
poorly-conceived as the trailer for "The Sixth Sense" was, its "What Lies
Beneath" counterpart is infinitely more risible. In this day and age of
inspired, creative marketing strategies like the "Blair Witch Project"
website and the "X-Men" political campaign, it amazes me that we are
still forced to endure such hamfisted efforts as this one.

However, I refuse to review "What Lies Beneath" on the basis of its
trailer alone (although I am rather appalled that Zemeckis has actually
condoned it because, essentially, he doesn't think people will see his
movie without knowing the plot beforehand). It is true to say that my
enjoyment of the film was hampered because I had too much foreknowledge of
the events. But I will make every effort to set this aside, and review
"What Lies Beneath" on its own merits.

As the film opens, Norman Spencer (Ford) and his wife Claire (Pfeiffer)
are seeing their daughter off to college, leaving just the two of them
alone in their old lakeside Vermont cottage. Spencer is a genetics
professor who sometimes seems married more to his work than to his wife.
As a result, Claire is often left alone in the house. When neighbour
Warren Feur's wife Mary (Miranda Otto) goes missing after an argument,
strange things start happening. Doors open by themselves, electronics
misbehave, and Claire thinks she sees a face in the water. She becomes
convinced that Warren (James Remar) has murdered his wife, and that she is
now being haunted by Mary's ghost. Norman, however, thinks his wife is
going insane.

With "What Lies Beneath", Zemeckis is clearly trying to evoke Hitchcock.
Most obviously, the entire subplot about the Feurs is a lift right out of
my own all-time favourite movie, "Rear Window", as Claire spies on the
neighbours through binoculars and finds disturbing but circumstantial
evidence of foul play. But here is one way the trailer helps to undermine
the picture (and if you haven't seen it, skip to the next paragraph now).
We know that the ghost isn't Mary Feur, so the entire sequence -- which
occupies most of the first half of the movie -- feels exactly like the
elaborate red herring that it is. As a result, I found myself impatiently
wanting the movie to just get on with it.

Zemeckis does successfully create a creepy atmosphere; there are plenty of
scares in "What Lies Beneath", and some of the effects (the face in the
water, a message in the condensation on a bathroom mirror) are understated
but work very well. The movie is cheapened, though, by the use of several
thriller cliches -- the sudden appearance of a family pet, the best friend
with coincidental occult inclinations, the killer who just won't die. Most
notably, Zemeckis badly overuses the device of having a character suddenly
appear in the frame. This was effective the first few times, but it got
rather silly when I lost track of the number of times it occurred.

Helping to foster the sinister atmosphere is a fine performance by
Pfeiffer, whose character is vulnerable and confused, but not weak. She
remains a captivating actor, able to communicate more with her eyes than
many performers can with their whole body. Pfeiffer is particularly good
in scenes where she becomes possessed by the ghost, seemlessly assuming
an persona without exaggerating the change.

Ford starts off weakly, mumbling his way through the early scenes, but
finds his stride in the latter half. It is good to see the actor return to
roles with a bit of an edge to them, unlike the straight-laced,
do-no-wrong heroes he has portrayed for much of the past decade in films
like "Patriot Games" and "Air Force One". Ford was always at his best
playing characters with something of an anti-hero bent, like Han Solo or
"Blade Runner"'s Deckard, and to an extent, "What Lies Beneath" is
reminiscent of that.

"What Lies Beneath" rides a consistent upward curve, as the supernatural
events (or are they?) continue and Claire gets closer and closer to
uncovering the secret behind the apparitions. Things fall off the rails a
bit when the identity of the villain (which, I'll admit, came as a
surprise to me) is finally revealed and the film takes a plunge into
"Scream"-type slasher fare. Rather extreme measures are taken to demonise
the character (like a reference to the villain's attention focussing next
on Claire's daughter) which come across as more than a little
heavy-handed. But things end well with a spooky, beautifully photographed
climax which is carried out with just enough conviction to make it work.

Although it by no means achieves the heights of deep-rooted, psychological
terror as, say, "The Blair Witch Project", "What Lies Beneath" is very
successful on a more visceral level, and is certainly one of the scarier
movies of recent times. It's not the sort of film that will give you
nightmares -- the frights are too immediate and short-sighted for
that -- but it is a lot of fun all the same.

But oh, that trailer...

Copyright © 2000 Shannon Patrick Sullivan.
Archived at The Popcorn Gallery,
  http://www.physics.mun.ca/~sps/movies/WhatLiesBeneath.html

  _______________________________________________________________________
 / Shannon Patrick Sullivan  | "We are all in the gutter, but some of us \
|       shannon@mun.ca       |  are looking at the stars." - Oscar Wilde |
 \___________________________|__________________________________________/
  | Popcorn Gallery Movie Reviews    www.physics.mun.ca/~sps/movies.html |
  | Doctor Who: A Brief History of Time (Travel)            /drwho.html  |

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
package com.cc3002.auxiliar.design.pattern.composite.example07.test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import com.cc3002.auxiliar.design.pattern.composite.example07.IMenuItem;
import com.cc3002.auxiliar.design.pattern.composite.example07.MenuEvent;
import com.cc3002.auxiliar.design.pattern.composite.example07.MenuItem;

import org.junit.Before;
import org.junit.Test;

public class MenuItemTest {

  private String name;
  private String description;
  private double price;
  private IMenuItem item;
  private int results;

  /**
   * Initialize test case.
   */
  @Before
  public void setUp() {
    name = "Item name";
    description = "Item description";
    price = 3.47;
    item = new MenuItem(name, description, true, price);
  }

  @Test
  public void testGetName() {
    assertEquals("Expects same name", name, item.getName());
  }

  @Test
  public void testGetDescription() {
    assertEquals("Expects same description", description, item.getDescription());
  }

  @Test
  public void testPrice() {
    assertEquals("Expects same price", price, item.getPrice(), 0.0d);
  }

  @Test
  public void testIsVegetarianYes() {
    assertTrue("Expects vegetarian item", item.isVegetarian());
  }

  @Test
  public void testIsVegetarianNo() {
    assertFalse("Expects not vegetarian item",
        new MenuItem(name, description, false, price).isVegetarian());
  }

  @Test
  public void testSetPrice() {
    item.setPrice(2.0);
    assertEquals("Expects new price", 2.0, item.getPrice(), 0.0d);
  }

  @Test
  public void testNotifyPriceChange() {
    item.addObserver(MenuEvent.PRICE_CHANGE, this::onPriceChange);
    item.setPrice(2.0);
    assertEquals("Expects price change notification.", 1, results);
  }

  public void onPriceChange(final MenuEvent event) {
    results += 1;
  }

  @Test
  public void testNoPriceChange() {
    testNotifyPriceChange();
    item.setPrice(2.0);
    assertEquals("Expects price change notification.", 1, results);
  }
}

redpajama_set_name: RedPajamaGithub


text:
module MonetDB
  class Connection
    module IO
    private

      def read
        raise ConnectionError, "Not connected to server" unless connected?

        length, last_chunk = read_length
        data, iterations = "", 0

        while (length > 0) && (iterations < 1000) do
          received = socket.recv(length)
          data << received
          length -= received.bytesize
          iterations += 1
        end
        data << read unless last_chunk

        data
      end

      def read_length
        bytes = socket.recv(2).unpack("v")[0]
        [(bytes >> 1), (bytes & 1) == 1]
      end

      def write(message)
        raise ConnectionError, "Not connected to server" unless connected?
        pack(message).each do |chunk|
          socket.write(chunk)
        end
        true
      end

      def pack(message)
        chunks = message.scan(/.{1,#{MAX_MSG_SIZE}}/m)
        chunks.each_with_index.to_a.collect do |chunk, index|
          last_bit = (index == chunks.size - 1) ? 1 : 0
          length = [(chunk.bytes.to_a.size << 1) | last_bit].pack("v").force_encoding('utf-8')
          "#{length}#{chunk}"
        end.freeze
      end

    end
  end
end


text:
package com.asi.ext.api.tools;

import java.util.List;

import com.asi.ext.api.radar.model.CriteriaSetCodeValues;
import com.asi.ext.api.radar.model.CriteriaSetValues;
import com.asi.ext.api.radar.model.Media;
import com.asi.ext.api.radar.model.PriceGrids;
import com.asi.ext.api.radar.model.Prices;
import com.asi.ext.api.radar.model.PricingItems;
import com.asi.ext.api.radar.model.Product;
import com.asi.ext.api.radar.model.ProductConfigurations;
import com.asi.ext.api.radar.model.ProductCriteriaSets;
import com.asi.ext.api.radar.model.ProductDataSheet;
import com.asi.ext.api.radar.model.ProductInventoryLink;
import com.asi.ext.api.radar.model.ProductKeywords;
import com.asi.ext.api.radar.model.ProductMediaItems;
import com.asi.ext.api.radar.model.SelectedComplianceCerts;
import com.asi.ext.api.radar.model.SelectedProductCategories;
import com.asi.ext.api.radar.model.SelectedSafetyWarnings;
import com.asi.ext.api.radar.model.SetCodeValues;
import com.asi.ext.api.util.ApplicationConstants;
import com.asi.ext.api.util.CommonUtilities;

public class ProductConverter {

    private final String COMPANY_ID    = "9207";
    private final String DATASOURCE_ID = "14236";

    public Product constructRadarProductModel(com.asi.ext.api.service.model.Product serviceProduct) {

        // Set Basic properties
        Product finalProduct = new Product();
        finalProduct.setId(ID);
        finalProduct.setCompanyId(COMPANY_ID);
        finalProduct.setDataSourceId(DATASOURCE_ID);
        finalProduct.setName(serviceProduct.getName());
        finalProduct.setExternalProductId(serviceProduct.getExternalProductId());
        finalProduct.setAsiProdNo(serviceProduct.getAsiProdNo());
        finalProduct.setDescription(serviceProduct.getDescription());
        finalProduct.setSummary(serviceProduct.getSummary());
        finalProduct.setShipperBillsByCode(serviceProduct.getShipperBillsBy());
        // Object Types
        finalProduct.setProductInventoryLink(getProductInventoryLink(serviceProduct.getProductInventoryLink()));
        finalProduct.setProductDataSheet(getProductDataSheet(serviceProduct.getProductDataSheet()));
        // List Elements
        finalProduct.setProductKeywords(getProductKeywords(serviceProduct.getProductKeywords()));
        finalProduct.setSelectedProductCategories(getProductCategories(serviceProduct.getCategories()));
        finalProduct.setSelectedComplianceCerts(getProductComplianceCerts(serviceProduct.getComplianceCerts()));
        finalProduct.setSelectedSafetyWarnings(getSelectedSafetyWarnings(serviceProduct.getSafetyWarnings()));

        // Temporary Product preparations
        ProductConfigurations configurations =  new ProductConfigurations();
        configurations.setProductId(PRODUCT_ID);
        configurations.setIsDefault("true");

        ProductCriteriaSets criteriaSets = new ProductCriteriaSets();
        CriteriaSetValues criteriaSetValue = new CriteriaSetValues();
        CriteriaSetCodeValues criteriaSetCodeValues = new CriteriaSetCodeValues();

        criteriaSetValue.setCriteriaSetCodeValues(new CriteriaSetCodeValues[]{criteriaSetCodeValues});
        criteriaSets.setCriteriaSetValues(new CriteriaSetValues[]{criteriaSetValue});

        PriceGrids priceGrids = new PriceGrids();
        Prices price = new Prices();
        priceGrids.setPrices(new Prices[]{price});
        PricingItems pricingItems = new PricingItems();
        priceGrids.setPricingItems(new PricingItems[]{pricingItems});

        finalProduct.setPriceGrids(new PriceGrids[]{priceGrids});

        ProductMediaItems mediaItems = new ProductMediaItems();
        mediaItems.setMedia(new Media());
        finalProduct.setProductMediaItems(new ProductMediaItems[]{mediaItems});
        /*product.getProductConfigurations()[0].getProductCriteriaSets()[0]
                .getCriteriaSetValues()[0].getCriteriaSetCodeValues()[0].getSetCodeValueId();*/

        configurations.setProductCriteriaSets(new ProductCriteriaSets[]{criteriaSets});
        finalProduct.setProductConfigurations(new ProductConfigurations[]{configurations});
        /*
         * finalProduct.
         * finalProduct.
         */

        return finalProduct;
    }

    public com.asi.ext.api.service.model.Product constructServiceProductModel(Product radarProdModel) {
        return null;
    }

    private final String PRODUCT_ID = ApplicationConstants.CONST_STRING_ZERO;
    private final String ID         = ApplicationConstants.CONST_STRING_ZERO;

    private ProductInventoryLink getProductInventoryLink(String inventoryLink) {
        ProductInventoryLink productInventoryLink = new ProductInventoryLink();
        productInventoryLink.setUrl(inventoryLink);
        productInventoryLink.setProductId(PRODUCT_ID);
        productInventoryLink.setId(ID);

        return productInventoryLink;
    }

    private ProductDataSheet getProductDataSheet(String productDataSheet) {
        ProductDataSheet prodDataSheet = new ProductDataSheet();
        prodDataSheet.setUrl(productDataSheet);
        prodDataSheet.setProductId(PRODUCT_ID);
        prodDataSheet.setId(ID);

        return prodDataSheet;
    }

    private ProductKeywords[] getProductKeywords(List<String> productKeywords) {
        String keywords = CommonUtilities.convertStringListToCSV(productKeywords);
        if (!CommonUtilities.isValueNull(keywords)) {
            ProductKeywords keyword = new ProductKeywords();
            keyword.setId(ID);
            keyword.setProductId(PRODUCT_ID);
            keyword.setValue(keywords);
            return new ProductKeywords[] { keyword };
        } else {
            return new ProductKeywords[] {};
        }
    }

    private SelectedProductCategories[] getProductCategories(List<String> productCategories) {
        String categories = CommonUtilities.convertStringListToCSV(productCategories);
        if (!CommonUtilities.isValueNull(categories)) {
            SelectedProductCategories category = new SelectedProductCategories();
            category.setCode(categories);
            category.setProductId(PRODUCT_ID);
            return new SelectedProductCategories[] { category };
        } else {
            return new SelectedProductCategories[] {};
        }
    }

    private SelectedComplianceCerts[] getProductComplianceCerts(List<String> productComplianceCerts) {
        String complianceCerts = CommonUtilities.convertStringListToCSV(productComplianceCerts);
        if (!CommonUtilities.isValueNull(complianceCerts)) {
            SelectedComplianceCerts selectedCompliance = new SelectedComplianceCerts();
            selectedCompliance.setId(ID);
            selectedCompliance.setProductId(PRODUCT_ID);
            selectedCompliance.setComplianceCertId(complianceCerts);
            return new SelectedComplianceCerts[] { selectedCompliance };
        } else {
            return new SelectedComplianceCerts[] {};
        }
    }

    private SelectedSafetyWarnings[] getSelectedSafetyWarnings(List<String> selectedSafetyWarnings) {
        String safetyWarnings = CommonUtilities.convertStringListToCSV(selectedSafetyWarnings);
        if (!CommonUtilities.isValueNull(safetyWarnings)) {
            SelectedSafetyWarnings safetyWarning = new SelectedSafetyWarnings();
            safetyWarning.setCode(safetyWarnings);
            return new SelectedSafetyWarnings[] { safetyWarning };
        } else {
            return new SelectedSafetyWarnings[] {};
        }
    }

}


text:
package upside_down

import (
	"reflect"
	"testing"

	"github.com/blevesearch/bleve/document"
	"github.com/blevesearch/bleve/index"
	"github.com/blevesearch/bleve/index/store/boltdb"
)

func TestIndexReader(t *testing.T) {
	defer func() {
		err := DestroyTest()
		if err != nil {
			t.Fatal(err)
		}
	}()

	analysisQueue := index.NewAnalysisQueue(1)
	idx, err := NewUpsideDownCouch(boltdb.Name, boltTestConfig, analysisQueue)
	if err != nil {
		t.Fatal(err)
	}
	err = idx.Open()
	if err != nil {
		t.Errorf("error opening index: %v", err)
	}
	defer func() {
		err := idx.Close()
		if err != nil {
			t.Fatal(err)
		}
	}()

	var expectedCount uint64
	doc := document.NewDocument("1")
	doc.AddField(document.NewTextField("name", []uint64{}, []byte("test")))
	err = idx.Update(doc)
	if err != nil {
		t.Errorf("Error updating index: %v", err)
	}
	expectedCount++

	doc = document.NewDocument("2")
	doc.AddField(document.NewTextFieldWithAnalyzer("name", []uint64{}, []byte("test test test"), testAnalyzer))
	doc.AddField(document.NewTextFieldCustom("desc", []uint64{}, []byte("eat more rice"), document.IndexField|document.IncludeTermVectors, testAnalyzer))
	err = idx.Update(doc)
	if err != nil {
		t.Errorf("Error updating index: %v", err)
	}
	expectedCount++

	indexReader, err := idx.Reader()
	if err != nil {
		t.Error(err)
	}
	defer func() {
		err := indexReader.Close()
		if err != nil {
			t.Fatal(err)
		}
	}()

	// first look for a term that doesn't exist
	reader, err := indexReader.TermFieldReader([]byte("nope"), "name")
	if err != nil {
		t.Errorf("Error accessing term field reader: %v", err)
	}
	count := reader.Count()
	if count != 0 {
		t.Errorf("Expected doc count to be: %d got: %d", 0, count)
	}
	err = reader.Close()
	if err != nil {
		t.Fatal(err)
	}

	reader, err = indexReader.TermFieldReader([]byte("test"), "name")
	if err != nil {
		t.Errorf("Error accessing term field reader: %v", err)
	}

	expectedCount = 2
	count = reader.Count()
	if count != expectedCount {
		t.Errorf("Exptected doc count to be: %d got: %d", expectedCount, count)
	}

	var match *index.TermFieldDoc
	var actualCount uint64
	match, err = reader.Next()
	for err == nil && match != nil {
		match, err = reader.Next()
		if err != nil {
			t.Errorf("unexpected error reading next")
		}
		actualCount++
	}
	if actualCount != count {
		t.Errorf("count was 2, but only saw %d", actualCount)
	}

	expectedMatch := &index.TermFieldDoc{
		ID:   "2",
		Freq: 1,
		Norm: 0.5773502588272095,
		Vectors: []*index.TermFieldVector{
			&index.TermFieldVector{
				Field: "desc",
				Pos:   3,
				Start: 9,
				End:   13,
			},
		},
	}
	tfr, err := indexReader.TermFieldReader([]byte("rice"), "desc")
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	match, err = tfr.Next()
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	if !reflect.DeepEqual(expectedMatch, match) {
		t.Errorf("got %#v, expected %#v", match, expectedMatch)
	}
	err = reader.Close()
	if err != nil {
		t.Fatal(err)
	}

	// now test usage of advance
	reader, err = indexReader.TermFieldReader([]byte("test"), "name")
	if err != nil {
		t.Errorf("Error accessing term field reader: %v", err)
	}

	match, err = reader.Advance("2")
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	if match == nil {
		t.Fatalf("Expected match, got nil")
	}
	if match.ID != "2" {
		t.Errorf("Expected ID '2', got '%s'", match.ID)
	}
	match, err = reader.Advance("3")
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	if match != nil {
		t.Errorf("expected nil, got %v", match)
	}
	err = reader.Close()
	if err != nil {
		t.Fatal(err)
	}

	// now test creating a reader for a field that doesn't exist
	reader, err = indexReader.TermFieldReader([]byte("water"), "doesnotexist")
	if err != nil {
		t.Errorf("Error accessing term field reader: %v", err)
	}
	count = reader.Count()
	if count != 0 {
		t.Errorf("expected count 0 for reader of non-existant field")
	}
	match, err = reader.Next()
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	if match != nil {
		t.Errorf("expected nil, got %v", match)
	}
	match, err = reader.Advance("anywhere")
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	if match != nil {
		t.Errorf("expected nil, got %v", match)
	}

}

func TestIndexDocIdReader(t *testing.T) {
	defer func() {
		err := DestroyTest()
		if err != nil {
			t.Fatal(err)
		}
	}()

	analysisQueue := index.NewAnalysisQueue(1)
	idx, err := NewUpsideDownCouch(boltdb.Name, boltTestConfig, analysisQueue)
	if err != nil {
		t.Fatal(err)
	}
	err = idx.Open()
	if err != nil {
		t.Errorf("error opening index: %v", err)
	}
	defer func() {
		err := idx.Close()
		if err != nil {
			t.Fatal(err)
		}
	}()

	var expectedCount uint64
	doc := document.NewDocument("1")
	doc.AddField(document.NewTextField("name", []uint64{}, []byte("test")))
	err = idx.Update(doc)
	if err != nil {
		t.Errorf("Error updating index: %v", err)
	}
	expectedCount++

	doc = document.NewDocument("2")
	doc.AddField(document.NewTextField("name", []uint64{}, []byte("test test test")))
	doc.AddField(document.NewTextFieldWithIndexingOptions("desc", []uint64{}, []byte("eat more rice"), document.IndexField|document.IncludeTermVectors))
	err = idx.Update(doc)
	if err != nil {
		t.Errorf("Error updating index: %v", err)
	}
	expectedCount++

	indexReader, err := idx.Reader()
	if err != nil {
		t.Error(err)
	}
	defer func() {
		err := indexReader.Close()
		if err != nil {
			t.Error(err)
		}
	}()

	// first get all doc ids
	reader, err := indexReader.DocIDReader("", "")
	if err != nil {
		t.Errorf("Error accessing doc id reader: %v", err)
	}
	defer func() {
		err := reader.Close()
		if err != nil {
			t.Fatal(err)
		}
	}()

	id, err := reader.Next()
	count := uint64(0)
	for id != "" {
		count++
		id, err = reader.Next()
	}
	if count != expectedCount {
		t.Errorf("expected %d, got %d", expectedCount, count)
	}

	// try it again, but jump to the second doc this time
	reader2, err := indexReader.DocIDReader("", "")
	if err != nil {
		t.Errorf("Error accessing doc id reader: %v", err)
	}
	defer func() {
		err := reader2.Close()
		if err != nil {
			t.Error(err)
		}
	}()

	id, err = reader2.Advance("2")
	if err != nil {
		t.Error(err)
	}
	if id != "2" {
		t.Errorf("expected to find id '2', got '%s'", id)
	}

	id, err = reader2.Advance("3")
	if err != nil {
		t.Error(err)
	}
	if id != "" {
		t.Errorf("expected to find id '', got '%s'", id)
	}
}

func TestCrashBadBackIndexRow(t *testing.T) {
	br, err := NewBackIndexRowKV([]byte{byte('b'), byte('a'), ByteSeparator}, []byte{})
	if err != nil {
		t.Fatal(err)
	}
	if string(br.doc) != "a" {
		t.Fatal(err)
	}
}


text:
'use strict';

var Registry = require('../../registry');
var helpers = require('./helpers');

module.exports = function getLegendData(calcdata, opts) {
    var inHover = opts._inHover;
    var grouped = helpers.isGrouped(opts);
    var reversed = helpers.isReversed(opts);

    var lgroupToTraces = {};
    var lgroups = [];
    var hasOneNonBlankGroup = false;
    var slicesShown = {};
    var lgroupi = 0;
    var maxNameLength = 0;
    var i, j;

    function addOneItem(legendGroup, legendItem) {
        // each '' legend group is treated as a separate group
        if(legendGroup === '' || !helpers.isGrouped(opts)) {
            // TODO: check this against fullData legendgroups?
            var uniqueGroup = '~~i' + lgroupi;
            lgroups.push(uniqueGroup);
            lgroupToTraces[uniqueGroup] = [legendItem];
            lgroupi++;
        } else if(lgroups.indexOf(legendGroup) === -1) {
            lgroups.push(legendGroup);
            hasOneNonBlankGroup = true;
            lgroupToTraces[legendGroup] = [legendItem];
        } else {
            lgroupToTraces[legendGroup].push(legendItem);
        }
    }

    // build an { legendgroup: [cd0, cd0], ... } object
    for(i = 0; i < calcdata.length; i++) {
        var cd = calcdata[i];
        var cd0 = cd[0];
        var trace = cd0.trace;
        var lgroup = trace.legendgroup;

        if(!inHover && (!trace.visible || !trace.showlegend)) continue;

        if(Registry.traceIs(trace, 'pie-like')) {
            if(!slicesShown[lgroup]) slicesShown[lgroup] = {};

            for(j = 0; j < cd.length; j++) {
                var labelj = cd[j].label;

                if(!slicesShown[lgroup][labelj]) {
                    addOneItem(lgroup, {
                        label: labelj,
                        color: cd[j].color,
                        i: cd[j].i,
                        trace: trace,
                        pts: cd[j].pts
                    });

                    slicesShown[lgroup][labelj] = true;
                    maxNameLength = Math.max(maxNameLength, (labelj || '').length);
                }
            }
        } else {
            addOneItem(lgroup, cd0);
            maxNameLength = Math.max(maxNameLength, (trace.name || '').length);
        }
    }

    // won't draw a legend in this case
    if(!lgroups.length) return [];

    // collapse all groups into one if all groups are blank
    var shouldCollapse = !hasOneNonBlankGroup || !grouped;

    var legendData = [];
    for(i = 0; i < lgroups.length; i++) {
        var t = lgroupToTraces[lgroups[i]];
        if(shouldCollapse) {
            legendData.push(t[0]);
        } else {
            legendData.push(t);
        }
    }
    if(shouldCollapse) legendData = [legendData];

    for(i = 0; i < legendData.length; i++) {
        // find minimum rank within group
        var groupMinRank = Infinity;
        for(j = 0; j < legendData[i].length; j++) {
            var rank = legendData[i][j].trace.legendrank;
            if(groupMinRank > rank) groupMinRank = rank;
        }

        // record on first group element
        legendData[i][0]._groupMinRank = groupMinRank;
        legendData[i][0]._preGroupSort = i;
    }

    var orderFn1 = function(a, b) {
        return (
            (a[0]._groupMinRank - b[0]._groupMinRank) ||
            (a[0]._preGroupSort - b[0]._preGroupSort) // fallback for old Chrome < 70 https://bugs.chromium.org/p/v8/issues/detail?id=90
        );
    };

    var orderFn2 = function(a, b) {
        return (
            (a.trace.legendrank - b.trace.legendrank) ||
            (a._preSort - b._preSort) // fallback for old Chrome < 70 https://bugs.chromium.org/p/v8/issues/detail?id=90
        );
    };

    // sort considering minimum group legendrank
    legendData.forEach(function(a, k) { a[0]._preGroupSort = k; });
    legendData.sort(orderFn1);
    for(i = 0; i < legendData.length; i++) {
        // sort considering trace.legendrank and legend.traceorder
        legendData[i].forEach(function(a, k) { a._preSort = k; });
        legendData[i].sort(orderFn2);

        var firstItemTrace = legendData[i][0].trace;

        var groupTitle = null;
        // get group title text
        for(j = 0; j < legendData[i].length; j++) {
            var gt = legendData[i][j].trace.legendgrouptitle;
            if(gt && gt.text) {
                groupTitle = gt;
                if(inHover) gt.font = opts._groupTitleFont;
                break;
            }
        }

        // reverse order
        if(reversed) legendData[i].reverse();

        if(groupTitle) {
            var hasPieLike = false;
            for(j = 0; j < legendData[i].length; j++) {
                if(Registry.traceIs(legendData[i][j].trace, 'pie-like')) {
                    hasPieLike = true;
                    break;
                }
            }

            // set group title text
            legendData[i].unshift({
                i: -1,
                groupTitle: groupTitle,
                noClick: hasPieLike,
                trace: {
                    showlegend: firstItemTrace.showlegend,
                    legendgroup: firstItemTrace.legendgroup,
                    visible: opts.groupclick === 'toggleitem' ? true : firstItemTrace.visible
                }
            });
        }

        // rearrange lgroupToTraces into a d3-friendly array of arrays
        for(j = 0; j < legendData[i].length; j++) {
            legendData[i][j] = [
                legendData[i][j]
            ];
        }
    }

    // number of legend groups - needed in legend/draw.js
    opts._lgroupsLength = legendData.length;
    // maximum name/label length - needed in legend/draw.js
    opts._maxNameLength = maxNameLength;

    return legendData;
};


text:
package net.vz.mongodb.jackson;

import net.vz.mongodb.jackson.mock.MockObject;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;

public class TestMapReduce extends MongoDBTestBase {
    private JacksonDBCollection<MockObject, String> coll;

    @Before
    public void setup() throws Exception {
        coll = getCollection(MockObject.class, String.class);
    }

    @Test
    public void testInlineMapReduce() throws Exception {
        simpleMapReduce(MapReduce.OutputType.INLINE, null);
    }

    @Test
    public void testReplaceMapReduce() throws Exception {
        JacksonDBCollection<Simple, String> resultColl = getCollection(Simple.class, String.class);
        simpleMapReduce(MapReduce.OutputType.REPLACE, resultColl.getName());
    }

    private void simpleMapReduce(MapReduce.OutputType outputType, String collection) {
        coll.insert(new MockObject("foo", 10));
        coll.insert(new MockObject("foo", 15));
        coll.insert(new MockObject("bar", 5));

        MapReduceOutput<Simple, String> output = coll.mapReduce(
                MapReduce.build("function() {emit(this.string, this.integer);}",
                        "function(k, vals) {var sum=0;for(var i in vals) sum += vals[i];return sum;}",
                        outputType, collection, Simple.class, String.class));

        Simple foo = null;
        Simple bar = null;

        for (Simple result : output.results()) {
            if (result._id.equals("foo")) {
                foo = result;
            } else if (result._id.equals("bar")) {
                bar = result;
            } else {
                fail("Unknown result: " + result._id);
            }
        }

        assertNotNull(foo);
        assertEquals(25, foo.value);

        assertNotNull(bar);
        assertEquals(5, bar.value);
    }

    public static class Simple {
        public String _id;
        public int value;
    }

    @Test
    public void testComplexInlineMapReduce() throws Exception {
        complexMapReduce(MapReduce.OutputType.INLINE, null);
    }

    @Test
    public void testComplexReplaceMapReduce() throws Exception {
        JacksonDBCollection<Complex, String> resultColl = getCollection(Complex.class, String.class);
        complexMapReduce(MapReduce.OutputType.REPLACE, resultColl.getName());
    }

    private void complexMapReduce(MapReduce.OutputType outputType, String collection) {
        coll.insert(new MockObject("foo", 10));
        coll.insert(new MockObject("foo", 15));
        coll.insert(new MockObject("bar", 5));

        MapReduceOutput<Complex, String> output = coll.mapReduce(
                MapReduce.build("function() {emit(this.string, {sum: this.integer, product: this.integer});}",
                        "function(k, vals) {var sum=0,product=1;for(var i in vals){sum+=vals[i].sum;product*=vals[i].product;}return {sum:sum,product:product};}",
                        outputType, collection, Complex.class, String.class));

        Complex foo = null;
        Complex bar = null;

        for (Complex result : output.results()) {
            if (result._id.equals("foo")) {
                foo = result;
            } else if (result._id.equals("bar")) {
                bar = result;
            } else {
                fail("Unknown result: " + result._id);
            }
        }

        assertNotNull(foo);
        assertEquals(25, foo.value.sum);
        assertEquals(150, foo.value.product);

        assertNotNull(bar);
        assertEquals(5, bar.value.sum);
        assertEquals(5, bar.value.product);
    }

    public static class Complex {
        public String _id;
        public Value value;
    }

    public static class Value {
        public int sum;
        public int product;
    }
}


text:
package com.thoughtworks.go.api;

import com.fasterxml.jackson.databind.JsonNode;
import com.thoughtworks.go.config.exceptions.RecordNotFoundException;
import com.thoughtworks.go.i18n.Localizer;
import com.thoughtworks.go.server.service.result.HttpLocalizedOperationResult;
import spark.Request;
import spark.Response;

import java.io.IOException;
import java.util.Objects;

public interface CrudController<Entity> extends ControllerMethods {
    String etagFor(Entity entityFromServer);

    default boolean isGetOrHeadRequestFresh(Request req, Entity entity) {
        return fresh(req, etagFor(entity));
    }

    default boolean isPutRequestFresh(Request req, Entity entity) {
        String etagFromClient = getIfMatch(req);
        if (etagFromClient == null) {
            return false;
        }
        String etagFromServer = etagFor(entity);
        return Objects.equals(etagFromClient, etagFromServer);
    }

    default Entity getEntityFromConfig(String name) {
        Entity entity = doGetEntityFromConfig(name);
        if (entity == null) {
            throw new RecordNotFoundException();
        }
        return entity;
    }

    Localizer getLocalizer();

    Entity doGetEntityFromConfig(String name);

    Entity getEntityFromRequestBody(Request req);

    default String handleCreateOrUpdateResponse(Request req, Response res, Entity entity, HttpLocalizedOperationResult result) throws IOException {
        if (result.isSuccessful()) {
            setEtagHeader(entity, res);
            return jsonize(req, entity);
        } else {
            res.status(result.httpCode());

            JsonNode jsonNode = entity == null ? null : jsonNode(req, entity);
            return writerForTopLevelObject(req, res, writer -> {
                    writer.add("message", result.message(getLocalizer()));

                    if (jsonNode != null) {
                        writer.add("data", jsonNode);
                    }
                }

            );
        }
    }

    String jsonize(Request req, Entity entity);

    JsonNode jsonNode(Request req, Entity entity) throws IOException;

    default void setEtagHeader(Entity entity, Response res) {
        setEtagHeader(res, etagFor(entity));
    }

}


text:
package xyz.brassgoggledcoders.moarcarts.mods.ie;

import blusunrize.immersiveengineering.api.shader.ShaderRegistry;
import blusunrize.immersiveengineering.api.shader.ShaderRegistry.ShaderRegistryEntry;
import net.minecraft.item.EnumRarity;

/**
 * @author SkySom
 */
public class Shaders
{
	public static ShaderRegistryEntry superChief;
	public static ShaderRegistryEntry empireBuilder;

	public static void initShaders()
	{
		int[] yellow = {224, 187, 65, 255};
		int[] red = {192, 0, 15, 255};
		int[] grey = {100, 100, 100, 255};
		int[] orange = {255, 102, 0, 255};
		int[] green = {43, 58, 61, 255};

		superChief = ShaderRegistry.registerShader("Super Chief", "0", EnumRarity.EPIC, grey, red, yellow, grey, null,
				true, true);
		empireBuilder = ShaderRegistry.registerShader("Empire Builder", "0", EnumRarity.COMMON, green, orange, green,
				green, null, true, true);
	}
}


text:
package net.imglib2.ops.operation.metadata.unary;

import net.imagej.ImageMetadata;
import net.imglib2.ops.operation.UnaryOperation;

/**
 * @author Christian Dietz (University of Konstanz)
 *
 * @param <M>
 * @deprecated Use net.imagej.ops instead.
 */
@Deprecated
public class CopyImageMetadata< M extends ImageMetadata > implements UnaryOperation< M, M >
{

	@Override
	public M compute( M input, M output )
	{
		output.setValidBits( input.getValidBits() );
		output.setCompositeChannelCount( input.getCompositeChannelCount() );

		for ( int c = 0; c < output.getCompositeChannelCount(); c++ )
		{
			output.setChannelMinimum( c, input.getChannelMinimum( c ) );
			output.setChannelMaximum( c, input.getChannelMaximum( c ) );
		}

		output.initializeColorTables( input.getColorTableCount() );
		for ( int n = 0; n < input.getColorTableCount(); n++ )
		{
			output.setColorTable( input.getColorTable( n ), n );
		}

		return output;
	}

	@Override
	public UnaryOperation< M, M > copy()
	{
		return new CopyImageMetadata< M >();
	}

}


text:
/**
 *    @file
 *      This file contains the basis class for all the various transport
 *      endpoint classes in the Inet layer, i.e. TCP, UDP, Raw and Tun.
 */

#ifndef ENDPOINTBASIS_H
#define ENDPOINTBASIS_H

#include <InetLayer/InetConfig.h>
#include <InetLayer/InetError.h>
#include <InetLayer/IANAConstants.h>
#include <InetLayer/InetLayerBasis.h>
#include <InetLayer/InetLayerEvents.h>
#include <InetLayer/InetInterface.h>

#include <Weave/Support/NLDLLUtil.h>

//--- Declaration of LWIP protocol control buffer structure names
#if WEAVE_SYSTEM_CONFIG_USE_LWIP
#if INET_CONFIG_ENABLE_RAW_ENDPOINT
struct raw_pcb;
#endif // INET_CONFIG_ENABLE_RAW_ENDPOINT
#if INET_CONFIG_ENABLE_UDP_ENDPOINT
struct udp_pcb;
#endif // INET_CONFIG_ENABLE_UDP_ENDPOINT
#if INET_CONFIG_ENABLE_TCP_ENDPOINT
struct tcp_pcb;
#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT
#if INET_CONFIG_ENABLE_TUN_ENDPOINT
struct netif;
#endif // INET_CONFIG_ENABLE_TUN_ENDPOINT
#endif // WEAVE_SYSTEM_CONFIG_USE_LWIP

namespace nl {
namespace Inet {

/**
 * @class EndPointBasis
 *
 * @brief Basis of internet transport endpoint classes
 */
class NL_DLL_EXPORT EndPointBasis : public InetLayerBasis
{
public:
    /** Common state codes */
    enum {
        kBasisState_Closed = 0      /**< Encapsulated descriptor is not valid. */
    };

#if WEAVE_SYSTEM_CONFIG_USE_SOCKETS
    /** Test whether endpoint is a POSIX socket */
    bool IsSocketsEndPoint(void) const;
#endif

#if WEAVE_SYSTEM_CONFIG_USE_LWIP
    /** Test whether endpoint is a LwIP protocol control buffer */
    bool IsLWIPEndPoint(void) const;
#endif

    /** Test whether endpoint has a valid descriptor. */
    bool IsOpenEndPoint(void) const;

protected:
#if WEAVE_SYSTEM_CONFIG_USE_SOCKETS
    int mSocket;                    /**< Encapsulated socket descriptor. */
    IPAddressType mAddrType;        /**< Protocol family, i.e. IPv4 or IPv6. */
    SocketEvents mPendingIO;        /**< Socket event masks */
#endif // WEAVE_SYSTEM_CONFIG_USE_SOCKETS

#if WEAVE_SYSTEM_CONFIG_USE_LWIP
    /** Encapsulated LwIP protocol control block */
    union
    {
        const void* mVoid;          /**< An untyped protocol control buffer reference */
#if INET_CONFIG_ENABLE_RAW_ENDPOINT
        raw_pcb* mRaw;              /**< Raw network interface protocol control */
#endif // INET_CONFIG_ENABLE_RAW_ENDPOINT
#if INET_CONFIG_ENABLE_UDP_ENDPOINT
        udp_pcb* mUDP;              /**< User datagram protocol (UDP) control */
#endif // INET_CONFIG_ENABLE_UDP_ENDPOINT
#if INET_CONFIG_ENABLE_TCP_ENDPOINT
        tcp_pcb* mTCP;              /**< Transmission control protocol (TCP) control */
#endif // INET_CONFIG_ENABLE_TCP_ENDPOINT
#if INET_CONFIG_ENABLE_TUN_ENDPOINT
        netif* mNetIf;              /**< Tunnel interface control */
#endif // INET_CONFIG_ENABLE_TUN_ENDPOINT
    };

    enum
    {
        kLwIPEndPointType_Unknown = 0,

        kLwIPEndPointType_Raw     = 1,
        kLwIPEndPointType_UDP     = 2,
        kLwIPEndPointType_UCP     = 3,
        kLwIPEndPointType_TCP     = 4
    };

    uint8_t mLwIPEndPointType;

    void DeferredFree(Weave::System::Object::ReleaseDeferralErrorTactic aTactic);
#endif // WEAVE_SYSTEM_CONFIG_USE_LWIP

    void InitEndPointBasis(InetLayer& aInetLayer, void* aAppState = NULL);
};

#if WEAVE_SYSTEM_CONFIG_USE_SOCKETS
inline bool EndPointBasis::IsSocketsEndPoint(void) const
{
    return mSocket >= 0;
}
#endif // WEAVE_SYSTEM_CONFIG_USE_SOCKETS

#if WEAVE_SYSTEM_CONFIG_USE_LWIP
inline bool EndPointBasis::IsLWIPEndPoint(void) const
{
    return mVoid != NULL;
}
#endif // WEAVE_SYSTEM_CONFIG_USE_LWIP

inline bool EndPointBasis::IsOpenEndPoint(void) const
{
    bool lResult = false;

#if WEAVE_SYSTEM_CONFIG_USE_LWIP
    lResult = (lResult || IsLWIPEndPoint());
#endif // WEAVE_SYSTEM_CONFIG_USE_LWIP

#if WEAVE_SYSTEM_CONFIG_USE_SOCKETS
    lResult = (lResult || IsSocketsEndPoint());
#endif // WEAVE_SYSTEM_CONFIG_USE_SOCKETS

    return lResult;
}

#if WEAVE_SYSTEM_CONFIG_USE_LWIP
inline void EndPointBasis::DeferredFree(Weave::System::Object::ReleaseDeferralErrorTactic aTactic)
{
    if (!WEAVE_SYSTEM_CONFIG_USE_SOCKETS || IsLWIPEndPoint())
    {
        DeferredRelease(aTactic);
    }
    else
    {
        Release();
    }
}
#endif // WEAVE_SYSTEM_CONFIG_USE_LWIP

} // namespace Inet
} // namespace nl

#endif // !defined(ENDPOINTBASIS_H)


text:
<?php

/**
 * @file
 * Contains \Drupal\pathauto\Tests\PathautoTaxonomyWebTest.
 */

namespace Drupal\pathauto\Tests;
use Drupal\simpletest\WebTestBase;

/**
 * Tests pathauto taxonomy UI integration.
 *
 * @group pathauto
 */
class PathautoTaxonomyWebTest extends WebTestBase {

  use PathautoTestHelperTrait;

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = array('taxonomy', 'pathauto', 'views');

  /**
   * Admin user.
   *
   * @var \Drupal\user\UserInterface
   */
  protected $adminUser;

  /**
   * {inheritdoc}
   */
  function setUp() {
    parent::setUp();

    // Allow other modules to add additional permissions for the admin user.
    $permissions = array(
      'administer pathauto',
      'administer url aliases',
      'create url aliases',
      'administer taxonomy',
    );
    $this->adminUser = $this->drupalCreateUser($permissions);
    $this->drupalLogin($this->adminUser);

    $this->createPattern('taxonomy_term', '/[term:vocabulary]/[term:name]');
  }

  /**
   * Basic functional testing of Pathauto with taxonomy terms.
   */
  function testTermEditing() {
    $this->drupalGet('admin/structure');
    $this->drupalGet('admin/structure/taxonomy');

    // Add vocabulary "tags".
    $vocabulary = $this->addVocabulary(array('name' => 'tags', 'vid' => 'tags'));

    // Create term for testing.
    $name = 'Testing: term name [';
    $automatic_alias = '/tags/testing-term-name';
    $this->drupalPostForm('admin/structure/taxonomy/manage/tags/add', array('name[0][value]' => $name), 'Save');
    $name = trim($name);
    $this->assertText("Created new term $name.");
    $term = $this->drupalGetTermByName($name);

    // Look for alias generated in the form.
    $this->drupalGet("taxonomy/term/{$term->id()}/edit");
    $this->assertFieldChecked('edit-path-0-pathauto');
    $this->assertFieldByName('path[0][alias]', $automatic_alias, 'Generated alias visible in the path alias field.');

    // Check whether the alias actually works.
    $this->drupalGet($automatic_alias);
    $this->assertText($name, 'Term accessible through automatic alias.');

    // Manually set the term's alias.
    $manual_alias = '/tags/' . $term->id();
    $edit = array(
      'path[0][pathauto]' => FALSE,
      'path[0][alias]' => $manual_alias,
    );
    $this->drupalPostForm("taxonomy/term/{$term->id()}/edit", $edit, t('Save'));
    $this->assertText("Updated term $name.");

    // Check that the automatic alias checkbox is now unchecked by default.
    $this->drupalGet("taxonomy/term/{$term->id()}/edit");
    $this->assertNoFieldChecked('edit-path-0-pathauto');
    $this->assertFieldByName('path[0][alias]', $manual_alias);

    // Submit the term form with the default values.
    $this->drupalPostForm(NULL, array('path[0][pathauto]' => FALSE), t('Save'));
    $this->assertText("Updated term $name.");

    // Test that the old (automatic) alias has been deleted and only accessible
    // through the new (manual) alias.
    $this->drupalGet($automatic_alias);
    $this->assertResponse(404, 'Term not accessible through automatic alias.');
    $this->drupalGet($manual_alias);
    $this->assertText($name, 'Term accessible through manual alias.');
  }

}


text:
package org.apache.calcite.materialize;

import org.apache.calcite.util.Litmus;

import com.google.common.collect.ImmutableList;

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

/** Root node in a {@link Lattice}. It has no parent. */
public class LatticeRootNode extends LatticeNode {
  /** Descendants, in prefix order. This root node is at position 0. */
  public final ImmutableList<LatticeNode> descendants;
  final ImmutableList<Path> paths;

  LatticeRootNode(LatticeSpace space, MutableNode mutableNode) {
    super(space, null, mutableNode);

    final ImmutableList.Builder<LatticeNode> b = ImmutableList.builder();
    flattenTo(b);
    this.descendants = b.build();
    this.paths = createPaths(space);
  }

  private ImmutableList<Path> createPaths(LatticeSpace space) {
    final List<Step> steps = new ArrayList<>();
    final List<Path> paths = new ArrayList<>();
    createPathsRecurse(space, steps, paths);
    assert steps.isEmpty();
    return ImmutableList.copyOf(paths);
  }

  void use(List<LatticeNode> usedNodes) {
    if (!usedNodes.contains(this)) {
      usedNodes.add(this);
    }
  }

  /** Validates that nodes form a tree; each node except the first references
   * a predecessor. */
  boolean isValid(Litmus litmus) {
    for (int i = 0; i < descendants.size(); i++) {
      LatticeNode node = descendants.get(i);
      if (i == 0) {
        if (node != this) {
          return litmus.fail("node 0 should be root");
        }
      } else {
        if (!(node instanceof LatticeChildNode)) {
          return litmus.fail("node after 0 should be child");
        }
        final LatticeChildNode child = (LatticeChildNode) node;
        if (!descendants.subList(0, i).contains(child.parent)) {
          return litmus.fail("parent not in preceding list");
        }
      }
    }
    return litmus.succeed();
  }

  /** Whether this node's graph is a super-set of (or equal to) another node's
   * graph. */
  public boolean contains(LatticeRootNode node) {
    return paths.containsAll(node.paths);
  }

}

// End LatticeRootNode.java


text:
module DataMapper
  module Assertions
    def assert_kind_of(name, value, *klasses)
      klasses.each { |k| return if value.kind_of?(k) }
      raise ArgumentError, "+#{name}+ should be #{klasses.map { |k| k.name } * ' or '}, but was #{value.class.name}", caller(2)
    end
  end
end


text:
// Generated by Haxe 3.4.0
#ifndef INCLUDED_kha_graphics2_truetype_Stbtt_temp_rect
#define INCLUDED_kha_graphics2_truetype_Stbtt_temp_rect

#ifndef HXCPP_H
#include <hxcpp.h>
#endif

HX_DECLARE_STACK_FRAME(_hx_pos_dca304a9eac19eaf_22_new)
HX_DECLARE_CLASS3(kha,graphics2,truetype,Stbtt_temp_rect)

namespace kha{
namespace graphics2{
namespace truetype{

class HXCPP_CLASS_ATTRIBUTES Stbtt_temp_rect_obj : public hx::Object
{
	public:
		typedef hx::Object super;
		typedef Stbtt_temp_rect_obj OBJ_;
		Stbtt_temp_rect_obj();

	public:
		enum { _hx_ClassId = 0x2882c282 };

		void __construct();
		inline void *operator new(size_t inSize, bool inContainer=false,const char *inName="kha.graphics2.truetype.Stbtt_temp_rect")
			{ return hx::Object::operator new(inSize,inContainer,inName); }
		inline void *operator new(size_t inSize, int extra)
			{ return hx::Object::operator new(inSize+extra,false,"kha.graphics2.truetype.Stbtt_temp_rect"); }

		hx::ObjectPtr< Stbtt_temp_rect_obj > __new() {
			hx::ObjectPtr< Stbtt_temp_rect_obj > __this = new Stbtt_temp_rect_obj();
			__this->__construct();
			return __this;
		}

		static hx::ObjectPtr< Stbtt_temp_rect_obj > __alloc(hx::Ctx *_hx_ctx) {
			Stbtt_temp_rect_obj *__this = (Stbtt_temp_rect_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(Stbtt_temp_rect_obj), false, "kha.graphics2.truetype.Stbtt_temp_rect"));
			*(void **)__this = Stbtt_temp_rect_obj::_hx_vtable;
{
            	HX_STACKFRAME(&_hx_pos_dca304a9eac19eaf_22_new)
            	HX_STACK_THIS(__this)
            	}

			return __this;
		}

		static void * _hx_vtable;
		static Dynamic __CreateEmpty();
		static Dynamic __Create(hx::DynamicArray inArgs);
		//~Stbtt_temp_rect_obj();

		HX_DO_RTTI_ALL;
		hx::Val __Field(const ::String &inString, hx::PropertyAccess inCallProp);
		hx::Val __SetField(const ::String &inString,const hx::Val &inValue, hx::PropertyAccess inCallProp);
		void __GetFields(Array< ::String> &outFields);
		static void __register();
		bool _hx_isInstanceOf(int inClassId);
		::String __ToString() const { return HX_HCSTRING("Stbtt_temp_rect","\xb1","\x5c","\x96","\x64"); }

		int x0;
		int y0;
		int x1;
		int y1;
};

} // end namespace kha
} // end namespace graphics2
} // end namespace truetype

#endif /* INCLUDED_kha_graphics2_truetype_Stbtt_temp_rect */


text:
package test.listeners;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class ConfigurationListenerSkipSampleTest {

  @BeforeMethod
  public void bmShouldFail() {
    throw new RuntimeException();
  }

  @BeforeMethod(dependsOnMethods = "bmShouldFail")
  public void bm() {
  }

  @Test
  public void f() {
  }
}


text:
#ifndef COMMON_ERRORS_H
#define COMMON_ERRORS_H

/* A problem was detected, but the requested operation can still
   proceed.  A warning message is constructed using a printf- or
   vprintf-style argument list.  The function "vwarning" must be
   provided by the client.  */

extern void warning (const char *fmt, ...)
     ATTRIBUTE_PRINTF (1, 2);

extern void vwarning (const char *fmt, va_list args)
     ATTRIBUTE_PRINTF (1, 0);

/* A non-predictable, non-fatal error was detected.  The requested
   operation cannot proceed.  An error message is constructed using
   a printf- or vprintf-style argument list.  These functions do not
   return.  The function "verror" must be provided by the client.  */

extern void error (const char *fmt, ...)
     ATTRIBUTE_NORETURN ATTRIBUTE_PRINTF (1, 2);

extern void verror (const char *fmt, va_list args)
     ATTRIBUTE_NORETURN ATTRIBUTE_PRINTF (1, 0);

/* An internal error was detected.  Internal errors indicate
   programming errors such as assertion failures, as opposed to
   more general errors beyond the application's control.  These
   functions do not return.  An error message is constructed using
   a printf- or vprintf-style argument list.  FILE and LINE
   indicate the file and line number where the programming error
   was detected.  The function "internal_verror" must be provided
   by the client.  */

extern void internal_error (const char *file, int line,
			    const char *fmt, ...)
     ATTRIBUTE_NORETURN ATTRIBUTE_PRINTF (3, 4);

extern void internal_verror (const char *file, int line,
			     const char *fmt, va_list args)
     ATTRIBUTE_NORETURN ATTRIBUTE_PRINTF (3, 0);

/* An internal problem was detected, but the requested operation can
   still proceed.  Internal warnings indicate programming errors as
   opposed to more general issues beyond the application's control.
   A warning message is constructed using a printf- or vprintf-style
   argument list.  The function "internal_vwarning" must be provided
   by the client.  */

extern void internal_warning (const char *file, int line,
			      const char *fmt, ...)
     ATTRIBUTE_PRINTF (3, 4);

extern void internal_vwarning (const char *file, int line,
			       const char *fmt, va_list args)
     ATTRIBUTE_PRINTF (3, 0);

/* Like "error", but the error message is constructed by combining
   STRING with the system error message for errno.  This function does
   not return.  This function must be provided by the client.  */

extern void perror_with_name (const char *string) ATTRIBUTE_NORETURN;

/* Call this function to handle memory allocation failures.  This
   function does not return.  This function must be provided by the
   client.  */

extern void malloc_failure (long size) ATTRIBUTE_NORETURN;

#endif /* COMMON_ERRORS_H */


text:
package ru.teymurov.githubsearch.mvp.views;

import com.arellomobile.mvp.MvpView;
import com.arellomobile.mvp.viewstate.strategy.AddToEndSingleStrategy;
import com.arellomobile.mvp.viewstate.strategy.AddToEndStrategy;
import com.arellomobile.mvp.viewstate.strategy.StateStrategyType;

import java.util.List;

import ru.teymurov.githubsearch.retrofit.gson.Repository;

@StateStrategyType(AddToEndSingleStrategy.class)
public interface SearchView extends MvpView {
    void hideLoading();
    void showLoading();
    void failedSearch(String message);

    @StateStrategyType(AddToEndStrategy.class)
    void addRepositories(List<Repository> repositories, boolean maybeMore);

    @StateStrategyType(AddToEndStrategy.class)
    void setRepositories(List<Repository> repositories, boolean maybeMore);
}


text:
dress
=====

dress is a database design documentor. This console application generates database design documentation in html format from your RDB like MySQL. There is no need to review updates and update your documentation one by one. You add comments on tables and rows, and then type a command in your terminal. That's all.

## Supported

* MySQL
* PostgreSQL
* SQLite3

## Usage

```
$ python dress config --datasource mysql
$ python dress export
```

## Note

Under development.

## License

Copyright (c) 2014-2015 Satoshi Okami. See the LICENSE file for license rights and limitations (MIT).


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Code Coverage for D:\jobeet\src/Acme/DemoBundle/Controller/DemoController.php</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="../../../css/bootstrap.min.css" rel="stylesheet">
  <link href="../../../css/style.css" rel="stylesheet">

D:\jobeet\src

Acme

DemoBundle

Controller

DemoController.php

Code Coverage

Classes and Traits

Functions and Methods

Lines

      Total

           0.00% covered (danger)

0.00%

0 / 1

           0.00% covered (danger)

0.00%

0 / 3

      CRAP

           0.00% covered (danger)

0.00%

0 / 16

      DemoController

           0.00% covered (danger)

0.00%

0 / 1

           0.00% covered (danger)

0.00%

0 / 3

      20

           0.00% covered (danger)

0.00%

0 / 16

       indexAction()

           0.00% covered (danger)

0.00%

0 / 1

      2

           0.00% covered (danger)

0.00%

0 / 3

       helloAction($name)

           0.00% covered (danger)

0.00%

0 / 1

      2

           0.00% covered (danger)

0.00%

0 / 3

       contactAction(Request $request)

           0.00% covered (danger)

0.00%

0 / 1

      6

           0.00% covered (danger)

0.00%

0 / 10

1
	<?php

2

3
	namespace Acme\DemoBundle\Controller;

4

5
	use Symfony\Bundle\FrameworkBundle\Controller\Controller;

6
	use Symfony\Component\HttpFoundation\RedirectResponse;

7
	use Symfony\Component\HttpFoundation\Request;

8
	use Acme\DemoBundle\Form\ContactType;

9

10
	// these import the "@Route" and "@Template" annotations

11
	use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

12
	use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

13

14
	class DemoController extends Controller

15
	{

16
	    /**

17
	     * @Route("/", name="_demo")

18
	     * @Template()

19
	     */

20
	    public function indexAction()

21
	    {

22
	        return array();

23
	    }

24

25
	    /**

26
	     * @Route("/hello/{name}", name="_demo_hello")

27
	     * @Template()

28
	     */

29
	    public function helloAction($name)

30
	    {

31
	        return array('name' => $name);

32
	    }

33

34
	    /**

35
	     * @Route("/contact", name="_demo_contact")

36
	     * @Template()

37
	     */

38
	    public function contactAction(Request $request)

39
	    {

40
	        $form = $this->createForm(new ContactType());

41
	        $form->handleRequest($request);

42

43
	        if ($form->isValid()) {

44
	            $mailer = $this->get('mailer');

45

46
	            // .. setup a message and send it

47
	            // http://symfony.com/doc/current/cookbook/email.html

48

49
	            $request->getSession()->getFlashBag()->set('notice', 'Message sent!');

50

51
	            return new RedirectResponse($this->generateUrl('_demo'));

52
	        }

53

54
	        return array('form' => $form->createView());

55
	    }

56
	}

Legend

     Executed
     Not Executed
     Dead Code

     Generated by PHP_CodeCoverage 2.0.15 using PHP 5.5.12 and PHPUnit 4.5.0 at Tue Mar 24 21:16:15 CET 2015.


text:
/* ========================================================
 * ResultThreadJob.java
 *
 * Author:      kmchugh
 * Created:     Feb 3, 2011, 7:23:34 PM
 *
 * Description
 * --------------------------------------------------------
 * General Class Description.
 *
 * Change Log
 * --------------------------------------------------------
 * Init.Date        Ref.            Description
 * --------------------------------------------------------
 *
 * ===================================================== */

package Goliath.Threading;

import Goliath.Arguments.Arguments;

/**
 * Class Description.
 * For example:
 *

 *      Example usage
 *

 *
 * @see         Related Class
 * @version     1.0 Feb 3, 2011
 * @author      kmchugh
**/
public abstract class ResultThreadJob extends ThreadJob
{
    private T m_oResult;

    public ResultThreadJob(A toCommandArgs)
    {
        super(toCommandArgs);
    }

    public void setResult(T toResult)
    {
        m_oResult = toResult;
    }

    public T getResult()
    {
        return m_oResult;
    }
}


text:
==

Live page at: [academy.vtex.com](https://academy.vtex.com)

## Contributing

First, install [node.js](http://nodejs.org/).

Then, install the grunt-cli package via npm:

    npm i -g grunt-cli

Finally, clone this repo, install deps and run grunt:

    git clone git@github.com:vtex/academy.git
    cd academy
    npm i
    grunt

## Deploying to GH Pages

    grunt dist

------


text:
@interface JunitFrameworkAssertionFailedError : JavaLangAssertionError

#pragma mark Public

- (instancetype)init;

- (instancetype)initWithNSString:(NSString *)message;

@end

J2OBJC_EMPTY_STATIC_INIT(JunitFrameworkAssertionFailedError)

FOUNDATION_EXPORT void JunitFrameworkAssertionFailedError_init(JunitFrameworkAssertionFailedError *self);

FOUNDATION_EXPORT JunitFrameworkAssertionFailedError *new_JunitFrameworkAssertionFailedError_init() NS_RETURNS_RETAINED;

FOUNDATION_EXPORT void JunitFrameworkAssertionFailedError_initWithNSString_(JunitFrameworkAssertionFailedError *self, NSString *message);

FOUNDATION_EXPORT JunitFrameworkAssertionFailedError *new_JunitFrameworkAssertionFailedError_initWithNSString_(NSString *message) NS_RETURNS_RETAINED;

J2OBJC_TYPE_LITERAL_HEADER(JunitFrameworkAssertionFailedError)

#endif // _JunitFrameworkAssertionFailedError_H_


text:
"""Data generators for Wiki LM and MNLI combined datasets."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensor2tensor.data_generators import cnn_dailymail
from tensor2tensor.data_generators import multi_problem
from tensor2tensor.data_generators import multinli
from tensor2tensor.data_generators import text_problems
from tensor2tensor.data_generators import translate_ende
from tensor2tensor.data_generators import translate_enfr
from tensor2tensor.data_generators import translate_enro
from tensor2tensor.data_generators import wiki_lm
from tensor2tensor.utils import registry

@registry.register_problem
class LanguagemodelEnWikiLMMultiNLISubwords(multi_problem.MultiProblem):
  """Wiki LM and MNLI mixed problem class."""

  def __init__(self, was_reversed=False, was_copy=False):
    super(LanguagemodelEnWikiLMMultiNLISubwords, self).__init__(
        was_reversed, was_copy)
    self.task_list.append(wiki_lm.LanguagemodelEnWiki32k())
    self.task_list.append(multinli.MultiNLIWikiLMSharedVocab())

  @property
  def vocab_type(self):
    return text_problems.VocabType.SUBWORD

@registry.register_problem
class LanguagemodelEnWikiLMMultiNLISubwords64k(multi_problem.MultiProblem):
  """Wiki LM and MNLI mixed problem class."""

  def __init__(self, was_reversed=False, was_copy=False):
    super(LanguagemodelEnWikiLMMultiNLISubwords64k, self).__init__(
        was_reversed, was_copy)
    self.task_list.append(wiki_lm.LanguagemodelEnWiki64k())
    self.task_list.append(multinli.MultiNLIWikiLMSharedVocab64k())

  @property
  def vocab_type(self):
    return text_problems.VocabType.SUBWORD

@registry.register_problem
class LanguagemodelEnWikiLMShortMultiNLISubwords64k(multi_problem.MultiProblem):
  """Wiki LM and MNLI mixed problem class."""

  def __init__(self, was_reversed=False, was_copy=False):
    super(LanguagemodelEnWikiLMShortMultiNLISubwords64k, self).__init__(
        was_reversed, was_copy)
    self.task_list.append(wiki_lm.LanguagemodelEnWiki64kShorter())
    self.task_list.append(multinli.MultiNLIWikiLMSharedVocab64k())

  @property
  def vocab_type(self):
    return text_problems.VocabType.SUBWORD

@registry.register_problem
class LanguagemodelEnWikiLMSummarizeCnndmSubwords(multi_problem.MultiProblem):
  """Wiki LM and CNN/DM summarization mixed problem class."""

  def __init__(self, was_reversed=False, was_copy=False):
    super(LanguagemodelEnWikiLMSummarizeCnndmSubwords, self).__init__(
        was_reversed, was_copy)
    self.task_list.append(wiki_lm.LanguagemodelEnWiki32k())
    self.task_list.append(
        cnn_dailymail.SummarizeCnnDailymailWikiLMSharedVocab())

  @property
  def vocab_type(self):
    return text_problems.VocabType.SUBWORD

@registry.register_problem
class LanguagemodelEnWikiLMSummarizeCnndmSubwords64k(
    multi_problem.MultiProblem):
  """Wiki LM and CNN/DM summarization mixed problem class."""

  def __init__(self, was_reversed=False, was_copy=False):
    super(LanguagemodelEnWikiLMSummarizeCnndmSubwords64k, self).__init__(
        was_reversed, was_copy)
    self.task_list.append(wiki_lm.LanguagemodelEnWiki64k())
    self.task_list.append(
        cnn_dailymail.SummarizeCnnDailymailWikiLMSharedVocab64k())

  @property
  def vocab_type(self):
    return text_problems.VocabType.SUBWORD

@registry.register_problem
class LanguagemodelMultiWikiTranslateFr(multi_problem.MultiProblem):
  """Wiki multi-lingual LM and En-Fr translation."""

  def __init__(self, was_reversed=False, was_copy=False):
    super(LanguagemodelMultiWikiTranslateFr, self).__init__(
        was_reversed, was_copy)
    self.task_list.append(wiki_lm.LanguagemodelDeEnFrRoWiki64k())
    self.task_list.append(translate_enfr.TranslateEnfrWmtMulti64k())

  @property
  def vocab_type(self):
    return text_problems.VocabType.SUBWORD

@registry.register_problem
class LanguagemodelMultiWikiTranslate(multi_problem.MultiProblem):
  """Wiki multi-lingual LM and multiple translations."""

  def __init__(self, was_reversed=False, was_copy=False):
    super(LanguagemodelMultiWikiTranslate, self).__init__(
        was_reversed, was_copy)
    self.task_list.append(wiki_lm.LanguagemodelDeEnFrRoWiki64k())
    self.task_list.append(translate_ende.TranslateEndeWmtMulti64k())
    self.task_list.append(translate_enfr.TranslateEnfrWmtMulti64k())
    self.task_list.append(translate_enro.TranslateEnroWmtMulti64k())
    self.task_list.append(translate_ende.TranslateEndeWmtMulti64k(
        was_reversed=True))
    self.task_list.append(translate_enfr.TranslateEnfrWmtMulti64k(
        was_reversed=True))
    self.task_list.append(translate_enro.TranslateEnroWmtMulti64k(
        was_reversed=True))

  @property
  def vocab_type(self):
    return text_problems.VocabType.SUBWORD


text:
<?php

function app($key)
{
	return Gravitano\Support\Aliases\App::make($key);
}

function router()
{
	return app(__FUNCTION__);
}

function request()
{
    return app(__FUNCTION__);
}

function view()
{
    return app(__FUNCTION__);
}

function twig()
{
    return app(__FUNCTION__);
}

function dd($var)
{
    die(var_dump($var));
}


text:
"""Engine extension tools and classes."""
import warnings
from enum import Enum
from abc import ABCMeta, abstractmethod

from .exceptions import EngineManagerError

__all__ = ['EngineFeatureMetadata',
           'EngineMetadata',
           'EngineManager']

class EngineInterface(Enum):
    """Represents an available interface to an engine.

    An interface is either internal or fileio. Internal interfaces use
    a python package or a shared library to talk to the underlying engine.
    FileIO, on the other hand, uses input/output files to interact with
    an engine executable.
    """
    Internal = 'internal'
    FileIO = 'fileio'

class EngineFeatureMetadata(object):
    """Represents a set of engine features.

    A feature provides a set of methods to solve a physics equation.

    Parameters
    ----------
    physics_equation: PhysicsEquation
      represents a physics equation
    methods: list
      methods to solve the equation as a list of ComputationalMethod objects
    """
    def __init__(self, physics_equation, methods):
        if not physics_equation:
            raise EngineManagerError('Physics equation must have a value.')
        if not methods or len(methods) == 0:
            raise \
                EngineManagerError('At least one method must be provided.')
        self.physics_equation = physics_equation
        self.methods = methods

class EngineMetadata(object):
    """Data structure to represent engine metadata.

    This class represents one supported engine along with its features.

    Parameters
    ----------
    name: str
      fixed name of a support engine to be used in user's data, i.e. key
    features: list
      features of this engine as a list of EngineFeatureMetadata objects
    interfaces: list
      supported engine interfaces as a list of engine.EngineInterface enums

    """
    def __init__(self, name, features, interfaces):
        self.name = name
        self.features = features
        self.interfaces = interfaces

class ABCEngineExtension(object):
    """Base class for all engine extensions."""
    __metaclass__ = ABCMeta

    @abstractmethod
    def get_supported_engines(self):
        """Get metadata about supported engines.

        Returns
        -------
        list: a list of EngineMetadata objects
        """

    @abstractmethod
    def create_wrapper(self, cuds, engine_name, engine_interface):
        """Creates a wrapper to the requested engine.

        Parameters
        ----------
        cuds: CUDS
          CUDS computational model data
        engine_name: str
          name of the engine, must be supported by this extension
        engine_interface: engine.EngineInterface
          the interface to interact with engine

        Returns
        -------
        ABCEngineExtension: A wrapper configured with cuds and ready to run
        """

    def create_engine_metadata(self, name, features, interfaces):
        """Factory method to create engine metadata.

        Parameters
        ----------
        name: str
          fixed name of a support engine to be used in user's data, i.e. key
        features: list
          features of this engine as a list of EngineFeatureMetadata objects
        interfaces: list
          supported engine interfaces as a list of engine.EngineInterface enums

        Returns
        -------
        EngineMetadata: a loaded engine metadata object
        """
        return EngineMetadata(name, features, interfaces)

    def create_engine_metadata_feature(self, physics_equation, methods):
        """Factory method to create engine metadata feature.

        Parameters
        ----------
        physics_equation: PhysicsEquation
          represents a physics equation
        methods: list
          ComputationalMethod objects to solve the equation

        Return
        ------
        EngineFeatureMetadata: a loaded engine metadata feature object
        """
        return EngineFeatureMetadata(physics_equation, methods)

class EngineManager(object):
    """Controller class to keep track of engine extensions."""

    def __init__(self):
        self._engine_extensions = {}

        # List of registered class ids
        self._registry = []

    def register_extension(self, cls):
        """Register an engine extension class.

        Parameters
        ----------
        cls: ABCEngineExtension
          a subclass of base extension metadata type
        """
        if cls.__name__ in self._registry:
            warnings.warn(
                'Ignoring already registered class %s' % cls.__name__)
            return

        if not issubclass(cls, ABCEngineExtension):
            raise \
                EngineManagerError("Not valid engine metadata class %s" % cls)

        # Instantiate the extension
        extension = cls()

        if not isinstance(extension, ABCEngineExtension):
            raise ValueError('Expected ABCEngineExtension, got %s' %
                             extension)

        for engine in extension.get_supported_engines():
            if engine.name in self._engine_extensions:
                raise EngineManagerError(
                    'There is already an extension registered '
                    'for %s engine.' % engine.name)

            # This extension knows how to create wrappers for the given engine.
            # It is our interaction point with its engines.
            self._engine_extensions[engine.name] = extension
            self._registry.append(cls.__name__)

    def create_wrapper(self, cuds, engine_name, engine_interface=None):
        """Create a wrapper to the given engine.

        Parameters
        ----------
        cuds: CUDS
            a cuds object which contains model information
        engine_name: str
            name of the underlying engine to launch the simulation with
        engine_interface: engine.EngineInterface
            the interface to the engine, internal or fileio
        """
        if engine_name in self._engine_extensions:
            extension = self._engine_extensions[engine_name]
            return extension.create_wrapper(cuds,
                                            engine_name,
                                            engine_interface)
        else:
            raise EngineManagerError(
                'Invalid engine name: %s. Available engines are %s'
                % (engine_name, self.get_supported_engine_names()))

    def get_supported_engines(self):
        """Get metadata about supported engines.

        Returns
        -------
        metadata: list
            a list of EngineMetadata objects
        """
        return list(self._engine_extensions.values())

    def get_supported_engine_names(self):
        """Show a list of supported engines.

        Returns
        -------
        names: list
            a list of engine names
        """
        return self._engine_extensions.keys()


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

enum
{
	SYM_BUTTON1 = GWM_SYM_USER,
	SYM_BUTTON2,
	SYM_BUTTON3,

	SYM_CHECKBOX,
	SYM_CB_MASK,

	SYM_BUTTON_FRAME1,
	SYM_BUTTON_FRAME2,

	SYM_FILE_DEMO,
};

GWMWindow *txtfield;
GWMWindow *cbMask;

int myCommandHandler(GWMCommandEvent *ev)
{
	switch (ev->symbol)
	{
	case SYM_BUTTON2:
		gwmMessageBox(NULL, "Example", "You clicked button 2!", GWM_MBUT_OK);
		return GWM_EVSTATUS_CONT;
	case SYM_CHECKBOX:
		if (gwmMessageBox(NULL, "Example", "Are you sure you want to flip this checkbox?", GWM_MBUT_YESNO | GWM_MBICON_QUEST) == GWM_SYM_YES)
		{
			return GWM_EVSTATUS_CONT;
		};
		return GWM_EVSTATUS_OK;
	case SYM_BUTTON_FRAME2:
		gwmMessageBox(NULL, "Example", gwmReadTextField(txtfield), GWM_MBUT_OK | GWM_MBICON_WARN);
		return GWM_EVSTATUS_CONT;
	case SYM_FILE_DEMO:
		gwmMessageBox(NULL, "Example", "You clicked the demo entry in the menu", GWM_MBUT_OK | GWM_MBICON_INFO);
		return GWM_EVSTATUS_CONT;
	case GWM_SYM_EXIT:
		return GWM_EVSTATUS_BREAK;
	default:
		return GWM_EVSTATUS_CONT;
	};
};

int myToggledHandler(GWMCommandEvent *ev)
{
	switch (ev->symbol)
	{
	case SYM_CB_MASK:
		if (gwmGetCheckboxState(cbMask))
		{
			gwmSetTextFieldFlags(txtfield, GWM_TXT_MASKED);
		}
		else
		{
			gwmSetTextFieldFlags(txtfield, 0);
		};
		return GWM_EVSTATUS_CONT;
	default:
		return GWM_EVSTATUS_CONT;
	};
};

int myHandler(GWMEvent *ev, GWMWindow *win, void *context)
{
	switch (ev->type)
	{
	case GWM_EVENT_COMMAND:
		return myCommandHandler((GWMCommandEvent*) ev);
	case GWM_EVENT_TOGGLED:
		return myToggledHandler((GWMCommandEvent*) ev);
	default:
		return GWM_EVSTATUS_CONT;
	};
};

int main()
{
	if (gwmInit() != 0)
	{
		fprintf(stderr, "Failed to initialize GWM!\n");
		return 1;
	};

	GWMWindow *topWindow = gwmCreateWindow(
		NULL,						// window parent (none)
		"GWM Demo",					// window caption
		GWM_POS_UNSPEC, GWM_POS_UNSPEC,			// window coordinates unspecified
		0, 0,						// window size (will be set later by gwmFit() )
		GWM_WINDOW_HIDDEN | GWM_WINDOW_NOTASKBAR	// hidden, no taskbar icon
	);
	assert(topWindow != NULL);

	gwmPushEventHandler(topWindow, myHandler, NULL);

	GWMLayout *boxLayout = gwmCreateBoxLayout(GWM_BOX_VERTICAL);

	GWMWindowTemplate wt;
	wt.wtComps = GWM_WTC_MENUBAR | GWM_WTC_TOOLBAR;
	wt.wtWindow = topWindow;
	wt.wtBody = boxLayout;
	gwmCreateTemplate(&wt);

	GWMWindow *menubar = wt.wtMenubar;

	GWMMenu *menuFile = gwmCreateMenu();
	gwmMenubarAdd(menubar, "File", menuFile);

	gwmMenuAddCommand(menuFile, SYM_FILE_DEMO, "Demo", NULL);
	gwmMenuAddCommand(menuFile, GWM_SYM_EXIT, NULL, NULL);

	GWMLayout *toolbar = wt.wtToolbar;

	int sym;
	for (sym=1; sym<35; sym++)
	{
		GWMToolButton *tool = gwmNewToolButton(topWindow);
		gwmSetToolButtonSymbol(tool, sym);
		gwmBoxLayoutAddWindow(toolbar, tool, 0, 0, 0);
	};

	GWMWindow *button1 = gwmCreateButtonWithLabel(
		topWindow,			// the parent window
		SYM_BUTTON1,			// the symbol
		"Button 1"			// and finally the label
	);

	gwmBoxLayoutAddWindow(
		boxLayout,			// the layout to add the button to
		button1,			// the button
		0,				// the proportion (use minimum size)
		0,				// the border width
		0				// flags
	);

	GWMWindow *button2, *button3;
	gwmBoxLayoutAddWindow(boxLayout, button2 = gwmCreateButtonWithLabel(topWindow, SYM_BUTTON2, "Button 2"), 0, 0, 0);
	gwmBoxLayoutAddWindow(boxLayout, button3 = gwmCreateButtonWithLabel(topWindow, SYM_BUTTON3, "Button 3"), 0, 0, 0);

	GWMWindow *optmenu = gwmNewOptionMenu(topWindow);
	gwmSetOptionMenu(optmenu, 0, "Select something...");
	gwmAddOptionMenu(optmenu, 1, "Here's one option");
	gwmAddOptionMenu(optmenu, 2, "...and another!");
	gwmAddOptionMenu(optmenu, 3, "And a final one!!!");
	gwmBoxLayoutAddWindow(boxLayout, optmenu, 0, 0, GWM_BOX_FILL);

	GWMCombo *combo = gwmNewCombo(topWindow);
	gwmBoxLayoutAddWindow(boxLayout, combo, 0, 0, GWM_BOX_FILL);
	gwmAddComboOption(combo, "First option");
	gwmAddComboOption(combo, "Some other option");
	gwmAddComboOption(combo, "кипeть злoбой");

	GWMIntSpinner *ispin = gwmNewIntSpinner(topWindow);
	gwmBoxLayoutAddWindow(boxLayout, ispin, 0, 0, GWM_BOX_FILL);
	gwmSetIntSpinnerFormat(ispin, "%d apples");

	GWMWindow *sliderHoriz = gwmNewSlider(topWindow);
	gwmSetSliderFlags(sliderHoriz, GWM_SLIDER_HORIZ);
	gwmSetSliderValue(sliderHoriz, 0.3);
	gwmBoxLayoutAddWindow(boxLayout, sliderHoriz, 0, 0, GWM_BOX_FILL);

	GWMWindow *sliderDisHoriz = gwmNewSlider(topWindow);
	gwmSetSliderFlags(sliderDisHoriz, GWM_SLIDER_HORIZ | GWM_SLIDER_DISABLED);
	gwmSetSliderValue(sliderDisHoriz, 0.2);
	gwmBoxLayoutAddWindow(boxLayout, sliderDisHoriz, 0, 0, GWM_BOX_FILL);

	GWMWindow *sbarHoriz = gwmNewScrollbar(topWindow);
	gwmSetScrollbarFlags(sbarHoriz, GWM_SLIDER_HORIZ);
	gwmSetScrollbarPosition(sbarHoriz, 0.2);
	gwmSetScrollbarLength(sbarHoriz, 0.5);
	gwmBoxLayoutAddWindow(boxLayout, sbarHoriz, 0, 0, GWM_BOX_FILL);

	txtfield = gwmNewTextField(topWindow);
	gwmWriteTextField(txtfield, "кипeть злoбой");
	gwmBoxLayoutAddWindow(boxLayout, txtfield, 0, 0, GWM_BOX_FILL);

	GWMWindow *checkbox = gwmNewCheckbox(topWindow);
	gwmSetCheckboxLabel(checkbox, "Play with me");
	gwmSetCheckboxSymbol(checkbox, SYM_CHECKBOX);
	gwmBoxLayoutAddWindow(boxLayout, checkbox, 0, 0, 0);

	cbMask = gwmNewCheckbox(topWindow);
	gwmSetCheckboxLabel(cbMask, "Mask the text");
	gwmSetCheckboxSymbol(cbMask, SYM_CB_MASK);
	gwmBoxLayoutAddWindow(boxLayout, cbMask, 0, 0, 0);

	GWMWindow *frame = gwmNewFrame(topWindow);
	gwmSetFrameCaption(frame, "Example frame");
	gwmBoxLayoutAddWindow(boxLayout, frame, 0, 0, 0);

	GWMWindow *panel = gwmGetFramePanel(frame);
	GWMLayout *panelLayout = gwmCreateBoxLayout(GWM_BOX_HORIZONTAL);
	gwmSetWindowLayout(panel, panelLayout);

	gwmBoxLayoutAddWindow(panelLayout, gwmCreateButtonWithLabel(panel, SYM_BUTTON_FRAME1, "Frame button 1"), 0, 0, 0);
	gwmBoxLayoutAddWindow(panelLayout, gwmCreateButtonWithLabel(panel, SYM_BUTTON_FRAME2, "Frame button 2"), 0, 0, 0);

	GWMWindow *sliderVert = gwmNewSlider(panel);
	gwmSetSliderValue(sliderVert, 0.5);
	gwmBoxLayoutAddWindow(panelLayout, sliderVert, 0, 0, GWM_BOX_FILL);

	GWMWindow *sliderDisVert = gwmNewSlider(panel);
	gwmSetSliderFlags(sliderDisVert, GWM_SLIDER_DISABLED);
	gwmSetSliderValue(sliderDisVert, 0.3);
	gwmBoxLayoutAddWindow(panelLayout, sliderDisVert, 0, 0, GWM_BOX_FILL);

	GWMWindow *sbarVert = gwmNewScrollbar(panel);
	gwmSetScrollbarPosition(sbarVert, 0.5);
	gwmSetScrollbarLength(sbarVert, 0.3);
	gwmBoxLayoutAddWindow(panelLayout, sbarVert, 0, 0, GWM_BOX_FILL);

	GWMWindow *frameA = gwmNewFrame(panel);
	gwmSetFrameCaption(frameA, "Radio group A");
	gwmBoxLayoutAddWindow(panelLayout, frameA, 0, 0, 0);

	GWMWindow *panelA = gwmGetFramePanel(frameA);
	GWMLayout *panelLayoutA = gwmCreateBoxLayout(GWM_BOX_VERTICAL);
	gwmSetWindowLayout(panelA, panelLayoutA);

	GWMRadioGroup *groupA = gwmCreateRadioGroup(0);

	GWMWindow *radioA1 = gwmNewRadioButton(panelA, groupA);
	gwmSetRadioButtonValue(radioA1, 0);
	gwmSetRadioButtonLabel(radioA1, "Radio button A1");
	gwmBoxLayoutAddWindow(panelLayoutA, radioA1, 0, 0, 0);

	GWMWindow *radioA2 = gwmNewRadioButton(panelA, groupA);
	gwmSetRadioButtonValue(radioA2, 1);
	gwmSetRadioButtonLabel(radioA2, "Radio button A2");
	gwmBoxLayoutAddWindow(panelLayoutA, radioA2, 0, 0, 0);

	GWMWindow *radioA3 = gwmNewRadioButton(panelA, groupA);
	gwmSetRadioButtonValue(radioA3, 2);
	gwmSetRadioButtonLabel(radioA3, "Radio button A3");
	gwmBoxLayoutAddWindow(panelLayoutA, radioA3, 0, 0, 0);

	GWMWindow *frameB = gwmNewFrame(panel);
	gwmSetFrameCaption(frameB, "Radio group B");
	gwmBoxLayoutAddWindow(panelLayout, frameB, 0, 0, 0);

	GWMWindow *panelB = gwmGetFramePanel(frameB);
	GWMLayout *panelLayoutB = gwmCreateBoxLayout(GWM_BOX_VERTICAL);
	gwmSetWindowLayout(panelB, panelLayoutB);

	GWMRadioGroup *groupB = gwmCreateRadioGroup(1);

	GWMWindow *radioB1 = gwmNewRadioButton(panelB, groupB);
	gwmSetRadioButtonValue(radioB1, 0);
	gwmSetRadioButtonLabel(radioB1, "Radio button B1");
	gwmBoxLayoutAddWindow(panelLayoutB, radioB1, 0, 0, 0);

	GWMWindow *radioB2 = gwmNewRadioButton(panelB, groupB);
	gwmSetRadioButtonValue(radioB2, 1);
	gwmSetRadioButtonLabel(radioB2, "Radio button B2");
	gwmBoxLayoutAddWindow(panelLayoutB, radioB2, 0, 0, 0);

	gwmFit(topWindow);
	gwmSetWindowFlags(topWindow, GWM_WINDOW_MKFOCUSED | GWM_WINDOW_RESIZEABLE);

	gwmMainLoop();
	gwmSetWindowFlags(topWindow, GWM_WINDOW_HIDDEN | GWM_WINDOW_NOTASKBAR);
	gwmDestroyButton(button1);
	gwmDestroyButton(button2);
	gwmDestroyButton(button3);
	gwmDestroyCheckbox(checkbox);
	gwmDestroyBoxLayout(boxLayout);
	gwmDestroyWindow(topWindow);
	gwmQuit();
	return 0;
};


text:
Using SDL with Microsoft Visual C++
===================================

### by Lion Kimbro with additions by James Turk

You can either use the precompiled libraries from the [SDL](https://www.libsdl.org/download.php) web site, or you can build SDL
yourself.

### Building SDL

0. To build SDL, your machine must, at a minimum, have the DirectX9.0c SDK installed. It may or may not be retrievable from
the [Microsoft](https://www.microsoft.com) website, so you might need to locate it [online](https://duckduckgo.com/?q=directx9.0c+sdk+download&t=h_&ia=web).
_Editor's note: I've been able to successfully build SDL using Visual Studio 2019 **without** the DX9.0c SDK_

1. Open the Visual Studio solution file at `./VisualC/SDL.sln`.

2. Your IDE will likely prompt you to upgrade this solution file to whatever later version of the IDE you're using. In the `Retarget Projects` dialog,
all of the affected project files should be checked allowing you to use the latest `Windows SDK Version` you have installed, along with
the `Platform Toolset`.

If you choose *NOT* to upgrade to use the latest `Windows SDK Version` or `Platform Toolset`, then you'll need the `Visual Studio 2010 Platform Toolset`.

3. Build the `.dll` and `.lib` files by right clicking on each project in turn (Projects are listed in the _Workspace_
panel in the _FileView_ tab), and selecting `Build`.

You may get a few warnings, but you should not get any errors.

Later, we will refer to the following `.lib` and `.dll` files that have just been generated:

-   `./VisualC/Win32/Debug/SDL2.dll` or `./VisualC/Win32/Release/SDL2.dll`
-   `./VisualC/Win32/Debug/SDL2.lib` or `./VisualC/Win32/Release/SDL2.lib`
-   `./VisualC/Win32/Debug/SDL2main.lib` or `./VisualC/Win32/Release/SDL2main.lib`

_Note for the `x64` versions, just replace `Win32` in the path with `x64`_

### Creating a Project with SDL

- Create a project as a `Win32 Application`.

- Create a C++ file for your project.

- Set the C runtime to `Multi-threaded DLL` in the menu:
`Project|Settings|C/C++                  tab|Code Generation|Runtime Library `.

- Add the SDL `include` directory to your list of includes in the menu:
`Project|Settings|C/C++ tab|Preprocessor|Additional include directories `

*VC7 Specific: Instead of doing this, I find it easier to add the
include and library directories to the list that VC7 keeps. Do this by
selecting Tools|Options|Projects|VC++ Directories and under the "Show
Directories For:" dropbox select "Include Files", and click the "New
Directory Icon" and add the [SDLROOT]\\include directory (e.g. If you
installed to c:\\SDL\\ add c:\\SDL\\include). Proceed to change the
dropbox selection to "Library Files" and add [SDLROOT]\\lib.*

The "include directory" I am referring to is the `./include` folder.

Now we're going to use the files that we had created earlier in the *Build SDL* step.

Copy the following file into your Project directory:

-   `SDL2.dll`

Add the following files to your project (It is not necessary to copy them to your project directory):

-   `SDL2.lib`
-   `SDL2main.lib`

To add them to your project, right click on your project, and select
`Add files to project`.

**Instead of adding the files to your project, it is more desirable to add them to the linker options: Project|Properties|Linker|Command Line
and type the names of the libraries to link with in the "Additional Options:" box. Note: This must be done for each build configuration
(e.g. Release,Debug).**

### Hello SDL2

Here's a sample SDL snippet to verify everything is setup in your IDE:

```
    #include "SDL.h"

    int main( int argc, char* argv[] )
    {
        const int WIDTH = 640;
        const int HEIGHT = 480;
        SDL_Window* window = NULL;
        SDL_Renderer* renderer = NULL;

        SDL_Init(SDL_INIT_VIDEO);
        window = SDL_CreateWindow("SDL2 Test", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN);
        renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        SDL_Quit();
        return 0;
    }
 ```

### That's it!

I hope that this document has helped you get through the most difficult part of using the SDL: installing it.
Suggestions for improvements should be posted to the [Github Issues](https://github.com/libsdl-org/SDL/issues).

### Credits

Thanks to [Paulus Esterhazy](mailto:pesterhazy@gmx.net), for the work on VC++ port.

This document was originally called "VisualC.txt", and was written by [Sam Lantinga](mailto:slouken@libsdl.org).

Later, it was converted to HTML and expanded into the document that you see today by [Lion Kimbro](mailto:snowlion@sprynet.com).

Minor Fixes and Visual C++ 7 Information (In Green) was added by [James Turk](mailto:james@conceptofzero.net)


text:
Clojure implementation of blockchain inspired by this [article](https://hackernoon.com/learn-blockchains-by-building-one-117428612f46)

[![Build Status](https://travis-ci.org/ThatGuyHughesy/blockchain.svg?branch=master)](https://travis-ci.org/ThatGuyHughesy/blockchain)

## Development

Run locally
```sh
$ lein ring server-headless
```

Testing
```sh
$ lein test
```

## Endpoints

**Add a new transaction to a block.**

```sh
POST /transactions/new
```

Parameters

| Name          | Type          | Description
| ------------- | ------------- |------------------------- |
| sender        | string        | Who is sending the coins |
| recipient     | string        | Who to send the coins to |
| amount        | int           | Number of coins          |

**Mine a new block.**

```sh
POST /mine
```

**Get the full Blockchain.**

```sh
GET /chain
```

**Add a new node.**

```sh
POST /nodes/new
```

Parameters

| Name          | Type          | Description
| ------------- | ------------- |------------------------- |
| address       | url           | URL of node              |

**Get all nodes.**

```sh
GET /nodes
```

**Resolve node conflicts.**

```sh
POST /nodes/resolve
```

## Contributing

Want to become a Blockchain [contributor](https://github.com/ThatGuyHughesy/blockchain/blob/master/CONTRIBUTORS.md)?
Then checkout our [code of conduct](https://github.com/ThatGuyHughesy/blockchain/blob/master/CODE_OF_CONDUCT.md) and [contributing guidelines](https://github.com/ThatGuyHughesy/blockchain/blob/master/CONTRIBUTING.md).

## Copyright & License

Copyright (c) 2017 Conor Hughes - Released under the MIT license.


text:
using System;

namespace csogg
{
	/// <summary>
	/// Summary description for Packet.
	/// </summary>
	public class Packet
	{
		public byte[] packet_base;
		public int packet;
		public int bytes;
		public int b_o_s;
		public int e_o_s;

		public long granulepos;

		public long packetno; // sequence number for decode; the framing
		// knows where there's a hole in the data,
		// but we need coupling so that the codec
		// (which is in a seperate abstraction
		// layer) also knows about the gap

		public Packet()
		{
			// No constructor
		}
	}
}


text:
package de.neofonie.cinderella.core.config.xml.condition;

import de.neofonie.cinderella.core.RequestUtil;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;

/**
 * Checks if the user has a session.
 */
@XmlAccessorType(XmlAccessType.FIELD)
public class Session implements Condition {

    @XmlAttribute(required = true)
    private boolean session;

    @Override
    public boolean matches(HttpServletRequest request) {
        boolean hasSession = RequestUtil.hasSession(request);
        return session == hasSession;
    }

    public boolean isSession() {
        return session;
    }

    public void setSession(boolean session) {
        this.session = session;
    }

    @Override
    public String toString() {
        return "Session{" +
                "session=" + session +
                '}';
    }
}


text:
@interface YWAddressController ()<UITableViewDelegate,UITableViewDataSource,YWAderssCellDelegate>
{
    NSMutableArray *_addressFrames;
    YWAderssCell *_lastCell;

}
@property (nonatomic,strong) UILabel *label;

@property (nonatomic,strong) UITableView *tableView;
@end

@implementation YWAddressController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = KviewColor;
    self.title = @"地址管理";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, KscreenHeight-50-64) style:UITableViewStyleGrouped];
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    //请求网络上的地址数据
    [self requestAddress];

    //添加添加按钮
    UIButton *exitButton = [[UIButton alloc]initWithFrame:CGRectMake(0, KscreenHeight-50, kScreenWidth, 50)];
    exitButton.backgroundColor = KthemeColor;
    [exitButton setTitle:@"添加新地址" forState:UIControlStateNormal];
    [exitButton setBackgroundImage:[UIImage imageWithColor:[UIColor grayColor]] forState:UIControlStateHighlighted];
    [exitButton addTarget:self action:@selector(add:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:exitButton];

    _label = [[UILabel alloc]init];
    _label.frame = CGRectMake(0, self.view.center.y-50, kScreenWidth, 40);
    _label.text = @"您还没有保存收货地址";
    _label.font = [UIFont systemFontOfSize:20];
    _label.textAlignment = NSTextAlignmentCenter;
    _label.hidden = YES;
    [self.view addSubview:_label];

}

- (void)requestAddress{
    _label.hidden = YES;
    YWUser *user = [YWUserTool account];
    NSMutableDictionary *parameters = [Utils paramter:Addres ID:user.ID];
    [YWHttptool GET:YWAddrList parameters:parameters success:^(id responseObject) {
        if ([Utils isNull:responseObject[@"result"]]) {
            _label.hidden = NO;
        }else{
              NSMutableArray *array = [YWAddressModel yw_objectWithKeyValuesArray:responseObject[@"result"]];
            _addressFrames = [NSMutableArray array];
            for (YWAddressModel *adderss in array){
                YWAddressFrame *addressFrame = [[YWAddressFrame alloc]init];
                addressFrame.model = adderss;
                [_addressFrames addObject:addressFrame];
            }
            [_tableView reloadData];
        }
    } failure:^(NSError *error) {

    }];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _addressFrames.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (YWAderssCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     YWAderssCell *cell = [tableView dequeueReusableCellWithIdentifier:@"addressCell" ];
    if (!cell) {
        cell = [[YWAderssCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"addressCell"];

    }
    //获取address模型
    YWAddressFrame *addressFrame = _addressFrames[indexPath.section];
    cell.indexpath = indexPath;
    cell.delegate = self;
    if ([addressFrame.model.isselect isEqualToString:@"1"]) {
        _lastCell = cell;
    }
    //给cell传递模型
    [cell configModel:addressFrame];

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 17;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    YWAddressFrame *addressFrame = _addressFrames[indexPath.section];
    return addressFrame.cellHeight;
}

- (void)clickCell:(NSIndexPath *)indexpath tag:(NSInteger)tag{
    //点击地址管理
    switch (tag) {
        case 1:
        {
            [_lastCell.defaultButoon setImage:[UIImage imageNamed:@"4"] forState:UIControlStateNormal];
            [_lastCell.defaultButoon setTitle:@"设为默认" forState:UIControlStateNormal];
            [_lastCell.defaultButoon setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            YWAderssCell *cell = [self.tableView cellForRowAtIndexPath:indexpath];
            [cell.defaultButoon setImage:[UIImage imageNamed:@"3"] forState:UIControlStateNormal];
            [cell.defaultButoon setTitle:@"默认地址" forState:UIControlStateNormal];
            [cell.defaultButoon setTitleColor:KthemeColor forState:UIControlStateNormal];
            _lastCell = cell;
            [self setOrdelete:[NSString stringWithFormat:@"%ld",tag] indexpath:indexpath];
        }
            break;
        case 2:
        {   YWAddressFrame *frame = _addressFrames[indexpath.section];
            YWAddressEditController *editVC = [[YWAddressEditController alloc]init];
            editVC.addressModel = frame.model;
            [self.navigationController pushViewController:editVC animated:YES];
        }
            break;
        case 3:
        { //设置提醒框
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"确认删除" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                [self setOrdelete:[NSString stringWithFormat:@"%ld",tag-1] indexpath:indexpath];
            }];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
            [alertController addAction:action1];
            [alertController addAction:cancelAction];
            [self presentViewController:alertController animated:YES completion:nil];
        }
            break;

        default:
            break;
    }
}

//删除,设置默认地址
- (void)setOrdelete:(NSString *)number indexpath:(NSIndexPath*)indexpath{
    YWUser *user = [YWUserTool account];
    YWAddressFrame *frame = _addressFrames[indexpath.section];
    YWAddressModel *model = frame.model;
    NSMutableDictionary *parametrs = [Utils paramter:SetAddr ID:user.ID];
    parametrs[@"aim"] = [[model.ID dataUsingEncoding:NSUTF8StringEncoding]base64EncodedStringWithOptions:0];
    parametrs[@"akd"] = [[number dataUsingEncoding:NSUTF8StringEncoding]base64EncodedStringWithOptions:0];
    [YWHttptool Post:YWSetAddr parameters:parametrs success:^(id responseObject) {
        if ([number isEqualToString:@"2"]) {
            [_addressFrames removeAllObjects];
            if (![Utils isNull:responseObject[@"result"]]){
                _label.hidden = YES;
                NSMutableArray *array = [YWAddressModel yw_objectWithKeyValuesArray:responseObject[@"result"]];
                for (YWAddressModel *adderss in array){
                    YWAddressFrame *addressFrame = [[YWAddressFrame alloc]init];
                    addressFrame.model = adderss;
                    [_addressFrames addObject:addressFrame];
                }
            }else{
                _label.hidden = NO;
            }
             [_tableView reloadData];
            }
    } failure:^(NSError *error) {
    }];
}

- (void)add:(UIButton *)sender{
    YWAddressEditController *editVC = [[YWAddressEditController alloc]init];
    editVC.type = @"1";
    [self.navigationController pushViewController:editVC animated:YES];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self requestAddress];
}
@end


text:
gitmessage1="diff --git a/README.md b/README.md
index 304484b..0401187 100644
--- a/README.md
+++ b/README.md
@@ -33,4 +33,9 @@ is no more than 80 characters. This command will pass.
 `./commit_message.sh "Adds new field to protobuf and sample" false 80`

 This will verify that the commit message above should be in past-tense and each
-line is no more than 80 characters. This command will fail.
\ No newline at end of file
+line is no more than 80 characters. This command will fail.
+
+## Git Diffs
+There are variety of changes that a contributor may make to a repo. To ensure
+that changes are consistent, this script can be used to verify a variety of
+potential changes.
\ No newline at end of file
"

gitmessage1_todo="diff --git a/README.md b/README.md
index 304484b..0401187 100644
--- a/README.md
+++ b/README.md
@@ -33,4 +33,9 @@ is no more than 80 characters. This command will pass.
 # (TODO @ Nick) Fix this typo
 `./commit_message.sh "Adds new field to protobuf and sample" false 80`

 This will verify that the commit message above should be in past-tense and each
-line is no more than 80 characters. This command will fail.
\ No newline at end of file
+line is no more than 80 characters. This command will fail.
+
+## Git Diffs
+todo remove this line later
+There are variety of changes that a contributor may make to a repo. To ensure
+that changes are consistent, this script can be used to verify a variety of
+potential changes.
\ No newline at end of file
"

# Verifies that the code does not have a TODO
echo "$gitmessage1" | ./rules/block-string.sh "TODO"
if [ $? -ne 0 ]; then
    echo "Test failed"
    exit 1
fi

# Verify that the commit has TODOs
echo "$gitmessage1_todo" | ./rules/block-string.sh "TODO"
if [ $? -eq 0 ]; then
    echo "Test failed"
    exit 1
fi

echo "All tests pass"