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

namespace Csg.Data.Sql
{
    /// <summary>
    /// Represents a column in a SELECT statement defined as a literal value.
    /// </summary>
    public class SqlLiteralColumn<TValue> : ISqlColumn
    {
        /// <summary>
        /// Initializes a new instance with the given value.
        /// </summary>
        /// <param name="value"></param>
        public SqlLiteralColumn(TValue value)
        {
            this.Value = value;
        }

        /// <summary>
        /// Initializes a new instance with the given value and alias.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="alias"></param>
        public SqlLiteralColumn(TValue value, string alias)
        {
            this.Value = value;
            this.Alias = alias;
        }

        /// <summary>
        /// Gets or sets the literal value.
        /// </summary>
        public TValue Value { get; set; }

        /// <summary>
        /// Gets a value that indicates if the column is an aggregate.
        /// </summary>
        public bool IsAggregate
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// Get or sets the <see cref="ISqlTable"/> table associated with the column.
        /// </summary>
        public ISqlTable Table { get; set; }

        /// <summary>
        /// Gets or sets the column alias to use when rendering the SELECT statement.
        /// </summary>
        public string Alias { get; set; }

        /// <summary>
        /// Gets the column alias to use when rendering the SELECT statement.
        /// </summary>
        /// <returns>The name of the column to use.</returns>
        public string GetAlias()
        {
            return this.Alias;
        }

        public void Render(SqlTextWriter writer, SqlBuildArguments args)
        {
            writer.WriteLiteralValue(this.Value);
            if (this.Alias != null)
            {
                writer.WriteSpace();
                writer.Write(SqlConstants.AS);
                writer.WriteSpace();
                writer.WriteColumnName(this.Alias);
            }
        }

        public void RenderValueExpression(SqlTextWriter writer, SqlBuildArguments args)
        {
            writer.WriteLiteralValue(this.Value);
        }
    }
}


text:
import {Component, OnInit} from '@angular/core';
import {Store} from '@ngrx/store';
import {AppState} from '../../store/appState.store';

import {AppItemComponent} from "../app-item/appItem.component";
import {AppItem} from "../app-item/appItem.model";
import {ACTION_TYPES} from "../../store/store";

const exec = require('child_process').exec;
const fs = require('fs');
const request = require('request');

declare let Notification: any;

@Component({
  selector: 'ae-home',
  template: `

Dev Apps

            Featured

            Updates

            My Apps

            Public

            Installed

          <login-form [title]="'Active Directory'"></login-form>
          <login-form [title]="'Crowd'"></login-form>

          <input #searchTextBox class="form-control" type="text" placeholder="type to search..." (keyup)="filterChanged(searchTextBox.value)">

          <app-item (installClicked)="download($event)"
                    [appItem]="app"></app-item>

  `,
  styleUrls: ['./apps.component.scss'],
})
export class AppsComponent implements OnInit {

  name: string;
  apps: Array<AppItem>;
  filteredApps: Array<AppItem>;

  constructor(public store: Store<AppState>) {
  }

  ngOnInit() {
    // let state = this.store.select('apps').subscribe((apps: Array<AppItem>) => {
    let state = this.store.subscribe((state: any) => {
      this.apps =  state.store.apps;
      this.filteredApps = this.apps;
    });
  }

  filterChanged(searchString) {
    this.filteredApps = this.apps.filter((app) => app.title.toLowerCase().indexOf(searchString.toLowerCase()) != -1);
  }

  doNotify() {
    let message = {
      title: "Content-Image Notification",
      body: "Short message plus a custom content image",
    };
    new Notification(message.title, message);
  }

  download(appItemComponent: AppItemComponent) {
    this.store.dispatch({
      type: ACTION_TYPES.INSTALL_APP,
      payload: appItemComponent.appItem
    });
    var out = fs.createWriteStream(appItemComponent.appItem.storeAs);
    let sizeBytes = appItemComponent.appItem.expectedDownloadSize;

    let downloadedBytes = 0;

    var req = request({
      method: 'GET',
      uri: appItemComponent.appItem.downloadUrl
    });
    req.on( 'response', function ( data ) {
      if(data.headers['content-length']) {
        console.log("content-length: " + data.headers['content-length']);
        sizeBytes = data.headers['content-length'];
      }
    });
    if(!sizeBytes) {
      sizeBytes = 100;
    }

    req.pipe(out);
    req.on('data', (chunk) => {
      downloadedBytes = downloadedBytes + chunk.length;
      let progressPercent = Math.round(downloadedBytes * 100 / sizeBytes);
      appItemComponent.updateProgressTo(progressPercent);
    });

    req.on('end', () => {
      this.install(appItemComponent.appItem);
      this.store.dispatch({
        type: ACTION_TYPES.INSTALL_APP_DONE
      });
    });
  }

  install(appItem: AppItem) {
    exec(appItem.installCommand, (error, stdout, stderr) => {
      if (error) {
        console.log(`exec error: ${error}`);
      }
    });
  }

}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.flink.streaming.examples.windowing;

import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.java.tuple.Tuple4;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.functions.timestamps.AscendingTimestampExtractor;
import org.apache.flink.streaming.api.functions.windowing.delta.DeltaFunction;
import org.apache.flink.streaming.api.windowing.assigners.GlobalWindows;
import org.apache.flink.streaming.api.windowing.evictors.TimeEvictor;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.triggers.DeltaTrigger;

import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * An example of grouped stream windowing where different eviction and trigger
 * policies can be used. A source fetches events from cars every 100 msec
 * containing their id, their current speed (kmh), overall elapsed distance (m)
 * and a timestamp. The streaming example triggers the top speed of each car
 * every x meters elapsed for the last y seconds.
 */
public class TopSpeedWindowing {

	// *************************************************************************
	// PROGRAM
	// *************************************************************************

	public static void main(String[] args) throws Exception {

		final ParameterTool params = ParameterTool.fromArgs(args);

		final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
		env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
		env.getConfig().setGlobalJobParameters(params);

		@SuppressWarnings({"rawtypes", "serial"})
		DataStream<Tuple4<Integer, Integer, Double, Long>> carData;
		if (params.has("input")) {
			carData = env.readTextFile(params.get("input")).map(new ParseCarData());
		} else {
			System.out.println("Executing TopSpeedWindowing example with default input data set.");
			System.out.println("Use --input to specify file input.");
			carData = env.addSource(CarSource.create(2));
		}

		int evictionSec = 10;
		double triggerMeters = 50;
		DataStream<Tuple4<Integer, Integer, Double, Long>> topSpeeds = carData
				.assignTimestampsAndWatermarks(new CarTimestamp())
				.keyBy(value -> value.f0)
				.window(GlobalWindows.create())
				.evictor(TimeEvictor.of(Time.of(evictionSec, TimeUnit.SECONDS)))
				.trigger(DeltaTrigger.of(triggerMeters,
						new DeltaFunction<Tuple4<Integer, Integer, Double, Long>>() {
							private static final long serialVersionUID = 1L;

							@Override
							public double getDelta(
									Tuple4<Integer, Integer, Double, Long> oldDataPoint,
									Tuple4<Integer, Integer, Double, Long> newDataPoint) {
								return newDataPoint.f2 - oldDataPoint.f2;
							}
						}, carData.getType().createSerializer(env.getConfig())))
				.maxBy(1);

		if (params.has("output")) {
			topSpeeds.writeAsText(params.get("output"));
		} else {
			System.out.println("Printing result to stdout. Use --output to specify output path.");
			topSpeeds.print();
		}

		env.execute("CarTopSpeedWindowingExample");
	}

	// *************************************************************************
	// USER FUNCTIONS
	// *************************************************************************

	private static class CarSource implements SourceFunction<Tuple4<Integer, Integer, Double, Long>> {

		private static final long serialVersionUID = 1L;
		private Integer[] speeds;
		private Double[] distances;

		private Random rand = new Random();

		private volatile boolean isRunning = true;

		private CarSource(int numOfCars) {
			speeds = new Integer[numOfCars];
			distances = new Double[numOfCars];
			Arrays.fill(speeds, 50);
			Arrays.fill(distances, 0d);
		}

		public static CarSource create(int cars) {
			return new CarSource(cars);
		}

		@Override
		public void run(SourceContext<Tuple4<Integer, Integer, Double, Long>> ctx) throws Exception {

			while (isRunning) {
				Thread.sleep(100);
				for (int carId = 0; carId < speeds.length; carId++) {
					if (rand.nextBoolean()) {
						speeds[carId] = Math.min(100, speeds[carId] + 5);
					} else {
						speeds[carId] = Math.max(0, speeds[carId] - 5);
					}
					distances[carId] += speeds[carId] / 3.6d;
					Tuple4<Integer, Integer, Double, Long> record = new Tuple4<>(carId,
							speeds[carId], distances[carId], System.currentTimeMillis());
					ctx.collect(record);
				}
			}
		}

		@Override
		public void cancel() {
			isRunning = false;
		}
	}

	private static class ParseCarData extends RichMapFunction<String, Tuple4<Integer, Integer, Double, Long>> {
		private static final long serialVersionUID = 1L;

		@Override
		public Tuple4<Integer, Integer, Double, Long> map(String record) {
			String rawData = record.substring(1, record.length() - 1);
			String[] data = rawData.split(",");
			return new Tuple4<>(Integer.valueOf(data[0]), Integer.valueOf(data[1]), Double.valueOf(data[2]), Long.valueOf(data[3]));
		}
	}

	private static class CarTimestamp extends AscendingTimestampExtractor<Tuple4<Integer, Integer, Double, Long>> {
		private static final long serialVersionUID = 1L;

		@Override
		public long extractAscendingTimestamp(Tuple4<Integer, Integer, Double, Long> element) {
			return element.f3;
		}
	}

}


text:
<html>
<head>
	<title>CSS LIGHT LEVEL</title>
	<!-- http://dev.w3.org/csswg/mediaqueries4/#mf-environment -->
	<style type="text/css">
		@media (light-level: normal) {
			p {
				background: grey; color: #333;
			}
		}

		@media (light-level: dim) {
			p {
				background: red; color: #ccc;
			}
		}

		@media (light-level: washed) {
			p {
				background: green; color: #white;
			}
		}

	</style>
</head>
<body>
	<h2> This is a test for CSS LIGHT LEVEL. Please try different light source, then check my font color and backgroung color.</h2>
</body>
</html>


text:
package org.apache.camel.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

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

public class CaseInsensitiveMapTest extends Assert {

    @Test
    public void testLookupCaseAgnostic() {
        Map<String, Object> map = new CaseInsensitiveMap();
        assertNull(map.get("foo"));

        map.put("foo", "cheese");

        assertEquals("cheese", map.get("foo"));
        assertEquals("cheese", map.get("Foo"));
        assertEquals("cheese", map.get("FOO"));
    }

    @Test
    public void testLookupCaseAgnosticAddHeader() {
        Map<String, Object> map = new CaseInsensitiveMap();
        assertNull(map.get("foo"));

        map.put("foo", "cheese");

        assertEquals("cheese", map.get("foo"));
        assertEquals("cheese", map.get("Foo"));
        assertEquals("cheese", map.get("FOO"));
        assertNull(map.get("unknown"));

        map.put("bar", "beer");

        assertEquals("beer", map.get("bar"));
        assertEquals("beer", map.get("Bar"));
        assertEquals("beer", map.get("BAR"));
        assertNull(map.get("unknown"));
    }

    @Test
    public void testLookupCaseAgnosticAddHeader2() {
        Map<String, Object> map = new CaseInsensitiveMap();
        assertNull(map.get("foo"));

        map.put("foo", "cheese");

        assertEquals("cheese", map.get("FOO"));
        assertEquals("cheese", map.get("foo"));
        assertEquals("cheese", map.get("Foo"));
        assertNull(map.get("unknown"));

        map.put("bar", "beer");

        assertEquals("beer", map.get("BAR"));
        assertEquals("beer", map.get("bar"));
        assertEquals("beer", map.get("Bar"));
        assertNull(map.get("unknown"));
    }

    @Test
    public void testLookupCaseAgnosticAddHeaderRemoveHeader() {
        Map<String, Object> map = new CaseInsensitiveMap();
        assertNull(map.get("foo"));

        map.put("foo", "cheese");

        assertEquals("cheese", map.get("foo"));
        assertEquals("cheese", map.get("Foo"));
        assertEquals("cheese", map.get("FOO"));
        assertNull(map.get("unknown"));

        map.put("bar", "beer");

        assertEquals("beer", map.get("bar"));
        assertEquals("beer", map.get("Bar"));
        assertEquals("beer", map.get("BAR"));
        assertNull(map.get("unknown"));

        map.remove("bar");
        assertNull(map.get("bar"));
        assertNull(map.get("unknown"));
    }

    @Test
    public void testSetWithDifferentCase() {
        Map<String, Object> map = new CaseInsensitiveMap();
        assertNull(map.get("foo"));

        map.put("foo", "cheese");
        map.put("Foo", "bar");

        assertEquals("bar", map.get("FOO"));
        assertEquals("bar", map.get("foo"));
        assertEquals("bar", map.get("Foo"));
    }

    @Test
    public void testRemoveWithDifferentCase() {
        Map<String, Object> map = new CaseInsensitiveMap();
        assertNull(map.get("foo"));

        map.put("foo", "cheese");
        map.put("Foo", "bar");

        assertEquals("bar", map.get("FOO"));
        assertEquals("bar", map.get("foo"));
        assertEquals("bar", map.get("Foo"));

        map.remove("FOO");

        assertEquals(null, map.get("foo"));
        assertEquals(null, map.get("Foo"));
        assertEquals(null, map.get("FOO"));

        assertTrue(map.isEmpty());
    }

    @Test
    public void testPutAll() {
        Map<String, Object> map = new CaseInsensitiveMap();
        assertNull(map.get("foo"));

        Map<String, Object> other = new CaseInsensitiveMap();
        other.put("Foo", "cheese");
        other.put("bar", 123);

        map.putAll(other);

        assertEquals("cheese", map.get("FOO"));
        assertEquals("cheese", map.get("foo"));
        assertEquals("cheese", map.get("Foo"));

        assertEquals(123, map.get("BAR"));
        assertEquals(123, map.get("bar"));
        assertEquals(123, map.get("BaR"));

        // key case should be preserved
        Map<String, Object> keys = new HashMap<>();
        keys.putAll(map);

        assertEquals("cheese", keys.get("Foo"));
        assertNull(keys.get("foo"));
        assertNull(keys.get("FOO"));

        assertEquals(123, keys.get("bar"));
        assertNull(keys.get("Bar"));
        assertNull(keys.get("BAR"));
    }

    @Test
    public void testPutAllOther() {
        Map<String, Object> map = new CaseInsensitiveMap();
        assertNull(map.get("foo"));

        Map<String, Object> other = new HashMap<>();
        other.put("Foo", "cheese");
        other.put("bar", 123);

        map.putAll(other);

        assertEquals("cheese", map.get("FOO"));
        assertEquals("cheese", map.get("foo"));
        assertEquals("cheese", map.get("Foo"));

        assertEquals(123, map.get("BAR"));
        assertEquals(123, map.get("bar"));
        assertEquals(123, map.get("BaR"));
    }

    @Test
    public void testPutAllEmpty() {
        Map<String, Object> map = new CaseInsensitiveMap();
        map.put("foo", "cheese");

        Map<String, Object> other = new HashMap<>();
        map.putAll(other);

        assertEquals("cheese", map.get("FOO"));
        assertEquals("cheese", map.get("foo"));
        assertEquals("cheese", map.get("Foo"));

        assertEquals(1, map.size());
    }

    @Test
    public void testConstructFromOther() {
        Map<String, Object> other = new HashMap<>();
        other.put("Foo", "cheese");
        other.put("bar", 123);

        Map<String, Object> map = new CaseInsensitiveMap(other);

        assertEquals("cheese", map.get("FOO"));
        assertEquals("cheese", map.get("foo"));
        assertEquals("cheese", map.get("Foo"));

        assertEquals(123, map.get("BAR"));
        assertEquals(123, map.get("bar"));
        assertEquals(123, map.get("BaR"));
    }

    @Test
    public void testKeySet() {
        Map<String, Object> map = new CaseInsensitiveMap();
        map.put("Foo", "cheese");
        map.put("BAR", 123);
        map.put("baZ", "beer");

        Set<String> keys = map.keySet();

        // we should be able to lookup no matter what case
        assertTrue(keys.contains("Foo"));
        assertTrue(keys.contains("foo"));
        assertTrue(keys.contains("FOO"));

        assertTrue(keys.contains("BAR"));
        assertTrue(keys.contains("bar"));
        assertTrue(keys.contains("Bar"));

        assertTrue(keys.contains("baZ"));
        assertTrue(keys.contains("baz"));
        assertTrue(keys.contains("Baz"));
        assertTrue(keys.contains("BAZ"));
    }

    @Test
    public void testRetainKeysCopyToAnotherMap() {
        Map<String, Object> map = new CaseInsensitiveMap();
        map.put("Foo", "cheese");
        map.put("BAR", 123);
        map.put("baZ", "beer");

        Map<String, Object> other = new HashMap<>(map);

        // we should retain the cases of the original keys
        // when its copied to another map
        assertTrue(other.containsKey("Foo"));
        assertFalse(other.containsKey("foo"));
        assertFalse(other.containsKey("FOO"));

        assertTrue(other.containsKey("BAR"));
        assertFalse(other.containsKey("bar"));
        assertFalse(other.containsKey("Bar"));

        assertTrue(other.containsKey("baZ"));
        assertFalse(other.containsKey("baz"));
        assertFalse(other.containsKey("Baz"));
        assertFalse(other.containsKey("BAZ"));
    }

    @Test
    public void testValues() {
        Map<String, Object> map = new CaseInsensitiveMap();
        map.put("Foo", "cheese");
        map.put("BAR", "123");
        map.put("baZ", "Beer");

        Iterator<Object> it = map.values().iterator();

        // should be String values
        assertEquals("String", it.next().getClass().getSimpleName());
        assertEquals("String", it.next().getClass().getSimpleName());
        assertEquals("String", it.next().getClass().getSimpleName());

        Collection<Object> values = map.values();
        assertEquals(3, values.size());
        assertTrue(values.contains("cheese"));
        assertTrue(values.contains("123"));
        assertTrue(values.contains("Beer"));
    }

    @Test
    public void testRomeks() {
        Map<String, Object> map = new CaseInsensitiveMap();
        map.put("foo", "cheese");

        assertEquals(1, map.size());
        assertEquals("cheese", map.get("fOo"));
        assertEquals(true, map.containsKey("foo"));
        assertEquals(true, map.containsKey("FOO"));

        assertEquals(true, map.keySet().contains("FOO"));
        assertEquals(true, map.keySet().contains("FoO"));
        assertEquals(true, map.keySet().contains("Foo"));
        assertEquals(true, map.keySet().contains("foo"));
        assertEquals(true, map.keySet().contains("fOO"));

        map.put("FOO", "cake");
        assertEquals(1, map.size());
        assertEquals(true, map.containsKey("foo"));
        assertEquals(true, map.containsKey("FOO"));

        assertEquals("cake", map.get("fOo"));
    }

    @Test
    public void testRomeksUsingRegularHashMap() {
        Map<String, Object> map = new HashMap<>();
        map.put("foo", "cheese");

        assertEquals(1, map.size());
        assertEquals(null, map.get("fOo"));
        assertEquals(true, map.containsKey("foo"));
        assertEquals(false, map.containsKey("FOO"));

        assertEquals(false, map.keySet().contains("FOO"));

        map.put("FOO", "cake");
        assertEquals(2, map.size());
        assertEquals(true, map.containsKey("foo"));
        assertEquals(true, map.containsKey("FOO"));

        assertEquals(null, map.get("fOo"));
        assertEquals("cheese", map.get("foo"));
        assertEquals("cake", map.get("FOO"));
    }

    @Test
    public void testRomeksTransferredToHashMapAfterwards() {
        Map<String, Object> map = new CaseInsensitiveMap();
        map.put("Foo", "cheese");
        map.put("FOO", "cake");
        assertEquals(1, map.size());
        assertEquals(true, map.containsKey("foo"));
        assertEquals(true, map.containsKey("FOO"));

        Map<String, Object> other = new HashMap<>(map);
        assertEquals(false, other.containsKey("foo"));
        assertEquals(false, other.containsKey("FOO"));
        // CaseInsensitiveMap preserves the original keys, which would be the 1st key we put
        assertEquals(true, other.containsKey("Foo"));
        assertEquals(1, other.size());
    }

    @Test
    public void testSerialization() throws Exception {
        CaseInsensitiveMap testMap = new CaseInsensitiveMap();
        testMap.put("key", "value");
        // force entry set to be created which could cause the map to be non serializable
        testMap.entrySet();

        ByteArrayOutputStream bStream = new ByteArrayOutputStream();
        ObjectOutputStream objStream = new ObjectOutputStream(bStream);
        objStream.writeObject(testMap);

        ObjectInputStream inStream = new ObjectInputStream(new ByteArrayInputStream(bStream.toByteArray()));
        CaseInsensitiveMap testMapCopy = (CaseInsensitiveMap) inStream.readObject();

        assertTrue(testMapCopy.containsKey("key"));
    }

    @Test
    public void testCopyToAnotherMapPreserveKeyCaseEntrySet() {
        Map<String, Object> map = new CaseInsensitiveMap();
        map.put("Foo", "cheese");
        map.put("BAR", "cake");
        assertEquals(2, map.size());
        assertEquals(true, map.containsKey("foo"));
        assertEquals(true, map.containsKey("bar"));

        Map<String, Object> other = new HashMap<>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            other.put(key, value);
        }

        assertEquals(false, other.containsKey("foo"));
        assertEquals(true, other.containsKey("Foo"));
        assertEquals(false, other.containsKey("bar"));
        assertEquals(true, other.containsKey("BAR"));
        assertEquals(2, other.size());
    }

    @Test
    public void testCopyToAnotherMapPreserveKeyCasePutAll() {
        Map<String, Object> map = new CaseInsensitiveMap();
        map.put("Foo", "cheese");
        map.put("BAR", "cake");
        assertEquals(2, map.size());
        assertEquals(true, map.containsKey("foo"));
        assertEquals(true, map.containsKey("bar"));

        Map<String, Object> other = new HashMap<>();
        other.putAll(map);

        assertEquals(false, other.containsKey("foo"));
        assertEquals(true, other.containsKey("Foo"));
        assertEquals(false, other.containsKey("bar"));
        assertEquals(true, other.containsKey("BAR"));
        assertEquals(2, other.size());
    }

    @Test
    public void testCopyToAnotherMapPreserveKeyCaseCtr() {
        Map<String, Object> map = new CaseInsensitiveMap();
        map.put("Foo", "cheese");
        map.put("BAR", "cake");
        assertEquals(2, map.size());
        assertEquals(true, map.containsKey("foo"));
        assertEquals(true, map.containsKey("bar"));

        Map<String, Object> other = new HashMap<>(map);

        assertEquals(false, other.containsKey("foo"));
        assertEquals(true, other.containsKey("Foo"));
        assertEquals(false, other.containsKey("bar"));
        assertEquals(true, other.containsKey("BAR"));
        assertEquals(2, other.size());
    }

    @Test
    public void testCopyToAnotherMapPreserveKeyKeySet() {
        Map<String, Object> map = new CaseInsensitiveMap();
        map.put("Foo", "cheese");
        map.put("BAR", "cake");
        assertEquals(2, map.size());
        assertEquals(true, map.containsKey("foo"));
        assertEquals(true, map.containsKey("bar"));

        Map<String, Object> other = new HashMap<>();

        for (String key : map.keySet()) {
            Object value = map.get(key);
            other.put(key, value);
        }

        // the original case of the keys should be preserved
        assertEquals(false, other.containsKey("foo"));
        assertEquals(true, other.containsKey("Foo"));
        assertEquals(false, other.containsKey("bar"));
        assertEquals(true, other.containsKey("BAR"));
        assertEquals(2, other.size());
    }

    @Test
    public void testConcurrent() throws Exception {
        ExecutorService service = Executors.newFixedThreadPool(5);

        final CountDownLatch latch = new CountDownLatch(1000);
        final Map<String, Object> map = new CaseInsensitiveMap();

        // do some stuff concurrently
        for (int i = 0; i < 1000; i++) {
            final int count = i;
            service.submit(new Runnable() {
                public void run() {
                    Map<String, Object> foo = new CaseInsensitiveMap();
                    foo.put("counter" + count, count);
                    foo.put("foo", 123);
                    foo.put("bar", 456);
                    foo.put("cake", "cheese");

                    // copy foo to map as map is a shared resource
                    synchronized (map) {
                        map.putAll(foo);
                    }

                    latch.countDown();
                }
            });
        }

        assertTrue(latch.await(10, TimeUnit.SECONDS));

        assertEquals(1003, map.size());
        assertEquals(true, map.containsKey("counter0"));
        assertEquals(true, map.containsKey("counter500"));
        assertEquals(true, map.containsKey("counter999"));

        assertEquals(123, map.get("FOO"));
        assertEquals(456, map.get("Bar"));
        assertEquals("cheese", map.get("cAKe"));
        service.shutdownNow();
    }

    @Ignore("Manual test")
    public void xxxTestCopyMapWithCamelHeadersTest() throws Exception {
        Map<String, Object> map = new CaseInsensitiveMap();
        map.put("CamelA", "A");
        map.put("CamelB", "B");
        map.put("CamelC", "C");

        // retain maps so we can profile that the map doesn't duplicate
        // camel keys as they are intern
        List<Map<?, ?>> maps = new ArrayList<>();

        for (int i = 0; i < 10000; i++) {
            Map<String, Object> copy = new CaseInsensitiveMap(map);
            assertEquals(3, copy.size());
            assertEquals("A", copy.get("CamelA"));
            assertEquals("B", copy.get("CamelB"));
            assertEquals("C", copy.get("CamelC"));

            maps.add(copy);
        }

        assertEquals(10000, maps.size());

        assertEquals(3, map.size());
        assertEquals("A", map.get("CamelA"));
        assertEquals("B", map.get("CamelB"));
        assertEquals("C", map.get("CamelC"));

        // use a memory profiler to see memory allocation
        // often you may want to give it time to run so you
        // have chance to capture memory snapshot in profiler
        Thread.sleep(9999999);
    }

}


text:
package edu.iastate.cs.design.spec.stackexchange.parse;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import edu.iastate.cs.design.spec.stackexchange.objects.BadgeCount;
import edu.iastate.cs.design.spec.stackexchange.objects.Post;
import edu.iastate.cs.design.spec.stackexchange.objects.ShallowUser;

/**
 This class abstracts away the library that parses our json objects from Stack Exchange. Uses gson for the moment.
 */
public class StackExchangeObjectParser {

    public static Post parsePostObject(String jsonObject) {
        return gsonParse(jsonObject, Post.class);
    }

    public static BadgeCount parseBadgeCountObject(String jsonObject) {
        return gsonParse(jsonObject, BadgeCount.class);
    }

    public static ShallowUser parseShallowUserObject(String jsonObject) {
        return gsonParse(jsonObject, ShallowUser.class);
    }

    private static <T> T gsonParse(String jsonObject, Class<T> objectType) {
        Gson parser = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
        return parser.fromJson(jsonObject, objectType);
    }
}


text:
This is Shayne's Boyers Kestrel Server (for serving static pages) with some Angular 2 code for consuming an API.

Instructions..

### ng2-kestrel-appserver

Updated for RC2
Get ASP.NET RC2 @ http://dot.net

####Static Web Server for Angular 2
Blog post here: http://www.tattoocoder.com/kestrel-as-a-static-server-for-angular/

Install the dotnet-cli & SDK from https://github.com/dotnet/cli#installers-and-binaries

```
* git clone git@github.com:spboyer/ng2-kestrel-appserver.git
* cd ng2-kestrel-appserver
* dotnet restore
* dotnet run
```

Option to run the app with `nodemon` to develop and auto refresh the .NET portions
```
* npm install
* npm start
```

This watches all `*.cs` files and will auto restart the application.  If you add any new
dependencies in the `project.json` file; a stop `dotnet restore` is required.


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

'-----------------------------------------------------------------------------------------------------------
' Defines a base class that is inherited by the writing classes that defines a bunch of utility
' functions for building up names of constructs. Basically anything that we want to shared between different
' output classes is defined here.
'-----------------------------------------------------------------------------------------------------------

Imports System.IO
Imports System.Text

' Utility functions for writing out the parse tree. Basically name generation and various simply utility functions
' that are shared by different writing classes. This is typically inherited by a writing class.
Public MustInherit Class WriteUtils
    Protected _parseTree As ParseTree  ' the tree to output

#If OLDSTYLE Then
    Protected Const NodeKindString = "NodeKind"
    Protected Const NodeListString = "NodeList"
    Protected Const SeparatedNodeListString = "SeparatedNodeList"
    Protected Const NodeFactoryListString = "NodeFactory"
#Else
    Protected Const NodeKindString = "SyntaxKind"
    Protected Const NodeListString = "SyntaxList"
    Protected Const SeparatedNodeListString = "SeparatedSyntaxList"
    Protected Const NodeFactoryListString = "Syntax"
#End If
    Public Sub New(parseTree As ParseTree)
        _parseTree = parseTree
    End Sub

    ' Name generation

    ' Get the base type name (no namespace) for a node structure.
    Protected Function StructureTypeName(nodeStructure As ParseNodeStructure) As String
        Return Ident(nodeStructure.Name)
    End Function

    ' Get the base type name (no namespace) for an enumeration.
    Protected Function EnumerationName(enumeration As ParseEnumeration) As String
        Return Ident(enumeration.Name)
    End Function

    'Get a factory name from a kind
    Protected Function FactoryName(nodeKind As ParseNodeKind) As String
        Return nodeKind.Name
    End Function

    'Get a factory name from a structure
    Protected Function FactoryName(nodeStructure As ParseNodeStructure) As String
#If OLDSTYLE Then
        Return nodeStructure.Name
#Else
        If nodeStructure.Name.EndsWith("Syntax", StringComparison.Ordinal) Then
            Return nodeStructure.Name.Substring(0, nodeStructure.Name.Length - 6)
        Else
            Return nodeStructure.Name
        End If
#End If
    End Function

    Protected Function SyntaxFactName(nodeStructure As ParseNodeStructure) As String
        Dim name = FactoryName(nodeStructure)
        If name = "Keyword" Then
            name = "KeywordKind"
        End If
        Return name
    End Function

    ' Get the name for a field private variable
    Protected Function FieldVarName(nodeField As ParseNodeField) As String
        Dim name As String = nodeField.Name
        Return "_" + LowerFirstCharacter(name)
    End Function

    ' Get the name for a child private variable
    Protected Function ChildVarName(nodeChild As ParseNodeChild) As String
        Dim name As String = nodeChild.Name
        Return "_" + LowerFirstCharacter(name)
    End Function

    ' Get the name for a child private variable cache (not in the builder, but in the actual node)
    Protected Function ChildCacheVarName(nodeChild As ParseNodeChild) As String
        Dim name As String = nodeChild.Name
        Return "_" + LowerFirstCharacter(name) + "Cache"
    End Function

    ' Get the name for a new child variable is the visitor
    Protected Function ChildNewVarName(nodeChild As ParseNodeChild) As String
        Dim name As String = nodeChild.Name
        Return Ident("new" + UpperFirstCharacter(name))
    End Function

#If False Then
    ' Get the name for a new child variable is the visitor, but for the separators
    Protected Function ChildNewVarSeparatorsName(ByVal nodeChild As ParseNodeChild) As String
        Dim name As String = ChildSeparatorsName(nodeChild)
        Return Ident(LowerFirstCharacter(name) + "New")
    End Function
#End If

    ' Get the name for a field parameter.
    ' If conflictName is not nothing, make sure the name doesn't conflict with that name.
    Protected Function FieldParamName(nodeField As ParseNodeField, Optional conflictName As String = Nothing) As String
        Dim name As String = nodeField.Name
        If String.Equals(name, conflictName, StringComparison.InvariantCultureIgnoreCase) Then
            name += "Parameter"
        End If
        Return Ident(LowerFirstCharacter(name))
    End Function

    ' Get the name for a child parameter
    ' If conflictName is not nothing, make sure the name doesn't conflict with that name.
    Protected Function ChildParamName(nodeChild As ParseNodeChild, Optional conflictName As String = Nothing) As String
        Dim name As String = OptionalChildName(nodeChild)
        If String.Equals(name, conflictName, StringComparison.InvariantCultureIgnoreCase) Then
            name += "Parameter"
        End If
        Return Ident(LowerFirstCharacter(name))
    End Function

#If False Then
    ' Get the name for a child separator list parameter
    Protected Function ChildSeparatorsParamName(ByVal nodeChild As ParseNodeChild) As String
        Return Ident(LowerFirstCharacter(ChildSeparatorsName(nodeChild)))
    End Function
#End If

    ' Get the name for a field property
    Protected Function FieldPropertyName(nodeField As ParseNodeField) As String
        Return Ident(UnescapedFieldPropertyName(nodeField))
    End Function

    Protected Function UnescapedFieldPropertyName(nodeField As ParseNodeField) As String
        Dim name As String = nodeField.Name
        Return UpperFirstCharacter(name)
    End Function

    ' Get the name for a child property
    Protected Function ChildWithFunctionName(nodeChild As ParseNodeChild) As String
        Return Ident("With" + UpperFirstCharacter(nodeChild.Name))
    End Function

    ' Get the name for a child property
    Protected Function ChildPropertyName(nodeChild As ParseNodeChild) As String
        Return Ident(UnescapedChildPropertyName(nodeChild))
    End Function

    Protected Function UnescapedChildPropertyName(nodeChild As ParseNodeChild) As String
        Return UpperFirstCharacter(OptionalChildName(nodeChild))
    End Function

    ' Get the name for a child separators property
    Protected Function ChildSeparatorsPropertyName(nodeChild As ParseNodeChild) As String
        Return Ident(UpperFirstCharacter(ChildSeparatorsName(nodeChild)))
    End Function

    ' If a child is optional and isn't a list, add "Optional" to the name.
    Protected Function OptionalChildName(nodeChild As ParseNodeChild) As String
        Dim name As String = nodeChild.Name
        If nodeChild.IsOptional AndAlso Not nodeChild.IsList Then
#If OLDSTYLE Then
            Return "Optional" + UpperFirstCharacter(name)
#Else
            Return UpperFirstCharacter(name)
#End If
        Else
            Return UpperFirstCharacter(name)
        End If
    End Function

    ' If a child is a separated list, return the name of the separators.
    Protected Function ChildSeparatorsName(nodeChild As ParseNodeChild) As String
        If nodeChild.IsList AndAlso nodeChild.IsSeparated Then
            If String.IsNullOrEmpty(nodeChild.SeparatorsName) Then
                _parseTree.ReportError(nodeChild.Element, "separator-name was not found, but is required for separated lists")
            End If
            Return UpperFirstCharacter(nodeChild.SeparatorsName)
        Else
            Throw New ApplicationException("Shouldn't get here")
        End If
    End Function

    ' Get the type reference for a field property
    Protected Function FieldTypeRef(nodeField As ParseNodeField) As String
        Dim fieldType As Object = nodeField.FieldType
        If TypeOf fieldType Is SimpleType Then
            Return SimpleTypeName(CType(fieldType, SimpleType))
        ElseIf TypeOf fieldType Is ParseEnumeration Then
            Return EnumerationTypeName(CType(fieldType, ParseEnumeration))
        End If

        nodeField.ParseTree.ReportError(nodeField.Element, "Bad type for field")
        Return "UNKNOWNTYPE"
    End Function

    ' Get the type reference for a child property
    Protected Function ChildPropertyTypeRef(nodeStructure As ParseNodeStructure, nodeChild As ParseNodeChild, Optional isGreen As Boolean = False, Optional denyOverride As Boolean = False) As String
        Dim isOverride = nodeChild.ContainingStructure IsNot nodeStructure AndAlso Not denyOverride

        Dim result As String
        If nodeChild.IsList Then
            If nodeChild.IsSeparated Then
                result = String.Format(If(isGreen, "SeparatedSyntaxList(Of {0})", "SeparatedSyntaxList(Of {0})"), BaseTypeReference(nodeChild))
            ElseIf KindTypeStructure(nodeChild.ChildKind).IsToken Then
                If isGreen Then
                    result = String.Format("SyntaxList(Of {0})", BaseTypeReference(nodeChild))
                Else
                    result = "SyntaxTokenList"
                End If

            Else
                result = String.Format("SyntaxList(Of {0})", BaseTypeReference(nodeChild))
            End If
        Else
            If Not isGreen AndAlso KindTypeStructure(nodeChild.ChildKind).IsToken Then
                Return String.Format("SyntaxToken")
            End If

            If Not isGreen AndAlso isOverride Then
                Dim childKindStructure As ParseNodeStructure = Nothing

                If nodeStructure.NodeKinds.Count = 1 Then
                    Dim childNodeKind = GetChildNodeKind(nodeStructure.NodeKinds(0), nodeChild)
                    childKindStructure = KindTypeStructure(childNodeKind)
                Else
                    Dim childKinds As New HashSet(Of ParseNodeKind)()

                    For Each kind In nodeStructure.NodeKinds
                        Dim childNodeKind = GetChildNodeKind(kind, nodeChild)
                        If childNodeKind IsNot Nothing Then
                            childKinds.Add(GetChildNodeKind(kind, nodeChild))
                        Else
                            childKinds = Nothing
                            Exit For
                        End If
                    Next

                    If childKinds IsNot Nothing Then
                        If childKinds.Count = 1 Then
                            childKindStructure = KindTypeStructure(childKinds.First)
                        Else
                            childKindStructure = GetCommonStructure(childKinds.ToList())
                        End If
                    End If
                End If

                If childKindStructure IsNot Nothing Then
                    Return childKindStructure.Name
                End If
            End If

            result = BaseTypeReference(nodeChild)
        End If

        If isGreen Then
            Return String.Format("InternalSyntax.{0}", result)
        End If

        Return result
    End Function

    Protected Function ChildFieldTypeRef(nodeChild As ParseNodeChild, Optional isGreen As Boolean = False) As String
        If nodeChild.IsList Then
            If nodeChild.IsSeparated Then
                Return String.Format(If(isGreen, "GreenNode", "SeparatedSyntaxList(Of {0})"), BaseTypeReference(nodeChild))
            Else
                Return String.Format(If(isGreen, "GreenNode", "SyntaxList(Of {0})"), BaseTypeReference(nodeChild))
            End If
        Else
            Return BaseTypeReference(nodeChild)
        End If
    End Function

    Protected Function ChildPrivateFieldTypeRef(nodeChild As ParseNodeChild) As String
        If nodeChild.IsList Then
            Return "SyntaxNode"
        Else
            Return BaseTypeReference(nodeChild)
        End If
    End Function

    ' Get the type reference for a child separators property
    Protected Function ChildSeparatorsTypeRef(nodeChild As ParseNodeChild) As String
        Return String.Format("SyntaxList(Of {0})", SeparatorsBaseTypeReference(nodeChild))
    End Function

    ' Get the type reference for a child constructor
    Protected Function ChildConstructorTypeRef(nodeChild As ParseNodeChild, Optional isGreen As Boolean = False) As String
        If nodeChild.IsList Then
            If isGreen OrElse KindTypeStructure(nodeChild.ChildKind).IsToken Then
                Return "GreenNode"
            Else
                Return "SyntaxNode"
            End If
        Else
            Dim name = BaseTypeReference(nodeChild)
            If KindTypeStructure(nodeChild.ChildKind).IsToken Then
                Return "InternalSyntax." + name
            End If
            Return name
        End If
    End Function

    ' Get the type reference for a child constructor
    Protected Function ChildFactoryTypeRef(nodeStructure As ParseNodeStructure, nodeChild As ParseNodeChild, Optional isGreen As Boolean = False, Optional internalForm As Boolean = False) As String
        If nodeChild.IsList Then
            If nodeChild.IsSeparated Then
                If isGreen Then
                    Return String.Format("InternalSyntax.SeparatedSyntaxList(of InternalSyntax.{0})", BaseTypeReference(nodeChild))
                Else
                    Return String.Format("SeparatedSyntaxList(Of {0})", BaseTypeReference(nodeChild))
                End If
            Else
                If isGreen Then
                    Return String.Format("InternalSyntax.SyntaxList(of InternalSyntax.{0})", StructureTypeName(_parseTree.RootStructure))
                Else
                    If KindTypeStructure(nodeChild.ChildKind).IsToken Then
                        Return String.Format("SyntaxTokenList")
                    Else
                        Return String.Format("SyntaxList(of {0})", BaseTypeReference(nodeChild))
                    End If
                End If

            End If
        Else
            If Not internalForm AndAlso KindTypeStructure(nodeChild.ChildKind).IsToken Then
                Return String.Format("SyntaxToken", BaseTypeReference(nodeChild))
            End If
            If Not isGreen Then
                Return ChildPropertyTypeRef(nodeStructure, nodeChild, isGreen)
            Else
                Return BaseTypeReference(nodeChild)
            End If
        End If
    End Function

#If False Then
    ' Get the type reference for a child separators constructor
    Protected Function ChildSeparatorConstructorTypeRef(ByVal nodeChild As ParseNodeChild) As String
        If nodeChild.IsList AndAlso nodeChild.IsSeparated Then
            Return String.Format("SeparatedNodeList(Of {0})", SeparatorsBaseTypeReference(nodeChild))
        Else
            Throw New ApplicationException("shouldn't get here")
        End If
    End Function
#End If

    ' Is this type reference a list structure kind?
    Protected Function IsListStructureType(nodeField As ParseNodeChild) As Boolean
        Return nodeField.IsList AndAlso (TypeOf nodeField.ChildKind Is ParseNodeKind OrElse TypeOf nodeField.ChildKind Is List(Of ParseNodeKind))
    End Function

    ' Is this type reference a non-list structure kind?
    Protected Function IsNodeStructureType(nodeField As ParseNodeChild) As Boolean
        Return Not nodeField.IsList AndAlso (TypeOf nodeField.ChildKind Is ParseNodeKind OrElse TypeOf nodeField.ChildKind Is List(Of ParseNodeKind))
    End Function

    ' Get the type reference for a child private variable, ignoring lists
    Protected Function BaseTypeReference(nodeChild As ParseNodeChild) As String
        Return KindTypeReference(nodeChild.ChildKind, nodeChild.Element)
    End Function

    ' Get the type reference for separators, ignoring lists
    Protected Function SeparatorsBaseTypeReference(nodeChild As ParseNodeChild) As String
        Return KindTypeReference(nodeChild.SeparatorsKind, nodeChild.Element)
    End Function

    ' Get the type reference for a kind
    Private Function KindTypeReference(kind As Object, element As XNode) As String
        If TypeOf kind Is ParseNodeKind Then
            Return StructureTypeName(CType(kind, ParseNodeKind).NodeStructure)
        ElseIf TypeOf kind Is List(Of ParseNodeKind) Then
            Dim commonStructure = GetCommonStructure(CType(kind, List(Of ParseNodeKind)))
            If commonStructure Is Nothing Then
                Return "Object"
            Else
                Return StructureTypeName(commonStructure)
            End If
        End If

        _parseTree.ReportError(element, "Invalid kind specified")
        Return "UNKNOWNTYPE"
    End Function

    ' Get the type reference for a kind
    Protected Function KindTypeStructure(kind As Object) As ParseNodeStructure
        If TypeOf kind Is ParseNodeKind Then
            Return CType(kind, ParseNodeKind).NodeStructure
        ElseIf TypeOf kind Is List(Of ParseNodeKind) Then
            Return GetCommonStructure(CType(kind, List(Of ParseNodeKind)))
        End If

        Return Nothing
    End Function

    ' Get the type name of a simple type
    Protected Function SimpleTypeName(simpleType As SimpleType) As String

        Select Case simpleType
            Case SimpleType.Bool
                Return "Boolean"
            Case SimpleType.Text
                Return "String"
            Case SimpleType.Character
                Return "Char"
            Case SimpleType.Int32
                Return "Integer"
            Case SimpleType.UInt32
                Return "UInteger"
            Case SimpleType.Int64
                Return "Long"
            Case SimpleType.UInt64
                Return "ULong"
            Case SimpleType.Float32
                Return "Single"
            Case SimpleType.Float64
                Return "Double"
            Case SimpleType.Decimal
                Return "System.Decimal"
            Case SimpleType.DateTime
                Return "DateTime"
            Case SimpleType.TextSpan
                Return "TextSpan"
            Case SimpleType.NodeKind
                Return NodeKindString
            Case Else
                Throw New ApplicationException("Unexpected simple type")
        End Select

    End Function

    ' Get the type name of an enumeration type
    Protected Function EnumerationTypeName(enumType As ParseEnumeration) As String
        Return Ident(enumType.Name)
    End Function

    ' The name of the node kind enumeration
    Protected Function NodeKindType() As String
        Return NodeKindString
    End Function

    ' The name of the visitor method for a structure type
    Protected Function VisitorMethodName(nodeStructure As ParseNodeStructure) As String
        Dim nodeName = nodeStructure.Name
        If nodeName.EndsWith("Syntax", StringComparison.Ordinal) Then nodeName = nodeName.Substring(0, nodeName.Length - 6)

        Return "Visit" + nodeName
    End Function

    ' Is this structure the root?
    Protected Function IsRoot(nodeStructure As ParseNodeStructure) As Boolean
        Return String.IsNullOrEmpty(nodeStructure.ParentStructureId)
    End Function

    ' Given a list of ParseNodeKinds, find the common structure that encapsulates all
    ' of them, or else return Nothing if there is no common structure.
    Protected Function GetCommonStructure(kindList As List(Of ParseNodeKind)) As ParseNodeStructure
        Dim structList = kindList.ConvertAll(Function(kind) kind.NodeStructure) ' list of the structures.

        ' Any candidate ancestor is an ancestor (or same) of the first element
        Dim candidate As ParseNodeStructure = structList(0)

        Do
            If IsAncestorOfAll(candidate, structList) Then
                Return candidate
            End If

            candidate = candidate.ParentStructure
        Loop While (candidate IsNot Nothing)

        Return Nothing ' no ancestor
    End Function

    ' Is this structure an ancestorOrSame of all
    Protected Function IsAncestorOfAll(parent As ParseNodeStructure, children As List(Of ParseNodeStructure)) As Boolean
        Return children.TrueForAll(Function(child) _parseTree.IsAncestorOrSame(parent, child))
    End Function

    ' Get all of the fields of a structure, including inherited fields, in the right order.
    ' TODO: need way to get the ordering right.
    Protected Function GetAllFieldsOfStructure(struct As ParseNodeStructure) As List(Of ParseNodeField)
        Dim fullList As New List(Of ParseNodeField)

        ' For now, just put inherited stuff at the beginning, until we design a real ordering solution
        Do While struct IsNot Nothing
            fullList.InsertRange(0, struct.Fields)
            struct = struct.ParentStructure
        Loop

        Return fullList
    End Function

    ' Get all of the children of a structure, including inherited children, in the right order.
    ' The ordering is defined first by order attribute, then by declared order (base before derived)
    Protected Function GetAllChildrenOfStructure(struct As ParseNodeStructure) As List(Of ParseNodeChild)
        Dim fullList As New List(Of Tuple(Of ParseNodeChild, Integer))

        ' For now, just put inherited stuff at the beginning, until we design a real ordering solution
        Dim baseLevel = 0  ' 0 for this structure, 1 for base, 2 for grandbase, ...

        Do While struct IsNot Nothing
            For i = 0 To struct.Children.Count - 1
                ' Add each child with an integer giving default sort order.
                fullList.Add(New Tuple(Of ParseNodeChild, Integer)(struct.Children(i), i - baseLevel * 100))
            Next
            struct = struct.ParentStructure
            baseLevel += 1
        Loop

        ' Return a new list in order.
        Return (From n In fullList Order By n.Item1.Order, n.Item2 Select n.Item1).ToList()
    End Function

    ' Get all of the children of a structure, including inherited children, in the right order.
    ' that can be passed to the factory method.
    ' The ordering is defined first by order attribute, then by declared order (base before derived)
    Protected Function GetAllFactoryChildrenOfStructure(struct As ParseNodeStructure) As IEnumerable(Of ParseNodeChild)
        Return From child In GetAllChildrenOfStructure(struct) Where Not child.NotInFactory Select child
    End Function

    ' String utility functions

    ' Lowercase the first character o a string
    Protected Function LowerFirstCharacter(s As String) As String
        If s Is Nothing OrElse s.Length = 0 Then
            Return s
        Else
            Return Char.ToLowerInvariant(s(0)) + s.Substring(1)
        End If
    End Function

    ' Uppercase the first character o a string
    Protected Function UpperFirstCharacter(s As String) As String
        If s Is Nothing OrElse s.Length = 0 Then
            Return s
        Else
            Return Char.ToUpperInvariant(s(0)) + s.Substring(1)
        End If
    End Function

    ' Word wrap a string into lines
    Protected Function WordWrap(text As String) As List(Of String)
        Const LineLength As Integer = 80
        Dim lines As New List(Of String)

        ' Remove newlines, consecutive spaces.
        text = text.Replace(vbCr, " ")
        text = text.Replace(vbLf, " ")
        Do
            Dim newText = text.Replace("  ", " ")
            If newText = text Then Exit Do
            text = newText
        Loop
        text = text.Trim()

        While text.Length >= LineLength
            Dim split As Integer = text.Substring(0, LineLength).LastIndexOf(" "c)
            If split < 0 Then split = LineLength

            Dim line As String = text.Substring(0, split).Trim()
            lines.Add(line)

            text = text.Substring(split).Trim()
        End While

        If text.Length > 0 Then
            lines.Add(text)
        End If

        Return lines
    End Function

    ' Create a description XML comment with the given tag, indented the given number of characters
    Private Sub GenerateXmlCommentPart(writer As TextWriter, text As String, xmlTag As String, indent As Integer)
        If String.IsNullOrWhiteSpace(text) Then Return

        text = XmlEscape(text)

        Dim lines = WordWrap(text)

        lines.Insert(0, "<" & xmlTag & ">")
        lines.Add("</" & xmlTag & ">")

        Dim prefix = New String(" "c, indent) & "''' "
        For Each line In lines
            writer.WriteLine(prefix & line)
        Next
    End Sub

    Protected Shared Function XmlEscape(value As String) As String
        Return value.Replace("&", "&").Replace("<", "<").Replace(">", ">")
    End Function

    Protected Shadows Function XmlEscapeAndWrap(value As String) As List(Of String)
        Return WordWrap(XmlEscape(value))
    End Function

    Public Sub GenerateSummaryXmlComment(writer As TextWriter, text As String, Optional indent As Integer = 8)
        GenerateXmlCommentPart(writer, text, "summary", indent)
    End Sub

    Public Sub GenerateParameterXmlComment(writer As TextWriter, parameterName As String, text As String, Optional escapeText As Boolean = False, Optional indent As Integer = 8)
        If String.IsNullOrWhiteSpace(text) Then Return

        If escapeText Then
            text = XmlEscape(text)
        Else
            ' Ensure the text does not require escaping.
            Dim filtered = text.Replace("<cref ", "").Replace("/>", "").Replace("&", "").Replace("<", "").Replace(">", "")
            Debug.Assert(filtered = XmlEscape(filtered))
        End If

        Dim prefix = New String(" "c, indent) & "''' "

        writer.WriteLine(prefix & "<param name=""{0}"">", parameterName)

        For Each line In WordWrap(text)
            writer.WriteLine(prefix & line)
        Next

        writer.WriteLine(prefix & "</param>")
    End Sub

    Public Sub GenerateTypeParameterXmlComment(writer As TextWriter, typeParameterName As String, text As String, Optional indent As Integer = 4)
        If String.IsNullOrWhiteSpace(text) Then Return

        text = XmlEscape(text)

        Dim prefix = New String(" "c, indent) & "''' "

        writer.WriteLine(prefix & "<typeparam name=""{0}"">", typeParameterName)

        For Each line In WordWrap(text)
            writer.WriteLine(prefix & line)
        Next

        writer.WriteLine(prefix & "</typeparam>")
    End Sub

    ' Generate and XML comment with the given description and remarks sections. If emtpy, the sections are ommitted.
    Protected Sub GenerateXmlComment(writer As TextWriter, descriptionText As String, remarksText As String, indent As Integer)
        GenerateXmlCommentPart(writer, descriptionText, "summary", indent)
        GenerateXmlCommentPart(writer, remarksText, "remarks", indent)
    End Sub

    ' Generate XML comment for a structure
    Protected Sub GenerateXmlComment(writer As TextWriter, struct As ParseNodeStructure, indent As Integer)
        Dim descriptionText As String = struct.Description
        Dim remarksText As String = Nothing
        GenerateXmlComment(writer, descriptionText, remarksText, indent)
    End Sub

    ' Generate XML comment for an child
    Protected Sub GenerateXmlComment(writer As TextWriter, child As ParseNodeChild, indent As Integer)
        Dim descriptionText As String = child.Description
        Dim remarksText As String = Nothing
        If child.IsOptional Then
            If child.IsList Then
                remarksText = "If nothing is present, an empty list is returned."
            Else
                remarksText = "This child is optional. If it is not present, then Nothing is returned."
            End If
        End If
        GenerateXmlComment(writer, descriptionText, remarksText, indent)
    End Sub

    ' Generate XML comment for an child
    Protected Sub GenerateWithXmlComment(writer As TextWriter, child As ParseNodeChild, indent As Integer)
        Dim descriptionText As String = "Returns a copy of this with the " + ChildPropertyName(child) + " property changed to the specified value. Returns this instance if the specified value is the same as the current value."
        Dim remarksText As String = Nothing
        GenerateXmlComment(writer, descriptionText, remarksText, indent)
    End Sub

    ' Generate XML comment for an field
    Protected Sub GenerateXmlComment(writer As TextWriter, field As ParseNodeField, indent As Integer)
        Dim descriptionText As String = field.Description
        Dim remarksText As String = Nothing
        GenerateXmlComment(writer, descriptionText, remarksText, indent)
    End Sub

    ' Generate XML comment for an kind
    Protected Sub GenerateXmlComment(writer As TextWriter, kind As ParseNodeKind, indent As Integer)
        Dim descriptionText As String = kind.Description
        Dim remarksText As String = Nothing
        GenerateXmlComment(writer, descriptionText, remarksText, indent)
    End Sub

    ' Generate XML comment for an enumeration
    Protected Sub GenerateXmlComment(writer As TextWriter, enumerator As ParseEnumeration, indent As Integer)
        Dim descriptionText As String = enumerator.Description
        Dim remarksText As String = Nothing
        GenerateXmlComment(writer, descriptionText, remarksText, indent)
    End Sub

    ' Generate XML comment for an enumerator
    Protected Sub GenerateXmlComment(writer As TextWriter, enumerator As ParseEnumerator, indent As Integer)
        Dim descriptionText As String = enumerator.Description
        Dim remarksText As String = Nothing
        GenerateXmlComment(writer, descriptionText, remarksText, indent)
    End Sub

    Private ReadOnly _VBKeywords As String() = {
        "ADDHANDLER",
        "ADDRESSOF",
        "ALIAS",
        "AND",
        "ANDALSO",
        "AS",
        "BOOLEAN",
        "BYREF",
        "BYTE",
        "BYVAL",
        "CALL",
        "CASE",
        "CATCH",
        "CBOOL",
        "CBYTE",
        "CCHAR",
        "CDATE",
        "CDBL",
        "CDEC",
        "CHAR",
        "CINT",
        "CLASS",
        "CLNG",
        "COBJ",
        "CONST",
        "CONTINUE",
        "CSBYTE",
        "CSHORT",
        "CSNG",
        "CSTR",
        "CTYPE",
        "CUINT",
        "CULNG",
        "CUSHORT",
        "DATE",
        "DECIMAL",
        "DECLARE",
        "DEFAULT",
        "DELEGATE",
        "DIM",
        "DIRECTCAST",
        "DO",
        "DOUBLE",
        "EACH",
        "ELSE",
        "ELSEIF",
        "END",
        "ENDIF",
        "ENUM",
        "ERASE",
        "ERROR",
        "EVENT",
        "EXIT",
        "FALSE",
        "FINALLY",
        "FOR",
        "FRIEND",
        "FUNCTION",
        "GET",
        "GETTYPE",
        "GETXMLNAMESPACE",
        "GLOBAL",
        "GOSUB",
        "GOTO",
        "HANDLES",
        "IF",
        "IMPLEMENTS",
        "IMPORTS",
        "IN",
        "INHERITS",
        "INTEGER",
        "INTERFACE",
        "IS",
        "ISNOT",
        "LET",
        "LIB",
        "LIKE",
        "LONG",
        "LOOP",
        "ME",
        "MOD",
        "MODULE",
        "MUSTINHERIT",
        "MUSTOVERRIDE",
        "MYBASE",
        "MYCLASS",
        "NAMESPACE",
        "NARROWING",
        "NEW",
        "NEXT",
        "NOT",
        "NOTHING",
        "NOTINHERITABLE",
        "NOTOVERRIDABLE",
        "OBJECT",
        "OF",
        "ON",
        "OPERATOR",
        "OPTION",
        "OPTIONAL",
        "OR",
        "ORELSE",
        "OVERLOADS",
        "OVERRIDABLE",
        "OVERRIDES",
        "PARAMARRAY",
        "PARTIAL",
        "PRIVATE",
        "PROPERTY",
        "PROTECTED",
        "PUBLIC",
        "RAISEEVENT",
        "READONLY",
        "REDIM",
        "REM",
        "REMOVEHANDLER",
        "RESUME",
        "RETURN",
        "SBYTE",
        "SELECT",
        "SET",
        "SHADOWS",
        "SHARED",
        "SHORT",
        "SINGLE",
        "STATIC",
        "STEP",
        "STOP",
        "STRING",
        "STRUCTURE",
        "SUB",
        "SYNCLOCK",
        "THEN",
        "THROW",
        "TO",
        "TRUE",
        "TRY",
        "TRYCAST",
        "TYPEOF",
        "UINTEGER",
        "ULONG",
        "USHORT",
        "USING",
        "VARIANT",
        "WEND",
        "WHEN",
        "WHILE",
        "WIDENING",
        "WITH",
        "WITHEVENTS",
        "WRITEONLY",
        "XOR"}

    ' If the string is a keyword, escape it. Otherwise just return it.
    Protected Function Ident(id As String) As String
        If _VBKeywords.Contains(id.ToUpperInvariant()) Then
            Return "[" + id + "]"
        Else
            Return id
        End If
    End Function

    Public Function EscapeQuotes(s As String) As String
        If s.IndexOf(""""c) <> -1 Then
            Dim sb As New StringBuilder
            Dim parts = s.Split(""""c)
            Dim last = parts.Length - 1
            For i = 0 To last - 1
                sb.Append(parts(i))
                sb.Append("""""")
            Next
            sb.Append(parts(last))
            s = sb.ToString
        End If
        Return s
    End Function

    Public Function GetChildNodeKind(nodeKind As ParseNodeKind, child As ParseNodeChild) As ParseNodeKind
        Dim childNodeKind = TryCast(child.ChildKind, ParseNodeKind)
        Dim childNodeKinds = TryCast(child.ChildKind, List(Of ParseNodeKind))

        If childNodeKinds IsNot Nothing AndAlso nodeKind IsNot Nothing Then
            childNodeKind = child.ChildKind(nodeKind.Name)
        End If

        If childNodeKind Is Nothing AndAlso child.DefaultChildKind IsNot Nothing Then
            childNodeKind = child.DefaultChildKind
        End If

        Return childNodeKind
    End Function

    Public Function IsAutoCreatableToken(node As ParseNodeStructure, nodeKind As ParseNodeKind, child As ParseNodeChild) As Boolean
        Dim childNodeKind = GetChildNodeKind(nodeKind, child)

        If childNodeKind IsNot Nothing Then
            Dim childNodeStructure = KindTypeStructure(childNodeKind)
            If childNodeStructure.IsToken AndAlso childNodeKind.Name <> "IdentifierToken" Then
                Return True
            End If
        End If

        Return False
    End Function

    Public Function IsAutoCreatableNodeOfAutoCreatableTokens(node As ParseNodeStructure, nodeKind As ParseNodeKind, child As ParseNodeChild) As Boolean
        Dim childNodeKind = GetChildNodeKind(nodeKind, child)

        ' Node contains only auto-creatable tokens
        If childNodeKind IsNot Nothing Then
            Dim childNodeStructure = KindTypeStructure(childNodeKind)
            If Not childNodeStructure.IsToken Then
                Dim allChildren = GetAllChildrenOfStructure(childNodeStructure)
                For Each childNodeChild In allChildren
                    If Not IsAutoCreatableToken(childNodeStructure, childNodeKind, childNodeChild) Then
                        Return False
                    End If
                Next

                Return True
            End If
        End If

        Return False
    End Function

    Public Function IsAutoCreatableChild(node As ParseNodeStructure, nodeKind As ParseNodeKind, child As ParseNodeChild) As Boolean
        Return IsAutoCreatableToken(node, nodeKind, child) OrElse IsAutoCreatableNodeOfAutoCreatableTokens(node, nodeKind, child)
    End Function

End Class


text:
package io.servicefabric.socketio.pipeline;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.CharsetUtil;
import org.junit.Before;
import org.junit.Test;

import static io.netty.util.ReferenceCountUtil.releaseLater;
import static org.junit.Assert.*;

public class FlashPolicyHandlerTest {

    private FlashPolicyHandler flashPolicyHandler;

    private final String policyResponse = "<?xml version=\"1.0\"?>"
            + "<!DOCTYPE cross-domain-policy SYSTEM \"/xml/dtds/cross-domain-policy.dtd\">" + "<cross-domain-policy> "
            + "   <site-control permitted-cross-domain-policies=\"master-only\"/>" + "   <allow-access-from domain=\"*\" to-ports=\"*\" />"
            + "</cross-domain-policy>";

    private final ByteBuf policyRequestBuffer = Unpooled.copiedBuffer("<policy-file-request/>", CharsetUtil.UTF_8);

    @Before
    public void init() throws Exception{
        flashPolicyHandler = new FlashPolicyHandler();
    }

    @Test
    public void testFlashPolicy() throws Exception {
        LastOutboundHandler lastOutboundHandler = new LastOutboundHandler();
        EmbeddedChannel channel = new EmbeddedChannel(lastOutboundHandler,flashPolicyHandler);
        channel.writeInbound(policyRequestBuffer);
        ByteBuf byteBuf = (ByteBuf) lastOutboundHandler.getOutboundMessages().poll();
        assertEquals(policyResponse, releaseLater(byteBuf).toString(CharsetUtil.UTF_8));
        assertTrue(lastOutboundHandler.getOutboundMessages().isEmpty());
        channel.finish();
    }

    @Test
    public void testNonFlashPolicy() throws Exception {
        LastOutboundHandler lastOutboundHandler = new LastOutboundHandler();
        EmbeddedChannel channel = new EmbeddedChannel(lastOutboundHandler,flashPolicyHandler);
        String message = "{ \"friends\": [" +
                "            {" +
                "                \"id\": 0," +
                "                \"name\": \"Vargas Cochran\"" +
                "            }," +
                "            {" +
                "                \"id\": 1," +
                "                \"name\": \"Gould Marsh\"" +
                "            }," +
                "            {" +
                "                \"id\": 2," +
                "                \"name\": \"Vaughn Contreras\"" +
                "            }" +
                "        ]," +
                "        \"greeting\": \"Hello, Kinney Warren! You have 5 unread messages.\"," +
                "        \"favoriteFruit\": \"banana\"}";
        channel.writeInbound(Unpooled.copiedBuffer(message, CharsetUtil.UTF_8));
        ByteBuf byteBuf = (ByteBuf) channel.readInbound();
        assertEquals(message, releaseLater(byteBuf).toString(CharsetUtil.UTF_8));
        channel.finish();
    }

}


text:
                    {{ range .Site.Menus.main }}

                        {{ .Name }}

                    {{end}}


text:
using UnityEngine;
using System.Collections;

public class MainMenu : MonoBehaviour
{
	public Texture2D backgroundTexture;
	public GUISkin mySkin = null;

	void OnGUI()
	{
		//Displays the menu background
		GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), backgroundTexture);
		//Creates skin object
		GUI.skin = mySkin;

		//Simple navigation menu buttons
		if (GUI.Button (new Rect(Screen.width * 0.1f, Screen.height * 0.6f, Screen.width * 0.8f, Screen.height * 0.1f), "Play Game"))
		{
			print ("Clicked Play Game");
			//Loads the scene called "introduction"
			Application.LoadLevel("Introduction");
		}
		if (GUI.Button (new Rect(Screen.width * 0.1f, Screen.height * 0.7f, Screen.width * 0.8f, Screen.height * 0.1f), "Level Select"))
		{
			print ("Clicked Level Select");
			Application.LoadLevel("Level Select");
		}
		if (GUI.Button (new Rect(Screen.width * 0.1f, Screen.height * 0.8f, Screen.width * 0.8f, Screen.height * 0.1f), "Quit"))
		{
			print ("Clicked Quit");
			Application.Quit();
		}
	}
}


text:
package com.iluwatar.memento;

/**
 *
 * External interface to memento.
 *
 */
public interface StarMemento {

}


text:
require "./fast-html-template.rb"
tmpl = HTML::Template.new("./ifnest.html")
tmpl.param({'one' => { 'hoge' => 'ほげほげ', 'two' => {'hoge' => 'complete'}}})
print "Content-Type: text/html\n\n"
print tmpl.output

#---------------------------------------------------
#Copyright (C) 2005 Community Engine Inc. All rights reserved.
#Author : ede
#---------------------------------------------------


text:
package net.ruippeixotog.scalascraper

import java.io.PrintStream

import com.typesafe.config.ConfigFactory
import net.ruippeixotog.scalascraper.ExampleMatchers._
import net.ruippeixotog.scalascraper.browser.Browser
import net.ruippeixotog.scalascraper.dsl.DSL.Extract._
import net.ruippeixotog.scalascraper.dsl.DSL._
import net.ruippeixotog.scalascraper.util.ProxyUtils
import net.ruippeixotog.scalascraper.util.Validated._
import org.jsoup.nodes.Element

import scala.collection.immutable.SortedMap

object ExampleMatchers {
  val succ = validatorAt("success-matcher")
  val errs = validatorsAt[Int]("error-matchers")
}

object ProxyApp extends App {
  ProxyUtils.setProxy("localhost", 3128)
  val browser = Browser()
  val doc = browser.get("http://observador.pt")

  println("=== OBSERVADOR HTTP & HTTPS PROXY ===")

  Thread.sleep(2000)

  ProxyUtils.removeProxy()

  // You should get a [java.net.SocketTimeoutException: connect timed out] if you are behind a proxy
  browser.get("http://observador.pt")
}

object NewsApp extends App {
  val browser = new Browser
  val doc = browser.get("http://observador.pt")

  println()
  println("=== OBSERVADOR ===")

  doc >> extractor(".logo img", attr("src")) |> println
  doc >> extractorAt[String]("example-extractor") |> println

  println("==================")
  println()

  doc >> ".small-news-list h4 > a" foreach println
}

object HeadlineApp extends App {
  val browser = new Browser

  browser.get("http://observador.pt") ~/~ (succ, errs) >> "h1" match {
    case VSuccess(headline) => println("HEADLINE: " + headline.head)
    case VFailure(status) => println("Error: " + status)
  }
}

object HeadlineBetterApp extends App {
  val browser = new Browser

  for {
    headline <- browser.get("http://observador.pt") ~/~ (succ, errs) >> element("h1 a")
    headlineDesc = browser.get(headline.attr("href")) >> text(".lead")
  } println("== " + headline.text + " ==\n" + headlineDesc)
}

object HeadlineVerboseApp extends App {
  val conf = ConfigFactory.load

  val browser = new Browser

  for {
    headline <- browser.get("http://observador.pt") validateWith (succ, errs) extract element("h1 a")
    headlineDesc = browser.get(headline.attr("href")) extract text(".lead")
  } println("== " + headline.text + " ==\n" + headlineDesc)
}

object MusicGenreTreeApp extends App {
  val browser = new Browser

  case class GenreNode(root: Element) {
    def leaves = root >> elements("> a.genre") map { e => e.text -> e }
    def nodes = root >> elementList("> div:has(b:has(a.genre))") >> (text(".genre"), element("blockquote"))

    def children: Map[String, GenreNode] = SortedMap(leaves ++ nodes: _*).mapValues(GenreNode.apply)

    def renderYaml(d: Int = 0): String =
      children.map {
        case (k, v) if v.children.isEmpty => s"${" " * d}- $k\n"
        case (k, v) => s"${" " * d}- $k:\n${v.renderYaml(d + 2)}"
      }.mkString
  }

  val page = browser.get("http://rateyourmusic.com/rgenre/")
  val out = new PrintStream("genres.yaml")
  GenreNode(page >> element("#content")).renderYaml() |> out.println
}


text:
FIFA 2014 World Cup Players by Place of Birth
========

[Interactive map](http://cdb.io/1kU9I2I)

![screenshot](https://raw.githubusercontent.com/josecarlosgonz/worldcup/master/fifa.png)


text:
from setuptools import setup

setup(
    name='snakecharmer',
    version='1.0.1',
    description="A collection of utilities for working with python",
    long_description=open('README.md').read(),
    author='HubSpot Dev Team',
    author_email='devteam+hapi@hubspot.com',
    url='https://github.com/HubSpot/snakecharmer',
    download_url='https://github.com/HubSpot/snakecharmer/tarball/v1.0.0',
    license='LICENSE.txt',
    packages=['snakecharmer'],
    install_requires=[
        'nose==1.1.2',
        'unittest2==0.5.1',
    ],
)


text:
Authors
=======

* Dirk Moors - www.ditchitall.be
* Jim Cortez - jimcortez.com
* Marek Kuziel - kuziel.info


text:
package com.liu.coolweather.location;

import android.content.Context;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.liu.coolweather.LzcApplication;
import com.liu.coolweather.MainActivity;
import com.liu.coolweather.tool.LogTool;
import com.liu.coolweather.tool.SharedTool;
import com.liu.coolweather.tool.ToastTool;

/**
 * Created by LIUZICHENG on 2016/12/17.
 */

public class LzcLocatOption implements BDLocationListener {
    private LocationClient mLocationClient;

    private BackDataListener backDataListener = null;

    public BackDataListener getBackDataListener() {
        return backDataListener;
    }

    public void setBackDataListener(BackDataListener backDataListener) {
        this.backDataListener = backDataListener;
    }

    public interface BackDataListener{
        void success();
        void fail();
    }

    public LzcLocatOption( ){
        mLocationClient = new LocationClient(LzcApplication.getContext());
        mLocationClient.registerLocationListener(this);
    }

    public void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
//        int span=1000;
        option.setScanSpan(0);//可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选,设置是否需要地址信息,默认不需要
        option.setOpenGps(true);//可选,默认false,设置是否使用gps
//        option.setLocationNotify(false);//可选,默认false,设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于"在北京天安门附近"
        option.setIsNeedLocationPoiList(true);//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死
//        option.SetIgnoreCacheException(false);//可选,默认false,设置是否收集CRASH信息,默认收集
//        option.setEnableSimulateGps(false);//可选,默认false,设置是否需要过滤GPS仿真结果,默认需要
        mLocationClient.setLocOption(option);
    }

    public void start(){
        if (mLocationClient != null){
            mLocationClient.start();
        }
    }
    public void stop(){
        if (mLocationClient != null){
            mLocationClient.stop();
        }
    }

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        switch (bdLocation.getLocType()){
            case BDLocation.TypeGpsLocation:// gps定位成功
                bx(bdLocation);
                break;
            case BDLocation.TypeNetWorkLocation://网络定位成功
                bx(bdLocation);
                break;
            default:
                ToastTool.Makter(LzcApplication.getContext(),"Error:"+bdLocation.getLocType());
                if (backDataListener != null){
                    backDataListener.fail();
                }
                break;
        }
    }
    private void bx(BDLocation bdLocation){
//        LogTool.i("定位成功:"+bdLocation.getCity()+"\n经纬度"+bdLocation.getLongitude()+","+bdLocation.getLatitude());
        if (bdLocation.getCity().isEmpty()){
            SharedTool.saveString("city",bdLocation.getCity());
            if (backDataListener != null){
                backDataListener.success();
            }
        }

    }
}


text:
from __future__ import absolute_import
from celery.backends.database import retry
from django.db import OperationalError

__author__ = 'marlon'

import requests
import feedparser as fp

from celery import task
from celery.utils.log import get_task_logger

from Crawler.models import LinksRSS, Postagens, Tags, TagsPostagens, Imagens

from lxml.html.clean import Cleaner

from django.core.files.images import ImageFile

logger = get_task_logger(__name__)

@task(name='tasks.do_crawler')
def do_crawler():
    logger.info("Coletando postagens")
    try:
        sites = LinksRSS.objects.all()
        cleaner = Cleaner(allow_tags=[''], remove_unknown_tags=False)
        for site in sites:
            try:
                coleta = fp.parse(site.link_rss)
                if "entries" in coleta:
                    for col in coleta.entries:
                        s = requests.get(col.link)
                        if s.status_code == 200 or s.status_code == 301:
                            link = s.url
                            texto = cleaner.clean_html(col["summary"])
                            valores = {
                                "titulo": col["title"],
                                "texto": texto,
                                "fk_site": site.fk_sites
                            }
                            if "img" in col:
                                if "src" in col.img:
                                    image_content = ImageFile(requests.get(col.img.src).content)
                                    imga = Imagens(img_cover=image_content, img_link_orig=col.img.src)
                                    imga.save()
                                    valores["fk_imagem"] = imga
                                elif "url" in col.img:
                                    image_content = ImageFile(requests.get(col.img.url).content)
                                    imga = Imagens(img_cover=image_content, img_link_orig=col.img.url)
                                    imga.save()
                                    valores["fk_imagem"] = imga
                                elif "href" in col.img:
                                    image_content = ImageFile(requests.get(col.img.href).content)
                                    imga = Imagens(img_cover=image_content, img_link_orig=col.img.href)
                                    imga.save()
                                    valores["fk_imagem"] = imga
                                elif "link" in col.img:
                                    image_content = ImageFile(requests.get(col.img.link).content)
                                    imga = Imagens(img_cover=image_content, img_link_orig=col.img.link)
                                    imga.save()
                                    valores["fk_imagem"] = imga
                            elif "media_thumbnail" in col:
                                image_content = ImageFile(requests.get(col.media_thumbnail[0].url).content)
                                imga = Imagens(img_cover=image_content, img_link_orig=col.img.src)
                                imga.save()
                                valores["fk_imagem"] = imga
                            elif "links" in col:
                                for li in col.links:
                                    if "type" in li:
                                        if li.type.find("image") != -1:
                                            image_content = ImageFile(requests.get(li.href).content)
                                            imga = Imagens(img_cover=image_content, img_link_orig=col.img.src)
                                            imga.save()
                                            valores["fk_imagem"] = imga

                            post, existe = Postagens.objects.get_or_create(link=link, defaults=valores)
                            if not existe:
                                if "tags" in col:
                                    for tag in col["tags"]:
                                        try:
                                            db_tag = Tags.objects.get(tag=tag["term"].lower())
                                            db_tag.contador += 1
                                            db_tag.save()
                                        except Tags.DoesNotExist:
                                            db_tag = Tags(tag=tag["term"].lower())
                                            db_tag.save()
                                        try:
                                            tpos = TagsPostagens.objects.get(fk_tag=db_tag, fk_postagem=post)
                                        except TagsPostagens.DoesNotExist:
                                            tpos = TagsPostagens(fk_tag=db_tag, fk_postagem=post)
                                            tpos.save()
                else:
                    logger.info("A consulta não retornou resultados")
            except Exception:
                logger.info("Erro na coleta da página: {0}".format(site.link_rss))

    except Exception as exce:
        logger.info("Erro: ")

    logger.info("Coleta Concluida")


text:
/**
 * Created by epotignano on 18/03/16.
 */

exports.configuration = {
    host: '',
    user: '',
    password: '',
    database: '',
    debug: false,
    insecureAuth: false
}


text:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>

<!-- Put site-specific property overrides in this file. -->

<configuration>
	<property>
		<name>dfs.replication</name>
		<value>1</value>
	</property>
	<property>
		<name>dfs.name.dir</name>
		<value>/home/gaoshen/dfs/name/</value>
	</property>
	<property>
		<name>dfs.data.dir</name>
		<value>/home/gaoshen/dfs/data/</value>
	</property>
</configuration>


text:
/**
  @file         task_worker_observer_base.cpp
  @brief        notifies events in hryky::task::worker::Base.
  @author       HRYKY
  @version      $Id: task_worker_observer_base.cpp 368 2014-07-14 21:21:42Z hryky.private@gmail.com $
 */
#include "precompiled.h"
#include "hryky/task/task_worker_observer_base.h"
//------------------------------------------------------------------------------
// macro
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// anonymous namespace
//------------------------------------------------------------------------------
namespace hryky
{
namespace task
{
namespace worker
{
namespace observer
{
namespace
{
} // namespace "anonymous"
} // namespace observer
} // namespace worker
} // namespace task
} // namespace hryky
//------------------------------------------------------------------------------
// static variable
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// function prototype
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// defines public member functions
//------------------------------------------------------------------------------
/**
  @brief default constructor.
 */
hryky::task::worker::observer::Base::Base()
	: intrusive_ptr_trait()
{
}
/**
  @brief instantiates with memory pool.
 */
hryky::task::worker::observer::Base::Base(mempool::Ptr const & mempool)
	: intrusive_ptr_trait(mempool)
{
}
/**
  @brief copy constructor.
 */
hryky::task::worker::observer::Base::Base(this_type const & rhs)
	: intrusive_ptr_trait(rhs)
{
}
/**
  @brief move constructor.
 */
hryky::task::worker::observer::Base::Base(this_type && rhs)
	: intrusive_ptr_trait(::std::move(rhs))
{
}
/**
  @brief destructor.
 */
hryky::task::worker::observer::Base::~Base()
{
}
/**
  @brief releases the internal resources.
 */
void hryky::task::worker::observer::Base::clear()
{
	this->intrusive_ptr_trait::clear();
}
/**
  @brief interchanges the each internal resources of two instances.
 */
void hryky::task::worker::observer::Base::swap(this_type &)
{
}
/**
  @brief callback function called just before the worker is attached.
 */
void hryky::task::worker::observer::Base::on_attach(worker_type & worker) {
	this->on_attach_impl(worker);
}
/**
  @brief callback function called just before the worker is detached.
 */
void hryky::task::worker::observer::Base::on_detach(worker_type & worker) {
	this->on_detach_impl(worker);
}
/**
  @brief callback function called just after some error occurs.
 */
void hryky::task::worker::observer::Base::on_error(worker_type & param) {
	this->on_error_impl(param);
}
//------------------------------------------------------------------------------
// defines protected member functions
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// defines private member functions
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// defines global functions
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// static functions
//------------------------------------------------------------------------------
namespace hryky
{
namespace task
{
namespace worker
{
namespace observer
{
namespace
{
} // namespace "anonymous"
} // namespace observer
} // namespace worker
} // namespace task
} // namespace hryky
//------------------------------------------------------------------------------
// explicit instantiation
//------------------------------------------------------------------------------
// end of file


text:
/**
 * Главный контроллер приложения
 *
 * @message system.page.beforeUnload
 * @message system.page.postBeforeUnload
 */
croc.Class.define('croc.controllers.Initialize', {
    extend: croc.Controller,
    members: {
        /**
         * Инициализация контроллера
         */
        initFinish: function() {
            if (croc.isClient) {
                this.__setUpUnloading();

                $('.js-construct').each(function() {
                    var el = $(this);
                    var plugin = el.data('plugin');
                    if (plugin) {
                        var pluginConf = el.data('pluginConf');
                        var plugins = (Array.isArray(plugin) ? plugin : [plugin]).map(function(name, index) {
                            var Plugin = croc.Class.getClass(name);
                            var conf = pluginConf && (Array.isArray(pluginConf) ? pluginConf[index] : pluginConf);
                            return new Plugin(conf ? _.assign({el: el}, conf) : {el: el});
                        }, this);
                        el.data('$$plugins', plugins);
                    }
                });

                if (croc.isDebug) {
                    $(document.body).click(function(e) {
                        var widget = $(e.target).closest('.js-widget');
                        if (widget.length) {
                            window.$widget = croc.cmp.Widget.getByElement(widget);
                        }
                    });
                }
            }
        },

        /**
         * @private
         */
        __setUpUnloading: function() {
            this._getDisposer().addListener($(window), 'beforeunload', function() {
                var preventUnloadText;
                var preventUnload = function(text) {
                    preventUnloadText = text;
                };
                croc.publish('system.page.beforeUnload', preventUnload);
                if (preventUnloadText) {
                    return preventUnloadText;
                }
                else {
                    croc.publish('system.page.postBeforeUnload');
                }
            });
        }
    }
});


text:
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
package org.openqa.selenium.edgehtml;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.internal.Require;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.service.DriverCommandExecutor;

/**
 * A {@link WebDriver} implementation that controls an Edge browser running on the local machine.
 * This class is provided as a convenience for easily testing the Edge browser. The control server
 * which each instance communicates with will live and die with the instance.
 *
 * To avoid unnecessarily restarting the Microsoft WebDriver server with each instance, use a
 * {@link RemoteWebDriver} coupled with the desired {@link EdgeHtmlDriverService}, which is managed
 * separately. For example: <pre>{@code
 *
 * import org.junit.jupiter.api.*;
 * import org.openqa.selenium.By;
 * import org.openqa.selenium.WebDriver;
 * import org.openqa.selenium.WebDriverException;
 * import org.openqa.selenium.WebElement;
 * import org.openqa.selenium.edgehtml.EdgeHtmlDriverService;
 * import org.openqa.selenium.edgehtml.EdgeHtmlOptions;
 * import org.openqa.selenium.remote.RemoteWebDriver;
 * import org.openqa.selenium.remote.service.DriverService;
 *
 * import java.io.IOException;
 * import java.util.ServiceLoader;
 * import java.util.stream.StreamSupport;
 *
 * import static org.junit.jupiter.api.Assertions.assertEquals;
 *
 * public class EdgeHtmlTest {
 *
 *     private static EdgeHtmlDriverService service;
 *     private WebDriver driver;
 *
 *     {@Literal @BeforeAll}
 *     public static void createAndStartService() {
 *         EdgeHtmlDriverService.Builder builder = new EdgeHtmlDriverService.Builder();
 *         service = builder.build();
 *         try {
 *             service.start();
 *         }
 *         catch (IOException e) {
 *             throw new RuntimeException(e);
 *         }
 *     }
 *
 *     {@Literal @AfterAll}
 *     public static void createAndStopService() {
 *         service.stop();
 *     }
 *
 *     {@Literal @BeforeEach}
 *     public void createDriver() {
 *         driver = new RemoteWebDriver(service.getUrl(),
 *                 new EdgeHtmlOptions());
 *     }
 *
 *     {@Literal @AfterEach}
 *     public void quitDriver() {
 *         driver.quit();
 *     }
 *
 *     {@Literal @Test}
 *     public void testBingSearch() {
 *         driver.get("http://www.bing.com");
 *         WebElement searchBox = driver.findElement(By.name("q"));
 *         searchBox.sendKeys("webdriver");
 *         searchBox.submit();
 *         assertEquals("webdriver - Bing", driver.getTitle());
 *     }
 * }}</pre>
 */
public class EdgeHtmlDriver extends RemoteWebDriver {

  public EdgeHtmlDriver() { this(new EdgeHtmlOptions()); }

  public EdgeHtmlDriver(EdgeHtmlOptions options) {
    this(new EdgeHtmlDriverService.Builder().build(), options);
  }

  public EdgeHtmlDriver(EdgeHtmlDriverService service) {
    this(service, new EdgeHtmlOptions());
  }

  public EdgeHtmlDriver(EdgeHtmlDriverService service, EdgeHtmlOptions options) {
    super(new DriverCommandExecutor(service), Require.nonNull("Driver options", options));
  }
}


text:
$:.unshift File.expand_path("../lib", File.dirname(__FILE__))
require 'test/unit'
require 'test_declarative'
require 'i18n'
require 'i18n/tests'
require 'mocha/test_unit'
require 'turn/autorun'

class Test::Unit::TestCase
  def self.test(name, &block)
    test_name = "test_#{name.gsub(/\s+/,'_')}".to_sym
    defined = instance_method(test_name) rescue false
    raise "#{test_name} is already defined in #{self}" if defined
    if block_given?
      define_method(test_name, &block)
    else
      define_method(test_name) do
        flunk "No implementation provided for #{name}"
      end
    end
  end

  def self.with_mocha
    yield if Object.respond_to?(:expects)
  end

  def teardown
    I18n.locale = nil
    I18n.default_locale = :en
    I18n.load_path = []
    I18n.available_locales = nil
    I18n.backend = nil
  end

  def translations
    I18n.backend.instance_variable_get(:@translations)
  end

  def store_translations(*args)
    data   = args.pop
    locale = args.pop || :en
    I18n.backend.store_translations(locale, data)
  end

  def locales_dir
    File.dirname(__FILE__) + '/test_data/locales'
  end
end

Object.class_eval do
  def meta_class
    class << self; self; end
  end
end unless Object.method_defined?(:meta_class)


text:
---
uid: SolidEdgeAssembly.Occurrence.NodeType
summary:
remarks:
---


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

#ifndef IOS_CHROME_COMMON_UI_UTIL_IMAGE_UTIL_H_
#define IOS_CHROME_COMMON_UI_UTIL_IMAGE_UTIL_H_

#import <UIKit/UIKit.h>

/**
 Scale down the image if it's too large so it doesn't take too much space
 to store or too much data to upload.
 This is taken from Google Toolbox for Mac. Extensions should not have
 too many dependencies, so this is reproduced here. This should not be used
 outside of extensions. Instead, use the simpler version in
 //ui/gfx/image/image_util.h.
 */
UIImage* ResizeImageForSearchByImage(UIImage* image);

// Returns an image generated from the given |view|, using |backgroundColor| and
// adding |padding| around the centered image.
UIImage* ImageFromView(UIView* view,
                       UIColor* backgroundColor,
                       UIEdgeInsets padding);

#endif  // IOS_CHROME_COMMON_UI_UTIL_IMAGE_UTIL_H_