text:
/* used for test case 533, 534 and 535 */

#include "test.h"

#include <fcntl.h>

#include "testutil.h"
#include "warnless.h"
#include "memdebug.h"

#define TEST_HANG_TIMEOUT 60 * 1000

int test(char *URL)
{
  int res = 0;
  CURL *curl = NULL;
  int running;
  CURLM *m = NULL;
  int current = 0;

  start_test_timing();

  global_init(CURL_GLOBAL_ALL);

  easy_init(curl);

  easy_setopt(curl, CURLOPT_URL, URL);
  easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  easy_setopt(curl, CURLOPT_FAILONERROR, 1L);

  multi_init(m);

  multi_add_handle(m, curl);

  fprintf(stderr, "Start at URL 0\n");

  for(;;) {
    struct timeval interval;
    fd_set rd, wr, exc;
    int maxfd = -99;

    interval.tv_sec = 1;
    interval.tv_usec = 0;

    multi_perform(m, &running);

    abort_on_test_timeout();

    if(!running) {
      if(!current++) {
        fprintf(stderr, "Advancing to URL 1\n");
        /* remove the handle we use */
        curl_multi_remove_handle(m, curl);

        /* make us re-use the same handle all the time, and try resetting
           the handle first too */
        curl_easy_reset(curl);
        easy_setopt(curl, CURLOPT_URL, libtest_arg2);
        easy_setopt(curl, CURLOPT_VERBOSE, 1L);
        easy_setopt(curl, CURLOPT_FAILONERROR, 1L);

        /* re-add it */
        multi_add_handle(m, curl);
      }
      else
        break; /* done */
    }

    FD_ZERO(&rd);
    FD_ZERO(&wr);
    FD_ZERO(&exc);

    multi_fdset(m, &rd, &wr, &exc, &maxfd);

    /* At this point, maxfd is guaranteed to be greater or equal than -1. */

    select_test(maxfd + 1, &rd, &wr, &exc, &interval);

    abort_on_test_timeout();
  }

test_cleanup:

  /* undocumented cleanup sequence - type UB */

  curl_easy_cleanup(curl);
  curl_multi_cleanup(m);
  curl_global_cleanup();

  return res;
}


text:
layout: post
title:  The Open Kitchen
cover: /images/the-open-kitchen/portraitcover.jpg
order: 4

---

![Close-Up One](/images/the-open-kitchen/lou-illustration.jpg)

Renting and sharing behaviours are experiencing a revival amongst a younger, more mobile generation. Users are adopting more flexible and sustainable alternatives to the current ownership model of consumption. I set myself the task to design a product-service-system that would make the renting of infrequent use kitchen utensils more convenient and accessible.
The Open Kitchen is a utensil library for anybody who is passionate about cooking, or want to learn a new skill without having to deal with the burden of a cluttered kitchen.
As a product outcome that would express the values of the service in a tangible way, I decided to create a pasta-making utensil set. A product that is not intended for individual ownership but shared usage has to be able to withstand heavy wear and tear, be hygienic, easily cleanable but also maintain a premium and professional feel. I conducted extensive research to find the right materials that would fit these requirements.

Illustration by Lou Rihn

![Pouch](/images/the-open-kitchen/pouch.jpg)
![Set](/images/the-open-kitchen/open-set.jpg)
![Rolling Pin](/images/the-open-kitchen/rolling-pin.jpg)
![Rolling Pin](/images/the-open-kitchen/rolling-pin-2.jpg)
![Utensils](/images/the-open-kitchen/utensils.jpg)
![Handle](/images/the-open-kitchen/handle.jpg)
![Context](/images/the-open-kitchen/overview.jpg)

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.IO;
#if GDI
using System.Drawing;
using System.Drawing.Drawing2D;
#endif
#if WPF
using System.Windows.Media;
#endif
using PdfSharp.Internal;

namespace PdfSharp.Drawing
{
  /// <summary>
  /// Classes derived from this abstract base class define objects used to fill the
  /// interiors of paths.
  /// </summary>
  public abstract class XBrush
  {
#if GDI
    internal abstract System.Drawing. Brush RealizeGdiBrush();

#if UseGdiObjects
    /// <summary>
    /// Converts from a System.Drawing.Brush.
    /// </summary>
    public static implicit operator XBrush(Brush brush)
    {
      XBrush xbrush;
      SolidBrush solidBrush;
      LinearGradientBrush lgBrush;
      if ((solidBrush = brush as SolidBrush) != null)
      {
        xbrush = new XSolidBrush(solidBrush.Color);
      }
      else if ((lgBrush = brush as LinearGradientBrush) != null)
      {
        // TODO: xbrush = new LinearGradientBrush(lgBrush.Rectangle, lgBrush.co(solidBrush.Color);
        throw new NotImplementedException("Brush type not yet supported by PDFsharp.");
      }
      else
      {
        throw new NotImplementedException("Brush type not supported by PDFsharp.");
      }
      return xbrush;
    }
#endif
#endif
#if WPF
    internal abstract System.Windows.Media. Brush RealizeWpfBrush();
#endif
  }
}


text:
package org.apache.camel.component.nagios;

import com.googlecode.jsendnsca.NonBlockingNagiosPassiveCheckSender;

import org.apache.camel.Producer;
import org.apache.camel.builder.RouteBuilder;
import org.junit.BeforeClass;
import org.mockito.Mockito;

/**
 * @version
 */
public class NagiosAsyncSendTest extends NagiosTest {

    @BeforeClass
    public static void setSender() {
        nagiosPassiveCheckSender =  Mockito.mock(NonBlockingNagiosPassiveCheckSender.class);
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                String uri = "nagios:127.0.0.1:25664?password=secret&sendSync=false";

                NagiosComponent nagiosComponent = new NagiosComponent();
                nagiosComponent.setCamelContext(context);
                NagiosEndpoint nagiousEndpoint = (NagiosEndpoint) nagiosComponent.createEndpoint(uri);
                nagiousEndpoint.setSender(nagiosPassiveCheckSender);
                Producer nagiosProducer = nagiousEndpoint.createProducer();

                from("direct:start")
                        .to(nagiousEndpoint)
                        .to("mock:result");
            }
        };
    }

}


text:
include(CMakeParseArguments) # cmake_parse_arguments

include(hunter_user_error)

# internal variables: _hunter_c_*
macro(hunter_cmake_args)
  set(_hunter_c_multiple_values CMAKE_ARGS)
  cmake_parse_arguments(
      _hunter_c
      ""
      ""
      "${_hunter_c_multiple_values}"
      ${ARGV}
  )
  list(LENGTH _hunter_c_UNPARSED_ARGUMENTS _hunter_c_len)
  if(NOT ${_hunter_c_len} EQUAL 1)
    hunter_user_error("unparsed: ${_hunter_c_UNPARSED_ARGUMENTS}")
  endif()

  list(GET _hunter_c_UNPARSED_ARGUMENTS 0 _hunter_c_current_project)

  if(NOT _hunter_c_CMAKE_ARGS)
    hunter_user_error("Expected CMAKE_ARGS")
  endif()

  set(
      "HUNTER_${_hunter_c_current_project}_DEFAULT_CMAKE_ARGS"
      ${_hunter_c_CMAKE_ARGS}
  )
endmacro()


text:
<!doctype html>

    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title>Rich J. Lee - </title>
    <meta name="description" content="" />
    <meta name="Author" content="Ken M. Lai(networktsukkomime.me)" />

    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,700,800|Dosis:300,400" rel="stylesheet" type="text/css" />

    <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">

    <link href="http://richjlee.com/theme/css/reset.css" rel="stylesheet" type="text/css" />
    <link href="http://richjlee.com/theme/css/framework.css" rel="stylesheet" type="text/css" />
    <link href="http://richjlee.com/theme/css/typography.css" rel="stylesheet" type="text/css" />
    <link href="http://richjlee.com/theme/css/layout.css" rel="stylesheet" type="text/css" />

    <link href="http://richjlee.com/theme/css/blog.css" rel="stylesheet" type="text/css" />

        <link rel="shortcut icon" href="https://dl.dropboxusercontent.com/s/2u6se8hh4yik45t/logo.png" type="image/x-icon" />
        <link rel="icon" href="https://dl.dropboxusercontent.com/s/2u6se8hh4yik45t/logo.png" type="image/x-icon" />
        <link rel="shortcut icon" href="https://dl.dropboxusercontent.com/s/2u6se8hh4yik45t/logo.png" type="image/x-icon" />

    <meta name="viewport" content="width=device-width, maximum-scale=1, initial-scale=1, user-scalable=0" />

      <button id="mobileMenu" class="fa fa-bars" type="button" data-toggle="collapse" data-target=".navbar-collapse"></button>

          Rich J. Lee

Home

About

Work

Blog

              Links

GitHub

LinkedIn

NFL Combine Data Pt. 2

           misc
           ?? Comments
          31/Mar/2016 Thu

Another quick look at combine data...

While physical attributes alone are not strong predictors of NFL success,
they play a significant role in the drafting process. Combine tests provide a
standardized way for teams to compare prospects. Each test measures a specific
football-related athletic trait; the 40 yard dash is ...

         READ MORE

NFL Combine Data Pt. 1

           misc
           ?? Comments
          14/Mar/2016 Mon

Just a very quick look at NFL combine data (1999-2014) with the draft coming up.
The first figure plots median 40 yard dash times by draft round for each
position. The positive relationship is clearly evident, particularly for
tight ends, wide receivers, cornerbacks, defensive ends, and outside
linebackers (Pearson's ...

         READ MORE

Pelican Static Site Generator

           misc
           ?? Comments
          06/Mar/2016 Sun

Welcome! This web page was created using Pelican,
a static site generator. Why a static site with Pelican?

-Flexible open-source and Python-based platform

-Supports Markdown for content creation

-Allows for easy, inexpensive hosting (I'm using Amazon S3, but GitHub pages
is a good free option)

-Improved performance and security ...

         READ MORE

← Previous

→ Next

Categories

 misc

Archives

                None
                None
                None

                        2016

                                03

                                            31/Mar/2016 ThuNFL Combine Data Pt. 2

                                            14/Mar/2016 MonNFL Combine Data Pt. 1

                                            06/Mar/2016 SunPelican Static Site Generator

            Rich J. Lee

2015 © All Rights Reserved.


text:
// System Objects
// ...

// Third Party Dependencies
// ...

// Internal
var commands = require('./commands');
var Tessel = require('./tessel');

/*
 Reboots Tessel
 */
Tessel.prototype.reboot = function() {
  var p1 = this.simpleExec(commands.reboot());

  // Using --lan will resolve the Promise but --usb will not. If more than 2 seconds, just resolve timeout i.e. "fire and forget"
  var p2 = new Promise((resolve) => {
    return setTimeout(resolve, 2000);
  });

  return Promise.race([p1, p2]);
};


text:
import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {Game} from './game';
import {GameService} from './game.service';

@Component({
    selector: 'game-list',
    templateUrl: './game.list.component.html'
})
export class GameListComponent implements OnInit {

    games: Game[];
    mediaCount: number;

    constructor(private gameService: GameService,
                private router: Router) {
    }

    ngOnInit(): void {
        this.updateData();
    }

    update(game: Game): void {
        this.router.navigate(['/games/edit', game.id]);
    }

    duplicate(game: Game): void {
        this.gameService.duplicate(game).then(response => this.updateData());
    }

    remove(game: Game): void {
        this.gameService.remove(game).then(response => this.updateData());
    }

    moveUp(game: Game): void {
        this.gameService.moveUp(game).then(response => this.updateData());
    }

    moveDown(game: Game): void {
        this.gameService.moveDown(game).then(response => this.updateData());
    }

    private updateData(): void {
        this.gameService.list().then(games => this.games = games);
        this.gameService.totalMedia().then(mediaCount => this.mediaCount = mediaCount);
    }

}


text:
Pattern: Use of blacklisted _URL_ scheme

Issue: -

## Description

A [URL scheme](https://url.spec.whatwg.org/#syntax-url-scheme) consists of alphanumeric, `+`, `-`, and `.` characters. It can appear at the start of a URL and is followed by `:`.

This rule treats URL schemes as case insensitive (`https` and `HTTPS` are the same).

This rule ignores URL arguments without an existing URL scheme.

This rule ignores URL arguments with variables or variable interpolation (`$sass`, `@less`, `--custom-property`, `#{$var}`, `@{var}`, `$(var)`).

## Examples

`array|string|regex`: `["array", "of", "schemes" or "regex"]|"scheme"|/regex/`

Given:

```js
["ftp", "/^http/"]
```

The following patterns are considered violations:

```css
a { background-image: url('ftp://www.example.com/file.jpg'); }
```

```css
a { background-image: url('http://www.example.com/file.jpg'); }
```

```css
a { background-image: url('https://www.example.com/file.jpg'); }
```

The following patterns are *not* considered violations:

```css
a { background-image: url('data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs='); }
```

```css
a { background-image: url('example.com/file.jpg'); }
```

```css
a { background-image: url('/example.com/file.jpg'); }
```

```css
a { background-image: url('//example.com/file.jpg'); }
```

```css
a { background-image: url('./path/to/file.jpg'); }
```

## Further Reading

* [stylelint - function-url-scheme-blacklist](https://stylelint.io/user-guide/rules/function-url-scheme-blacklist)


text:
package com.rgi.common.util.functional;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import org.junit.Test;

@SuppressWarnings({"javadoc", "static-method"})
public class ThrowingSupplierTest
{
    @Test(expected = RuntimeException.class)
    public void testGetThrowsException()
    {
        final ThrowingSupplier<String> ts = () -> { throw new NullPointerException(); };

        ts.get();
        fail("Expected ThrowingSupplier method throws to throw at RuntimeException");
    }

    @Test
    public void testGet()
    {
        final ThrowingSupplier<String> ts = () -> "Hello, world!";
        final String result = "Hello, world!";
        assertTrue("Expected ThrowingSupplier method throws to return the string 'Hello, world.'", result.equals(ts.get()));
    }
}


text:
from model.group import Group

def test_add_group(app, db, json_groups, check_ui):
    group = json_groups
    old_groups = db.get_group_list()
    app.group.create(group)
    new_groups = db.get_group_list()
    #assert len(old_groups) + 1 == app.group.count()#len(new_groups)
    old_groups.append(group)
    if check_ui:
        assert sorted(new_groups, key=Group.id_or_max) == sorted(app.group.get_group_list(), key=Group.id_or_max)


text:
module Cardano.Wallet.API.V1.Headers
    ( applicationJson
    ) where

import           Pos.Util.Servant (applicationJson)


text:
package org.elasticsearch.spark.integration;

import java.sql.Timestamp
import java.util.concurrent.TimeUnit
import scala.collection.JavaConversions.propertiesAsScalaMap
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.sql.IntegerType
import org.apache.spark.sql.Row
import org.apache.spark.sql.SQLContext
import org.apache.spark.sql.StringType
import org.apache.spark.sql.StructField
import org.apache.spark.sql.StructType
import org.apache.spark.sql.TimestampType
import org.elasticsearch.hadoop.mr.RestUtils
import org.elasticsearch.hadoop.util.TestSettings
import org.elasticsearch.hadoop.util.TestUtils
import org.elasticsearch.spark._
import org.elasticsearch.spark.rdd.EsSpark
import org.elasticsearch.spark.sql._
import org.elasticsearch.spark.sql.sqlContextFunctions
import org.hamcrest.Matchers.containsString
import org.hamcrest.Matchers.is
import org.hamcrest.Matchers.not
import org.junit.AfterClass
import org.junit.Assert._
import org.junit.Assume._
import org.junit.BeforeClass
import org.junit.FixMethodOrder
import org.junit.runners.MethodSorters
import org.elasticsearch.hadoop.cfg.ConfigurationOptions._
import org.junit.Test
import javax.xml.bind.DatatypeConverter
import org.apache.spark.sql.catalyst.expressions.GenericRow
import java.util.Arrays
import java.nio.file.Path
import java.io.File
import org.apache.commons.io.FileUtils
import org.apache.hadoop.mapred.JobContext

case class KeyValue(key: Int, value: String)

object AbstractScalaEsScalaSparkSQL {
  @transient val conf = new SparkConf().setAll(TestSettings.TESTING_PROPS).setMaster("local").setAppName("estest");
  @transient var cfg: SparkConf = null
  @transient var sc: SparkContext = null
  @transient var sqc: SQLContext = null

  @BeforeClass
  def setup() {
    sc = new SparkContext(conf)
    sqc = new SQLContext(sc)
  }

  @AfterClass
  def cleanup() {
    if (sc != null) {
      sc.stop
      // give jetty time to clean its act up
      Thread.sleep(TimeUnit.SECONDS.toMillis(3))
    }
  }
}

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class AbstractScalaEsScalaSparkSQL extends Serializable {

	val sc = AbstractScalaEsScalaSparkSQL.sc
	val sqc = AbstractScalaEsScalaSparkSQL.sqc

    @Test
    def testBasicRead() {
        val schemaRDD = artistsAsSchemaRDD
        assertTrue(schemaRDD.count > 300)
        schemaRDD.registerTempTable("datfile")
        println(schemaRDD.schemaString)
        //schemaRDD.take(5).foreach(println)
        val results = sqc.sql("SELECT name FROM datfile WHERE id >=1 AND id <=10")
        //results.take(5).foreach(println)
    }

    @Test
    def testEsSchemaRDD1Write() {
      val schemaRDD = artistsAsSchemaRDD

      val target = "sparksql-test/scala-basic-write"
      schemaRDD.saveToEs(target)
      assertTrue(RestUtils.exists(target))
      assertThat(RestUtils.get(target + "/_search?"), containsString("345"))
    }

    @Test
    def testEsSchemaRDD1WriteWithMapping() {
      val schemaRDD = artistsAsSchemaRDD

      val target = "sparksql-test/scala-basic-write-id-mapping"
      schemaRDD.saveToEs(target, Map(ES_MAPPING_ID -> "id", ES_MAPPING_EXCLUDE -> "url"))
      assertTrue(RestUtils.exists(target))
      assertThat(RestUtils.get(target + "/_search?"), containsString("345"))
      assertThat(RestUtils.exists(target + "/1"), is(true))
      assertThat(RestUtils.get(target + "/_search?"), not(containsString("url")))
    }

    //@Test
    def testEsSchemaRDDWarning() {
      val schemaRDD = artistsAsSchemaRDD

      val target = "sparksql-test/scala-basic-write-id-mapping"
      EsSpark.saveToEs(schemaRDD, target)
    }

    @Test
    def testEsSchemaRDD2Read() {
      val target = "sparksql-test/scala-basic-write"

      val schemaRDD = sqc.esRDD(target)
      assertTrue(schemaRDD.count > 300)
      val schema = schemaRDD.schemaString
      assertTrue(schema.contains("id: long"))
      assertTrue(schema.contains("name: string"))
      assertTrue(schema.contains("pictures: string"))
      assertTrue(schema.contains("time: long"))
      assertTrue(schema.contains("url: string"))

      //schemaRDD.take(5).foreach(println)

      schemaRDD.registerTempTable("basicRead")
      val nameRDD = sqc.sql("SELECT name FROM basicRead WHERE id >= 1 AND id <=10")
      nameRDD.take(7).foreach(println)
      assertEquals(10, nameRDD.count)
    }

    @Test
    def testEsSchemaRDD3WriteWithRichMapping() {
      val input = TestUtils.sampleArtistsDat()
      val data = sc.textFile(input)

      val schema = StructType(Seq(StructField("id", IntegerType, false),
        StructField("name", StringType, false),
        StructField("url", StringType, true),
        StructField("pictures", StringType, true),
        StructField("time", TimestampType, true),
        StructField("nested",
            StructType(Seq(StructField("id", IntegerType, false),
		        StructField("name", StringType, false),
		        StructField("url", StringType, true),
		        StructField("pictures", StringType, true),
		        StructField("time", TimestampType, true))), true)))

      val rowRDD = data.map(_.split("\t")).map(r => Row(r(0).toInt, r(1), r(2), r(3), new Timestamp(DatatypeConverter.parseDateTime(r(4)).getTimeInMillis()),
    		  											Row(r(0).toInt, r(1), r(2), r(3), new Timestamp(DatatypeConverter.parseDateTime(r(4)).getTimeInMillis()))))
      val schemaRDD = sqc.applySchema(rowRDD, schema)

      val target = "sparksql-test/scala-basic-write-rich-mapping-id-mapping"
      schemaRDD.saveToEs(target, Map(ES_MAPPING_ID -> "id"))
      assertTrue(RestUtils.exists(target))
      assertThat(RestUtils.get(target + "/_search?"), containsString("345"))
      assertThat(RestUtils.exists(target + "/1"), is(true))
    }

    @Test
    def testEsSchemaRDD4ReadRichMapping() {
      val target = "sparksql-test/scala-basic-write-rich-mapping-id-mapping"

      val schemaRDD = sqc.esRDD(target)

      assertTrue(schemaRDD.count > 300)
      println(schemaRDD.schemaString)
    }

    private def artistsAsSchemaRDD = {
      val input = TestUtils.sampleArtistsDat()
      val data = sc.textFile(input)

      val schema = StructType(Seq(StructField("id", IntegerType, false),
        StructField("name", StringType, false),
        StructField("url", StringType, true),
        StructField("pictures", StringType, true),
        StructField("time", TimestampType, true)))

      val rowRDD = data.map(_.split("\t")).map(r => Row(r(0).toInt, r(1), r(2), r(3), new Timestamp(DatatypeConverter.parseDateTime(r(4)).getTimeInMillis())))
      val schemaRDD = sqc.applySchema(rowRDD, schema)
      schemaRDD
    }

    private def artistsAsBasicSchemaRDD = {
      val input = TestUtils.sampleArtistsDat()
      val data = sc.textFile(input)

      val schema = StructType(Seq(StructField("id", IntegerType, false),
        StructField("name", StringType, false),
        StructField("url", StringType, true),
        StructField("pictures", StringType, true)))

      val rowRDD = data.map(_.split("\t")).map(r => Row(r(0).toInt, r(1), r(2), r(3)))
      val schemaRDD = sqc.applySchema(rowRDD, schema)
      schemaRDD
    }

    @Test
    def testEsSchemaRDD50ReadAsDataSource() {
      val target = "sparksql-test/scala-basic-write"
      val schemaRDD = sqc.sql("CREATE TEMPORARY TABLE sqlbasicread " +
              "USING org.elasticsearch.spark.sql " +
              "OPTIONS (resource '" + target + "')");

      val allRDD = sqc.sql("SELECT * FROM sqlbasicread WHERE id >= 1 AND id <=10")
      println(allRDD.schemaString)

      val nameRDD = sqc.sql("SELECT name FROM sqlbasicread WHERE id >= 1 AND id <=10")

      println(nameRDD.schemaString)
      assertEquals(10, nameRDD.count)
      nameRDD.take(7).foreach(println)
    }

    @Test
    def testEsSchemaFromDocsWithDifferentProperties() {
      val target = "spark-test/scala-sql-varcols"

      val trip1 = Map("reason" -> "business", "airport" -> "SFO")
      val trip2 = Map("participants" -> 5, "airport" -> "OTP")

      sc.makeRDD(Seq(trip1, trip2)).saveToEs(target)

      val schemaRDD = sqc.sql("CREATE TEMPORARY TABLE sqlvarcol " +
              "USING org.elasticsearch.spark.sql " +
              "OPTIONS (resource '" + target + "')");

      val allResults = sqc.sql("SELECT * FROM sqlvarcol")
      assertEquals(2, allResults.count())
      println(allResults.schemaString)

      val filter = sqc.sql("SELECT * FROM sqlvarcol WHERE airport = 'OTP'")
      assertEquals(1, filter.count())

      val nullColumns = sqc.sql("SELECT reason, airport FROM sqlvarcol ORDER BY airport")
      val rows = nullColumns.take(2)
      assertEquals("[null,OTP]", rows(0).toString())
      assertEquals("[business,SFO]", rows(1).toString())
    }

    @Test
    def testJsonLoadAndSavedToEs() {
      val input = sqc.jsonFile(this.getClass.getResource("/simple.json").toURI().toString())
      input.printSchema
      println(input.schema)
      input.saveToEs("spark-test/json-file")

      val basic = sqc.jsonFile(this.getClass.getResource("/basic.json").toURI().toString())
      basic.printSchema
      println(basic.schema)
      basic.saveToEs("spark-test/json-file")

    }

    @Test
    def testKeyValueParquetFile() {
      // Parquet is compiled against Hadoop 2 so check whether that's the case or not
      assumeTrue(classOf[JobContext].isInterface())

      //val items = 128
      //val rdd = sc.parallelize(1 to items).flatMap(i => Seq.fill(items)(KeyValue(i, i.toString)))

      val outputParquet = "bin/keyvaluerdd.parquet"
      FileUtils.deleteDirectory(new File(outputParquet))

      // running into https://issues.apache.org/jira/browse/SPARK-5281
      //sqc.createSchemaRDD(rdd).saveAsParquetFile(outputParquet)
      val schemaRDD = artistsAsBasicSchemaRDD
      schemaRDD.saveAsParquetFile(outputParquet)

      sqc.parquetFile(outputParquet).registerTempTable("testparquet")
      val select = sqc.sql("SELECT * FROM testparquet")
      println(select.schema)
      select.saveToEs("test/parquet")
    }

    //@Test
    // insert not supported
    def testEsSchemaRDD51WriteAsDataSource() {
      val target = "sparksql-test/scala-basic-write"
      val schemaRDD = sqc.sql("CREATE TEMPORARY TABLE sqlbasicwrite " +
              "USING org.elasticsearch.spark.sql " +
              "OPTIONS (resource '" + target + "')");

      val insertRDD = sqc.sql("INSERT INTO sqlbasicwrite SELECT 123456789, 'test-sql', 'http://test-sql.com', '', 12345")

      println(insertRDD.schemaString)
      assertTrue(insertRDD.count == 1)
      insertRDD.take(7).foreach(println)
    }
}


text:
*cluster-worker* component instances are the basic building blocks of [Onedata](https://github.com/onedata/onedata) services (including Oneprovider and Onezone), which enable Onedata services to easily scale on large number of nodes on a single cluster. Each *cluster-worker* can be configured for different tasks depending on the current needs (data access, metadata management, etc.) by [cluster-manager](https://github.com/onedata/cluster-manager) component.

*cluster-workers* are implemented in Erlang, and provide the following functionality:
 * internal request load balancing between cluster nodes
 * unified data store in local memory and [mnesia](http://erlang.org/doc/man/mnesia.html) distributed database
 * automatic scaling of Onedata services to multiple cluster nodes

# Usage

This component of Onedata is not to be used separately, but only as a dependency of a specific Onedata service (e.g. Oneprovider or Onezone) and configured for specific operation.

It should be included as rebar dependency in final application. Its behaviour may be configured via plug-ings provided by final application (see API). However, for testing and debugging purposes, it can be started as a standalone application with default plug-ins 2 ways:
 - Inside Erlang Virtual Machine using command "application:start(cluster_worker)". It requires only compiled code available to the Erlang Virtual Machine,
 - From shell using script "cluster_worker" with argument "console" or "start". To generate start script, release of application must be created.

To prepare cluster_worker to be started:
 - Use command "make submodules" to initialize submodules
 - Use command "./make.py" to generate release,
 - Use "./make.py compile" to compile code only (faster than building release).

# APIs
Cluster-worker behaviour is influenced by the following plug-ins that should be included in the final application:

 * *datastore_config_plugin* - module that provides datastore_config_behaviour to indicate which modules should be used by datastore,
 * *dns_worker_plugin* - module that provides dns_worker_plugin_default. It allows manipulation of build-in dns server,
 * *logger_plugin* - module that provides logger_plugin_behaviour. It allows manipulation of logger behaviour,
 * *node_manager_plugin* - module that provides ode_manager_plugin_behaviour. It allows configuration of modules (entities that provide functionality of application) and listeners.

Default implementation of plug-ins is in *src/plugins* directory.

# cluster-worker in Onedata

Two basic elements of Onedata - [op-worker](https://github.com/onedata/op-worker) and [oz-worker](https://github.com/onedata/oz-worker) base on cluster-worker.


text:
package de.vanmar.android.hoebapp.service;

public class TechnicalException extends Exception {

	private static final long serialVersionUID = 1119080653454935673L;

	TechnicalException() {
		super();
	}

	public TechnicalException(Exception cause) {
		super(cause);
	}

	public TechnicalException(String message) {
		super(message);
	}
}


text:
import type { ITextProps } from '../../primitives';
import type { CustomProps } from '../../../components/types/utils';
import type { IBoxProps, IStackProps } from '../../primitives';
import type { InterfaceBoxProps } from '../../../components/primitives/Box';

export interface InterfaceFormControlProps
  extends InterfaceBoxProps<IFormControlProps> {
  /**
   * If provided, this prop is passed to its children.
   */
  nativeID?: string;
  /**
   * If true, this prop is passed to its children.
   */
  isInvalid?: boolean;
  /**
   * If true, this prop is passed to its children.
   */
  isRequired?: boolean;
  /**
   * If true, this prop is passed to its children.
   */
  isDisabled?: boolean;
  /**
   * If true, this prop is passed to its children.
   */
  isReadOnly?: boolean;
}

export interface IFormControlLabelProps extends IFormControlProps {
  /**
   * Passed props will be applied on disabled state.
   */
  _disabled?: Partial<IBoxProps<IFormControlLabelProps>>;
  // _focus?: any;
  /**
   * Passed props will be applied on invalid state.
   */
  _invalid?: Partial<IBoxProps<IFormControlLabelProps>>;
  /**
   * Reflects the value of the 'for' content property.
   */
  htmlFor?: string;
  /**
   * Props applied to astrick text
   */
  _astrick?: Partial<ITextProps>;
}
export interface IFormControlErrorMessageProps extends IFormControlProps {
  /**
   * Passed props will be applied on disabled state.
   */
  _disabled?: Partial<IBoxProps<IFormControlLabelProps>>;
  /**
   * The right icon element to use in the FormControl.ErrorMessage.
   */
  rightIcon?: JSX.Element | Array<JSX.Element>;
  /**
   * The left icon element to use in the FormControl.ErrorMessage.
   */
  leftIcon?: JSX.Element | Array<JSX.Element>;
  /**
   * The start icon element to use in the FormControl.ErrorMessage.
   */
  startIcon?: JSX.Element | Array<JSX.Element>;
  /**
   * The end icon element to use in the FormControl.ErrorMessage.
   */
  endIcon?: JSX.Element | Array<JSX.Element>;
  /**
   * Props to be passed to the HStack used inside of FormControl.ErrorMessage.
   */
  _stack?: Partial<IStackProps>;
}
export interface IFormControlHelperTextProps extends IFormControlProps {
  /**
   * Passed props will be applied on disabled state.
   */
  _disabled?: Partial<IBoxProps<IFormControlLabelProps>>;
  // _focus?: any;
  /**
   * Passed props will be applied on invalid state.
   */
  _invalid?: Partial<IBoxProps<IFormControlLabelProps>>;
}

export type FormControlComponentType = ((
  props: IFormControlProps
) => JSX.Element) & {
  Label: React.MemoExoticComponent<
    (props: IFormControlLabelProps) => JSX.Element
  >;
  ErrorMessage: React.MemoExoticComponent<
    (props: IFormControlErrorMessageProps) => JSX.Element
  >;
  HelperText: React.MemoExoticComponent<
    (props: IFormControlHelperTextProps) => JSX.Element
  >;
};

export type IFormControlProps = InterfaceFormControlProps &
  CustomProps<'FormControl'>;


text: xiao meng meng de gou wo


text:
/**
 * Outreach module:
 * Progressive revelation of embedded components in household form
 */

(function() {

    /**
     * Function to display/hide embedded household components
     *
     * @param status: whether to show (true) or hide (false) the components
     */
    $.showHouseholdComponents = function(status) {

        var toggle_rows = ['#po_household_sub_defaultcontact__row',
                           '#po_household_sub_defaultcontact__row1',
                           '#po_household_sub_household_social_language__row',
                           '#po_household_sub_household_social_language__row1',
                           '#po_household_sub_household_social_community__row',
                           '#po_household_sub_household_social_community__row1',
                           '#po_household_sub_household_dwelling_dwelling_type__row',
                           '#po_household_sub_household_dwelling_dwelling_type__row1',
                           '#po_household_sub_household_dwelling_type_of_use__row',
                           '#po_household_sub_household_dwelling_type_of_use__row1',
                           '#po_household_sub_household_dwelling_repair_status__row',
                           '#po_household_sub_household_dwelling_repair_status__row1'
                           ];

        var rows = toggle_rows.join(',');
        var hasError = $(rows).find('.error').length;
        if (status || hasError) {
            $(rows).removeClass('hide').show();
        } else {
            $(rows).hide();
        }
    };
})(jQuery);

$(document).ready(function() {

    $('#po_household_followup').off('.po')
                               .on('click.po', function() {
        $.showHouseholdComponents($(this).prop('checked'));
    });
    // Check initial state
    $.showHouseholdComponents($('#po_household_followup').prop('checked'));
});


text:
package org.apache.hadoop.hdfs.server.namenode;

import java.io.IOException;

public class FinalizeCheckpointException extends IOException {
  private static final long serialVersionUID = 1L;

  FinalizeCheckpointException(String reason) {
    super(reason);
  }
}


text:
import sys
import numpy
from tqdm import tqdm
from truncate import read_wave_file
from audio_helpers import fundamental_frequency

QUANTIZE_FACTOR = 8

def compare_windows(window_a, window_b):
    return numpy.sqrt(numpy.mean(numpy.power(window_a - window_b, 2)))

def slide_window(file, period, start_at=0, end_before=0):
    for power in reversed(xrange(7, 10)):
        multiple = 2 ** power
        window_size = int(period * multiple)
        # Uncomment this to search from the start_at value to the end_before
        # rather than just through one window's length
        # end_range = len(file) - (window_size * 2) - end_before
        end_range = start_at + window_size
        for i in xrange(start_at, end_range):
            yield power, i, window_size

def window_match(file):
    period = (1.0 / fundamental_frequency(file, 1)) * 2
    print period, 'period in samples'

    winner = None

    window_positions = list(
        slide_window(file, period, len(file) / 2, len(file) / 8)
    )
    for power, i, window_size in tqdm(window_positions):
        window_start = find_similar_sample_index(file, i, i + window_size)
        window_end = find_similar_sample_index(file, i, i + (window_size * 2))
        effective_size = window_end - window_start

        difference = compare_windows(
            file[i:i + effective_size],
            file[window_start:window_end]
        ) / effective_size
        if winner is None or difference < winner[0]:
            winner = (
                difference,
                effective_size,
                i,
                abs(file[i] - file[window_start])
            )
            print 'new winner', winner

    lowest_difference, winning_window_size, winning_index, gap = winner

    print "Best loop match:", lowest_difference
    print "window size", winning_window_size
    print "winning index", winning_index
    print "winning gap", gap
    return winning_index, winning_window_size

def slope_at_index(file, i):
    return (file[i + 1] - file[i - 1]) / 2

def find_similar_sample_index(
    file,
    reference_index,
    search_around_index,
    search_size=100  # samples
):
    reference_slope = slope_at_index(file, reference_index) > 0
    best_match = None
    search_range = xrange(
        search_around_index - search_size,
        search_around_index + search_size
    )
    for i in search_range:
        slope = slope_at_index(file, i) > 0
        if slope != reference_slope:
            continue

        abs_diff = abs(file[i] - file[reference_index])

        if best_match is not None:
            _, best_abs_diff = best_match
            if abs_diff < best_abs_diff:
                best_match = (i, abs_diff)
        else:
            best_match = (i, abs_diff)
    return best_match[0] if best_match is not None else search_around_index

def zero_crossing_match(file):
    period = (1.0 / fundamental_frequency(file, 1)) * 2
    print period, 'period in samples'

    period_multiple = 64
    period = period * period_multiple

    for i in reversed(xrange(2 * len(file) / 3, 5 * len(file) / 6)):
        if file[i] >= 0 and file[i + 1] < 0 and \
                file[int(i + period)] >= 0 and \
                file[int(i + 1 + period)] < 0 and \
                file[int(i + period * 2)] >= 0 and \
                file[int(i + 1 + period * 2)] < 0:
            return i, int(period)

def fast_autocorrelate(x):
    """
    Compute the autocorrelation of the signal, based on the properties of the
    power spectral density of the signal.

    Note that the input's length may be reduced before the correlation is
    performed due to a pathalogical case in numpy.fft:
    http://stackoverflow.com/a/23531074/679081

    > The FFT algorithm used in np.fft performs very well (meaning O(n log n))
    > when the input length has many small prime factors, and very bad
    > (meaning a naive DFT requiring O(n^2)) when the input size is a prime
    > number.
    """

    # This is one simple way to ensure that the input array
    # has a length with many small prime factors, although it
    # doesn't guarantee that (also hopefully we don't chop too much)
    optimal_input_length = int(numpy.sqrt(len(x))) ** 2
    x = x[:optimal_input_length]
    xp = x - numpy.mean(x)
    f = numpy.fft.fft(xp)
    p = numpy.absolute(numpy.power(f, 2))
    pi = numpy.fft.ifft(p)
    result = numpy.real(pi)[:x.size / 2] / numpy.sum(numpy.power(xp, 2))
    return result

def find_argmax_after(file, offset):
    return numpy.argmax(file[offset:]) + offset

def autocorrelated_loop(file, search_start, min_loop_width_in_seconds=0.2):
    # Strategy:
    #  1) run an autocorrelation on the file.
    #  3) Find argmax of the autocorrelation
    #  4) define some peak_width and find the next highest peak after current
    #  5) define the loop bounds as from the first peak to the second peak
    #  6) massage the loop bounds using find_similar_sample_index
    #  7) ???
    #  8) Profit!
    autocorrelation = fast_autocorrelate(file)
    return find_loop_from_autocorrelation(
        file,
        autocorrelation,
        search_start,
        min_loop_width_in_seconds
    )

def find_loop_from_autocorrelation(
    file,
    autocorrelation,
    search_start,
    min_loop_width_in_seconds=0.2,
    sample_rate=48000
):
    search_start /= 2
    max_autocorrelation_peak_width = int(
        min_loop_width_in_seconds * sample_rate
    )
    loop_start = find_argmax_after(autocorrelation, search_start)
    loop_end = find_argmax_after(
        autocorrelation,
        loop_start + max_autocorrelation_peak_width
    )

    loop_end = find_similar_sample_index(file, loop_start, loop_end) - 1
    return loop_start, (loop_end - loop_start)

def minimize(iterable, callable):
    best_result = None
    best_score = None
    for x in iterable:
        if x:
            score = callable(*x)
            if best_score is None or score < best_score:
                best_score = score
                best_result = x
    return best_result

def autocorrelate_loops(file, sample_rate):
    autocorrelation = fast_autocorrelate(file)
    search_points = [
        3 * len(file) / 4,
        2 * len(file) / 3,
        len(file) / 2,
        len(file) / 3,
    ]
    loop_widths = [0.2, 0.4, 0.6, 0.8, 1.0, 1.5, 2, 2.5, 3.]
    for search_point in search_points:
        for width in loop_widths:
            try:
                yield find_loop_from_autocorrelation(
                    file, autocorrelation,
                    search_point, width, sample_rate)
            except ValueError:
                # We couldn't search for a loop width of that size.
                pass
    yield None

def find_loop_points(data, sample_rate):
    channel = data[0]

    result = minimize(
        autocorrelate_loops(channel, sample_rate),
        lambda start, length: abs(channel[start] - channel[start + length])
    )

    if result:
        loop_start, loop_size = result
        return loop_start, loop_start + loop_size

def process(aif, sample_rate=48000):
    file = read_wave_file(aif)

    # loop_start, loop_size = window_match(file)
    # loop_start, loop_size = zero_crossing_match(file)
    loop_start, loop_end = find_loop_points(file)
    loop_size = loop_end - loop_start

    file = file[0]

    print 'start, end', loop_start, loop_end

    plt.plot(file[loop_start:loop_end])
    plt.plot(file[loop_end:loop_start + (2 * loop_size)])
    plt.show()

    plt.plot(file[
        loop_start - (sample_rate * 2):
        loop_start + (sample_rate * 2)
    ])
    plt.axvline(sample_rate * 2)
    plt.axvline((sample_rate * 2) + loop_size)
    plt.show()

if __name__ == "__main__":
    import matplotlib.pyplot as plt
    process(sys.argv[1])


text:
#ifndef _INCLUDE_PICTURE_H_
#define _INCLUDE_PICTURE_H_

#include "motion.h"

void overlay_smartmask(struct context *, unsigned char *);
void overlay_fixed_mask(struct context *, unsigned char *);
void put_fixed_mask(struct context *, const char *);
void overlay_largest_label(struct context *, unsigned char *);
void put_picture_fd(struct context *, FILE *, unsigned char *, int);
int put_picture_memory(struct context *, unsigned char*, int, unsigned char *, int);
void put_picture(struct context *, char *, unsigned char *, int );
unsigned char *get_pgm(FILE *, int, int);
void preview_save(struct context *);

#endif /* _INCLUDE_PICTURE_H_ */


text:
import requests
import string
from time import sleep
import math

from ytd.compat import text
from ytd.compat import quote

user_agent = 'yahoo-ticker-symbol-downloader'
general_search_characters = 'abcdefghijklmnopqrstuvwxyz0123456789.='
first_search_characters = 'abcdefghijklmnopqrstuvwxyz'

class SymbolDownloader:
    """Abstract class"""

    def __init__(self, type):
        # All downloaded symbols are stored in a dict before exporting
        # This is to ensure no duplicate data
        self.symbols = {}
        self.rsession = requests.Session()
        self.type = type

        self.queries = []
        self._add_queries()
        self.current_q = self.queries[0]
        self.done = False

    def _add_queries(self, prefix=''):
        # This method will add (prefix+)a...z to self.queries
        # This API requires the first character of the search to be a letter.
        # The second character can be a letter, number, dot, or equals sign.
        if len(prefix)==0:
            search_characters = first_search_characters
        else:
            search_characters = general_search_characters

        for i in range(len(search_characters)):
            element = str(prefix) + str(search_characters[i])
            if element not in self.queries:  # Avoid having duplicates in list
                self.queries.append(element)

    def _encodeParams(self, params):
        encoded = ''
        for key, value in params.items():
            encoded += ';' + quote(key) + '=' + quote(text(value))
        return encoded

    def _fetch(self, insecure):
        params = {
            'searchTerm': self.current_q,
        }
        query_string = {
            'device': 'console',
            'returnMeta': 'true',
        }
        protocol = 'http' if insecure else 'https'
        req = requests.Request('GET',
            protocol+'://finance.yahoo.com/_finance_doubledown/api/resource/searchassist'+self._encodeParams(params),
            headers={'User-agent': user_agent},
            params=query_string
        )
        req = req.prepare()
        print("req " + req.url)
        resp = self.rsession.send(req, timeout=(12, 12))
        resp.raise_for_status()

        return resp.json()

    def decodeSymbolsContainer(self, symbolsContainer):
        raise Exception("Function to extract symbols must be overwritten in subclass. Generic symbol downloader does not know how.")

    def _getQueryIndex(self):
        return self.queries.index(self.current_q)

    def getTotalQueries(self):
        return len(self.queries)

    def _nextQuery(self):
        if self._getQueryIndex() + 1 >= len(self.queries):
            self.current_q = self.queries[0]
        else:
            self.current_q = self.queries[self._getQueryIndex() + 1]

    def nextRequest(self, insecure=False, pandantic=False):
        self._nextQuery()
        success = False
        retryCount = 0
        json = None
        # Eponential back-off algorithm
        # to attempt 5 more times sleeping 5, 25, 125, 625, 3125 seconds
        # respectively.
        maxRetries = 5
        while(success == False):
            try:
                json = self._fetch(insecure)
                success = True
            except (requests.HTTPError,
                    requests.exceptions.ChunkedEncodingError,
                    requests.exceptions.ReadTimeout,
                    requests.exceptions.ConnectionError) as ex:
                if retryCount < maxRetries:
                    attempt = retryCount + 1
                    sleepAmt = int(math.pow(5,attempt))
                    print("Retry attempt: " + str(attempt) + " of " + str(maxRetries) + "."
                        " Sleep period: " + str(sleepAmt) + " seconds."
                        )
                    sleep(sleepAmt)
                    retryCount = attempt
                else:
                    raise

        (symbols, count) = self.decodeSymbolsContainer(json)

        for symbol in symbols:
            self.symbols[symbol.ticker] = symbol

        # There is no pagination with this API.
				# If we receive 10 results, we assume there are more than 10 and add another layer of queries to narrow the search further
        if(count == 10):
            self._add_queries(self.current_q)
        elif(count > 10):
            # This should never happen with this API, it always returns at most 10 items
            raise Exception("Funny things are happening: count "
                            + text(count)
                            + " > 10. "
                            + "Content:"
                            + "\n"
                            + repr(json))

        if self._getQueryIndex() + 1 >= len(self.queries):
            self.done = True
        else:
            self.done = False

        return symbols

    def isDone(self):
        return self.done

    def getCollectedSymbols(self):
        return self.symbols.values()

    def getRowHeader(self):
        return ["Ticker", "Name", "Exchange"]

    def printProgress(self):
        if self.isDone():
            print("Progress: Done!")
        else:
            print("Progress:"
                + " Query " + str(self._getQueryIndex()+1) + "/" + str(self.getTotalQueries()) + "."
                + "\n"
                + str(len(self.symbols)) + " unique " + self.type + " entries collected so far."
                )
        print ("")


text:
glue.module.create(
    [
        'glue/game',
        'glue/baseobject'
    ],
    function (Game, BaseObject) {
        describe('modules.glue.baseobject', function () {
            'use strict';

            it('Should be able to create a valid base object', function (done) {
                var object = BaseObject().add({
                    init: function () {},
                    update: function () {},
                    draw: function () {}
                });
                spyOn(object, 'init');
                spyOn(object, 'update');
                spyOn(object, 'draw');

                Game.add(object);

                setTimeout(function () {
                    expect(object.init).toHaveBeenCalled();
                    expect(object.update).toHaveBeenCalled();
                    expect(object.draw).toHaveBeenCalled();
                    done();
                }, 300);
            });
            it('Should be able to add children objects to a base object', function (done) {
                var initialized = false,
                    object = BaseObject().add({
                        init: function () {
                            // init should be called during addChild
                            initialized = true;
                        },
                        update: function () {
                            expect(initialized).toBeTruthy();
                            done();
                        }
                    }),
                    parent = BaseObject().add({
                        init: function () {
                            this.addChild(object);
                        }
                    });

                Game.add(parent);
            });
            it('Should be able to remove children from a base object', function (done) {
                var destroyed = false,
                    object = BaseObject().add({
                        destroy: function () {
                            // destroy method should be called after removeChild
                            destroyed = true;
                        }
                    }),
                    parent = BaseObject().add({
                        update: function (gameData) {
                            var children = this.getChildren();
                            // remove if children are present
                            if (children.length > 0) {
                                this.removeChild(object);
                            } else {
                                // no more children
                                expect(destroyed).toBeTruthy();
                                done();
                            }
                            // make sure you call the base update
                            this.base.update(gameData);
                        }
                    });

                parent.addChild(object);

                Game.add(parent);
            });
        });
    }
);


text:
"""
Django settings for whoshouldivotefor project.

Generated by 'django-admin startproject' using Django 1.11.2.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os
import dj_database_url

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('APP_SECRET')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = [
    'localhost',
    '127.0.0.1',
    'glacial-sands-83405.herokuapp.com',
    'www.whoshouldivotefor.ca',
    'whoshouldivotefor.ca',
]

# Application definition

INSTALLED_APPS = [
    'explorer.apps.ExplorerConfig',
    'api.apps.ApiConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'webpack_loader',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'whoshouldivotefor.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'whoshouldivotefor.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.environ.get('WSSIVF_DBNAME'),
        'USER': os.environ.get('WSSIVF_USER'),
        'PASSWORD': os.environ.get('WSSIVF_PASSWORD'),
        'HOST': 'localhost',
        'PORT': '',
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'America/Toronto'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Update database configuration with $DATABASE_URL.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)

# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'

# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT, 'static'),
    os.path.join(BASE_DIR, 'assets'),
)

# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
# STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'

REST_FRAMEWORK = {
    'PAGE_SIZE': 10,
}

WEBPACK_LOADER = {
    'DEFAULT': {
        'BUNDLE_DIR_NAME': 'bundles/',
        'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
    }
}


text:
using namespace llvm;

static std::unique_ptr<Module> parseIR(LLVMContext &C, const char *IR) {
  SMDiagnostic Err;
  std::unique_ptr<Module> Mod = parseAssemblyString(IR, Err, C);
  if (!Mod)
    Err.print("CodeMoverUtilsTests", errs());
  return Mod;
}

static void run(Module &M, StringRef FuncName,
                function_ref<void(Function &F, DominatorTree &DT,
                                  PostDominatorTree &PDT, DependenceInfo &DI)>
                    Test) {
  auto *F = M.getFunction(FuncName);
  DominatorTree DT(*F);
  PostDominatorTree PDT(*F);
  TargetLibraryInfoImpl TLII;
  TargetLibraryInfo TLI(TLII);
  AssumptionCache AC(*F);
  AliasAnalysis AA(TLI);
  LoopInfo LI(DT);
  ScalarEvolution SE(*F, TLI, AC, DT, LI);
  DependenceInfo DI(F, &AA, &SE, &LI);
  Test(*F, DT, PDT, DI);
}

static BasicBlock *getBasicBlockByName(Function &F, StringRef Name) {
  for (BasicBlock &BB : F)
    if (BB.getName() == Name)
      return &BB;
  llvm_unreachable("Expected to find basic block!");
}

static Instruction *getInstructionByName(Function &F, StringRef Name) {
  for (BasicBlock &BB : F)
    for (Instruction &I : BB)
      if (I.getName() == Name)
        return &I;
  llvm_unreachable("Expected to find instruction!");
}

TEST(CodeMoverUtils, IsControlFlowEquivalentSimpleTest) {
  LLVMContext C;

  // void foo(int &i, bool cond1, bool cond2) {
  //   if (cond1)
  //     i = 1;
  //   if (cond1)
  //     i = 2;
  //   if (cond2)
  //     i = 3;
  // }
  std::unique_ptr<Module> M =
      parseIR(C, R"(define void @foo(i32* %i, i1 %cond1, i1 %cond2) {
                 entry:
                   br i1 %cond1, label %if.first, label %if.first.end
                 if.first:
                   store i32 1, i32* %i, align 4
                   br label %if.first.end
                 if.first.end:
                   br i1 %cond1, label %if.second, label %if.second.end
                 if.second:
                   store i32 2, i32* %i, align 4
                   br label %if.second.end
                 if.second.end:
                   br i1 %cond2, label %if.third, label %if.third.end
                 if.third:
                   store i32 3, i32* %i, align 4
                   br label %if.third.end
                 if.third.end:
                   ret void
                 })");
  run(*M, "foo",
      [&](Function &F, DominatorTree &DT, PostDominatorTree &PDT,
          DependenceInfo &DI) {
        BasicBlock *FirstIfBody = getBasicBlockByName(F, "if.first");
        EXPECT_TRUE(
            isControlFlowEquivalent(*FirstIfBody, *FirstIfBody, DT, PDT));
        BasicBlock *SecondIfBody = getBasicBlockByName(F, "if.second");
        EXPECT_TRUE(
            isControlFlowEquivalent(*FirstIfBody, *SecondIfBody, DT, PDT));

        BasicBlock *ThirdIfBody = getBasicBlockByName(F, "if.third");
        EXPECT_FALSE(
            isControlFlowEquivalent(*FirstIfBody, *ThirdIfBody, DT, PDT));
        EXPECT_FALSE(
            isControlFlowEquivalent(*SecondIfBody, *ThirdIfBody, DT, PDT));
      });
}

TEST(CodeMoverUtils, IsControlFlowEquivalentOppositeCondTest) {
  LLVMContext C;

  // void foo(int &i, unsigned X, unsigned Y) {
  //   if (X < Y)
  //     i = 1;
  //   if (Y > X)
  //     i = 2;
  //   if (X >= Y)
  //     i = 3;
  //   else
  //     i = 4;
  //   if (X == Y)
  //     i = 5;
  //   if (Y == X)
  //     i = 6;
  //   else
  //     i = 7;
  //   if (X != Y)
  //     i = 8;
  //   else
  //     i = 9;
  // }
  std::unique_ptr<Module> M =
      parseIR(C, R"(define void @foo(i32* %i, i32 %X, i32 %Y) {
                 entry:
                   %cmp1 = icmp ult i32 %X, %Y
                   br i1 %cmp1, label %if.first, label %if.first.end
                 if.first:
                   store i32 1, i32* %i, align 4
                   br label %if.first.end
                 if.first.end:
                   %cmp2 = icmp ugt i32 %Y, %X
                   br i1 %cmp2, label %if.second, label %if.second.end
                 if.second:
                   store i32 2, i32* %i, align 4
                   br label %if.second.end
                 if.second.end:
                   %cmp3 = icmp uge i32 %X, %Y
                   br i1 %cmp3, label %if.third, label %if.third.else
                 if.third:
                   store i32 3, i32* %i, align 4
                   br label %if.third.end
                 if.third.else:
                   store i32 4, i32* %i, align 4
                   br label %if.third.end
                 if.third.end:
                   %cmp4 = icmp eq i32 %X, %Y
                   br i1 %cmp4, label %if.fourth, label %if.fourth.end
                 if.fourth:
                   store i32 5, i32* %i, align 4
                   br label %if.fourth.end
                 if.fourth.end:
                   %cmp5 = icmp eq i32 %Y, %X
                   br i1 %cmp5, label %if.fifth, label %if.fifth.else
                 if.fifth:
                   store i32 6, i32* %i, align 4
                   br label %if.fifth.end
                 if.fifth.else:
                   store i32 7, i32* %i, align 4
                   br label %if.fifth.end
                 if.fifth.end:
                   %cmp6 = icmp ne i32 %X, %Y
                   br i1 %cmp6, label %if.sixth, label %if.sixth.else
                 if.sixth:
                   store i32 8, i32* %i, align 4
                   br label %if.sixth.end
                 if.sixth.else:
                   store i32 9, i32* %i, align 4
                   br label %if.sixth.end
                 if.sixth.end:
                   ret void
                 })");
  run(*M, "foo",
      [&](Function &F, DominatorTree &DT, PostDominatorTree &PDT,
          DependenceInfo &DI) {
        BasicBlock *FirstIfBody = getBasicBlockByName(F, "if.first");
        BasicBlock *SecondIfBody = getBasicBlockByName(F, "if.second");
        BasicBlock *ThirdIfBody = getBasicBlockByName(F, "if.third");
        BasicBlock *ThirdElseBody = getBasicBlockByName(F, "if.third.else");
        EXPECT_TRUE(
            isControlFlowEquivalent(*FirstIfBody, *ThirdElseBody, DT, PDT));
        EXPECT_TRUE(
            isControlFlowEquivalent(*SecondIfBody, *ThirdElseBody, DT, PDT));
        EXPECT_FALSE(
            isControlFlowEquivalent(*ThirdIfBody, *ThirdElseBody, DT, PDT));

        BasicBlock *FourthIfBody = getBasicBlockByName(F, "if.fourth");
        BasicBlock *FifthIfBody = getBasicBlockByName(F, "if.fifth");
        BasicBlock *FifthElseBody = getBasicBlockByName(F, "if.fifth.else");
        EXPECT_FALSE(
            isControlFlowEquivalent(*FifthIfBody, *FifthElseBody, DT, PDT));
        BasicBlock *SixthIfBody = getBasicBlockByName(F, "if.sixth");
        EXPECT_TRUE(
            isControlFlowEquivalent(*FifthElseBody, *SixthIfBody, DT, PDT));
        BasicBlock *SixthElseBody = getBasicBlockByName(F, "if.sixth.else");
        EXPECT_TRUE(
            isControlFlowEquivalent(*FourthIfBody, *SixthElseBody, DT, PDT));
        EXPECT_TRUE(
            isControlFlowEquivalent(*FifthIfBody, *SixthElseBody, DT, PDT));
      });
}

TEST(CodeMoverUtils, IsControlFlowEquivalentCondNestTest) {
  LLVMContext C;

  // void foo(int &i, bool cond1, bool cond2) {
  //   if (cond1)
  //     if (cond2)
  //       i = 1;
  //   if (cond2)
  //     if (cond1)
  //       i = 2;
  // }
  std::unique_ptr<Module> M =
      parseIR(C, R"(define void @foo(i32* %i, i1 %cond1, i1 %cond2) {
         entry:
           br i1 %cond1, label %if.outer.first, label %if.first.end
         if.outer.first:
           br i1 %cond2, label %if.inner.first, label %if.first.end
         if.inner.first:
           store i32 1, i32* %i, align 4
           br label %if.first.end
         if.first.end:
           br i1 %cond2, label %if.outer.second, label %if.second.end
         if.outer.second:
           br i1 %cond1, label %if.inner.second, label %if.second.end
         if.inner.second:
           store i32 2, i32* %i, align 4
           br label %if.second.end
         if.second.end:
           ret void
         })");
  run(*M, "foo",
      [&](Function &F, DominatorTree &DT, PostDominatorTree &PDT,
          DependenceInfo &DI) {
        BasicBlock *FirstOuterIfBody = getBasicBlockByName(F, "if.outer.first");
        BasicBlock *FirstInnerIfBody = getBasicBlockByName(F, "if.inner.first");
        BasicBlock *SecondOuterIfBody =
            getBasicBlockByName(F, "if.outer.second");
        BasicBlock *SecondInnerIfBody =
            getBasicBlockByName(F, "if.inner.second");
        EXPECT_TRUE(isControlFlowEquivalent(*FirstInnerIfBody,
                                            *SecondInnerIfBody, DT, PDT));
        EXPECT_FALSE(isControlFlowEquivalent(*FirstOuterIfBody,
                                             *SecondOuterIfBody, DT, PDT));
        EXPECT_FALSE(isControlFlowEquivalent(*FirstOuterIfBody,
                                             *SecondInnerIfBody, DT, PDT));
        EXPECT_FALSE(isControlFlowEquivalent(*FirstInnerIfBody,
                                             *SecondOuterIfBody, DT, PDT));
      });
}

TEST(CodeMoverUtils, IsControlFlowEquivalentImbalanceTest) {
  LLVMContext C;

  // void foo(int &i, bool cond1, bool cond2) {
  //   if (cond1)
  //     if (cond2)
  //       if (cond3)
  //         i = 1;
  //   if (cond2)
  //     if (cond3)
  //       i = 2;
  //   if (cond1)
  //     if (cond1)
  //       i = 3;
  //   if (cond1)
  //     i = 4;
  // }
  std::unique_ptr<Module> M = parseIR(
      C, R"(define void @foo(i32* %i, i1 %cond1, i1 %cond2, i1 %cond3) {
         entry:
           br i1 %cond1, label %if.outer.first, label %if.first.end
         if.outer.first:
           br i1 %cond2, label %if.middle.first, label %if.first.end
         if.middle.first:
           br i1 %cond3, label %if.inner.first, label %if.first.end
         if.inner.first:
           store i32 1, i32* %i, align 4
           br label %if.first.end
         if.first.end:
           br i1 %cond2, label %if.outer.second, label %if.second.end
         if.outer.second:
           br i1 %cond3, label %if.inner.second, label %if.second.end
         if.inner.second:
           store i32 2, i32* %i, align 4
           br label %if.second.end
         if.second.end:
           br i1 %cond1, label %if.outer.third, label %if.third.end
         if.outer.third:
           br i1 %cond1, label %if.inner.third, label %if.third.end
         if.inner.third:
           store i32 3, i32* %i, align 4
           br label %if.third.end
         if.third.end:
           br i1 %cond1, label %if.fourth, label %if.fourth.end
         if.fourth:
           store i32 4, i32* %i, align 4
           br label %if.fourth.end
         if.fourth.end:
           ret void
         })");
  run(*M, "foo",
      [&](Function &F, DominatorTree &DT, PostDominatorTree &PDT,
          DependenceInfo &DI) {
        BasicBlock *FirstIfBody = getBasicBlockByName(F, "if.inner.first");
        BasicBlock *SecondIfBody = getBasicBlockByName(F, "if.inner.second");
        EXPECT_FALSE(
            isControlFlowEquivalent(*FirstIfBody, *SecondIfBody, DT, PDT));

        BasicBlock *ThirdIfBody = getBasicBlockByName(F, "if.inner.third");
        BasicBlock *FourthIfBody = getBasicBlockByName(F, "if.fourth");
        EXPECT_TRUE(
            isControlFlowEquivalent(*ThirdIfBody, *FourthIfBody, DT, PDT));
      });
}

TEST(CodeMoverUtils, IsControlFlowEquivalentPointerTest) {
  LLVMContext C;

  // void foo(int &i, int *cond) {
  //   if (*cond)
  //     i = 1;
  //   if (*cond)
  //     i = 2;
  //   *cond = 1;
  //   if (*cond)
  //     i = 3;
  // }
  std::unique_ptr<Module> M =
      parseIR(C, R"(define void @foo(i32* %i, i32* %cond) {
                 entry:
                   %0 = load i32, i32* %cond, align 4
                   %tobool1 = icmp ne i32 %0, 0
                   br i1 %tobool1, label %if.first, label %if.first.end
                 if.first:
                   store i32 1, i32* %i, align 4
                   br label %if.first.end
                 if.first.end:
                   %1 = load i32, i32* %cond, align 4
                   %tobool2 = icmp ne i32 %1, 0
                   br i1 %tobool2, label %if.second, label %if.second.end
                 if.second:
                   store i32 2, i32* %i, align 4
                   br label %if.second.end
                 if.second.end:
                   store i32 1, i32* %cond, align 4
                   %2 = load i32, i32* %cond, align 4
                   %tobool3 = icmp ne i32 %2, 0
                   br i1 %tobool3, label %if.third, label %if.third.end
                 if.third:
                   store i32 3, i32* %i, align 4
                   br label %if.third.end
                 if.third.end:
                   ret void
                 })");
  run(*M, "foo",
      [&](Function &F, DominatorTree &DT, PostDominatorTree &PDT,
          DependenceInfo &DI) {
        BasicBlock *FirstIfBody = getBasicBlockByName(F, "if.first");
        BasicBlock *SecondIfBody = getBasicBlockByName(F, "if.second");
        // Limitation: if we can prove cond haven't been modify between %0 and
        // %1, then we can prove FirstIfBody and SecondIfBody are control flow
        // equivalent.
        EXPECT_FALSE(
            isControlFlowEquivalent(*FirstIfBody, *SecondIfBody, DT, PDT));

        BasicBlock *ThirdIfBody = getBasicBlockByName(F, "if.third");
        EXPECT_FALSE(
            isControlFlowEquivalent(*FirstIfBody, *ThirdIfBody, DT, PDT));
        EXPECT_FALSE(
            isControlFlowEquivalent(*SecondIfBody, *ThirdIfBody, DT, PDT));
      });
}

TEST(CodeMoverUtils, IsControlFlowEquivalentNotPostdomTest) {
  LLVMContext C;

  // void foo(bool cond1, bool cond2) {
  //   if (cond1) {
  //     if (cond2)
  //       return;
  //   } else
  //     if (cond2)
  //       return;
  //   return;
  // }
  std::unique_ptr<Module> M =
      parseIR(C, R"(define void @foo(i1 %cond1, i1 %cond2) {
                 idom:
                   br i1 %cond1, label %succ0, label %succ1
                 succ0:
                   br i1 %cond2, label %succ0ret, label %succ0succ1
                 succ0ret:
                   ret void
                 succ0succ1:
                   br label %bb
                 succ1:
                   br i1 %cond2, label %succ1ret, label %succ1succ1
                 succ1ret:
                   ret void
                 succ1succ1:
                   br label %bb
                 bb:
                   ret void
                 })");
  run(*M, "foo",
      [&](Function &F, DominatorTree &DT, PostDominatorTree &PDT,
          DependenceInfo &DI) {
        BasicBlock &Idom = F.front();
        assert(Idom.getName() == "idom" && "Expecting BasicBlock idom");
        BasicBlock &BB = F.back();
        assert(BB.getName() == "bb" && "Expecting BasicBlock bb");
        EXPECT_FALSE(isControlFlowEquivalent(Idom, BB, DT, PDT));
      });
}

TEST(CodeMoverUtils, IsSafeToMoveTest1) {
  LLVMContext C;

  // void safecall() noexcept willreturn nosync;
  // void unsafecall();
  // void foo(int * __restrict__ A, int * __restrict__ B, int * __restrict__ C,
  //          long N) {
  //   X = N / 1;
  //   safecall();
  //   unsafecall1();
  //   unsafecall2();
  //   for (long i = 0; i < N; ++i) {
  //     A[5] = 5;
  //     A[i] = 0;
  //     B[i] = A[i];
  //     C[i] = A[i];
  //     A[6] = 6;
  //   }
  // }
  std::unique_ptr<Module> M = parseIR(
      C, R"(define void @foo(i32* noalias %A, i32* noalias %B, i32* noalias %C
                           , i64 %N) {
         entry:
           %X = sdiv i64 1, %N
           call void @safecall()
           %cmp1 = icmp slt i64 0, %N
           call void @unsafecall1()
           call void @unsafecall2()
           br i1 %cmp1, label %for.body, label %for.end
         for.body:
           %i = phi i64 [ 0, %entry ], [ %inc, %for.body ]
           %arrayidx_A5 = getelementptr inbounds i32, i32* %A, i64 5
           store i32 5, i32* %arrayidx_A5, align 4
           %arrayidx_A = getelementptr inbounds i32, i32* %A, i64 %i
           store i32 0, i32* %arrayidx_A, align 4
           %load1 = load i32, i32* %arrayidx_A, align 4
           %arrayidx_B = getelementptr inbounds i32, i32* %B, i64 %i
           store i32 %load1, i32* %arrayidx_B, align 4
           %load2 = load i32, i32* %arrayidx_A, align 4
           %arrayidx_C = getelementptr inbounds i32, i32* %C, i64 %i
           store i32 %load2, i32* %arrayidx_C, align 4
           %arrayidx_A6 = getelementptr inbounds i32, i32* %A, i64 6
           store i32 6, i32* %arrayidx_A6, align 4
           %inc = add nsw i64 %i, 1
           %cmp = icmp slt i64 %inc, %N
           br i1 %cmp, label %for.body, label %for.end
         for.end:
           ret void
         }
         declare void @safecall() nounwind nosync willreturn
         declare void @unsafecall1()
         declare void @unsafecall2())");

  run(*M, "foo",
      [&](Function &F, DominatorTree &DT, PostDominatorTree &PDT,
          DependenceInfo &DI) {
        BasicBlock *Entry = getBasicBlockByName(F, "entry");
        Instruction *CI_safecall = Entry->front().getNextNode();
        assert(isa<CallInst>(CI_safecall) &&
               "Expecting CI_safecall to be a CallInst");
        Instruction *CI_unsafecall = CI_safecall->getNextNode()->getNextNode();
        assert(isa<CallInst>(CI_unsafecall) &&
               "Expecting CI_unsafecall to be a CallInst");
        BasicBlock *ForBody = getBasicBlockByName(F, "for.body");
        Instruction &PN = ForBody->front();
        assert(isa<PHINode>(PN) && "Expecting PN to be a PHINode");
        Instruction *SI_A5 =
            getInstructionByName(F, "arrayidx_A5")->getNextNode();
        Instruction *SI = getInstructionByName(F, "arrayidx_A")->getNextNode();
        Instruction *LI1 = getInstructionByName(F, "load1");
        Instruction *LI2 = getInstructionByName(F, "load2");
        Instruction *SI_A6 =
            getInstructionByName(F, "arrayidx_A6")->getNextNode();

        // Can move after CI_safecall, as it does not throw, not synchronize, or
        // must return.
        EXPECT_TRUE(isSafeToMoveBefore(*CI_safecall->getPrevNode(),
                                       *CI_safecall->getNextNode(), DT, PDT,
                                       DI));

        // Cannot move CI_unsafecall, as it may throw.
        EXPECT_FALSE(isSafeToMoveBefore(*CI_unsafecall->getNextNode(),
                                        *CI_unsafecall, DT, PDT, DI));

        // Moving instruction to non control flow equivalent places are not
        // supported.
        EXPECT_FALSE(
            isSafeToMoveBefore(*SI_A5, *Entry->getTerminator(), DT, PDT, DI));

        // Moving PHINode is not supported.
        EXPECT_FALSE(isSafeToMoveBefore(PN, *PN.getNextNode()->getNextNode(),
                                        DT, PDT, DI));

        // Cannot move non-PHINode before PHINode.
        EXPECT_FALSE(isSafeToMoveBefore(*PN.getNextNode(), PN, DT, PDT, DI));

        // Moving Terminator is not supported.
        EXPECT_FALSE(isSafeToMoveBefore(*Entry->getTerminator(),
                                        *PN.getNextNode(), DT, PDT, DI));

        // Cannot move %arrayidx_A after SI, as SI is its user.
        EXPECT_FALSE(isSafeToMoveBefore(*SI->getPrevNode(), *SI->getNextNode(),
                                        DT, PDT, DI));

        // Cannot move SI before %arrayidx_A, as %arrayidx_A is its operand.
        EXPECT_FALSE(isSafeToMoveBefore(*SI, *SI->getPrevNode(), DT, PDT, DI));

        // Cannot move LI2 after SI_A6, as there is a flow dependence.
        EXPECT_FALSE(
            isSafeToMoveBefore(*LI2, *SI_A6->getNextNode(), DT, PDT, DI));

        // Cannot move SI after LI1, as there is a anti dependence.
        EXPECT_FALSE(isSafeToMoveBefore(*SI, *LI1->getNextNode(), DT, PDT, DI));

        // Cannot move SI_A5 after SI, as there is a output dependence.
        EXPECT_FALSE(isSafeToMoveBefore(*SI_A5, *LI1, DT, PDT, DI));

        // Can move LI2 before LI1, as there is only an input dependence.
        EXPECT_TRUE(isSafeToMoveBefore(*LI2, *LI1, DT, PDT, DI));
      });
}

TEST(CodeMoverUtils, IsSafeToMoveTest2) {
  LLVMContext C;

  std::unique_ptr<Module> M =
      parseIR(C, R"(define void @foo(i1 %cond, i32 %op0, i32 %op1) {
                 entry:
                   br i1 %cond, label %if.then.first, label %if.end.first
                 if.then.first:
                   %add = add i32 %op0, %op1
                   %user = add i32 %add, 1
                   br label %if.end.first
                 if.end.first:
                   br i1 %cond, label %if.then.second, label %if.end.second
                 if.then.second:
                   %sub_op0 = add i32 %op0, 1
                   %sub = sub i32 %sub_op0, %op1
                   br label %if.end.second
                 if.end.second:
                   ret void
                 })");

  run(*M, "foo",
      [&](Function &F, DominatorTree &DT, PostDominatorTree &PDT,
          DependenceInfo &DI) {
        Instruction *AddInst = getInstructionByName(F, "add");
        Instruction *SubInst = getInstructionByName(F, "sub");

        // Cannot move as %user uses %add and %sub doesn't dominates %user.
        EXPECT_FALSE(isSafeToMoveBefore(*AddInst, *SubInst, DT, PDT, DI));

        // Cannot move as %sub_op0 is an operand of %sub and %add doesn't
        // dominates %sub_op0.
        EXPECT_FALSE(isSafeToMoveBefore(*SubInst, *AddInst, DT, PDT, DI));
      });
}

TEST(CodeMoverUtils, IsSafeToMoveTest3) {
  LLVMContext C;

  std::unique_ptr<Module> M = parseIR(C, R"(define void @foo(i64 %N) {
                 entry:
                   br label %for.body
                 for.body:
                   %i = phi i64 [ 0, %entry ], [ %inc, %for.latch ]
                   %inc = add nsw i64 %i, 1
                   br label %for.latch
                 for.latch:
                   %cmp = icmp slt i64 %inc, %N
                   br i1 %cmp, label %for.body, label %for.end
                 for.end:
                   ret void
                 })");

  run(*M, "foo",
      [&](Function &F, DominatorTree &DT, PostDominatorTree &PDT,
          DependenceInfo &DI) {
        Instruction *IncInst = getInstructionByName(F, "inc");
        Instruction *CmpInst = getInstructionByName(F, "cmp");

        // Can move as the incoming block of %inc for %i (%for.latch) dominated
        // by %cmp.
        EXPECT_TRUE(isSafeToMoveBefore(*IncInst, *CmpInst, DT, PDT, DI));
      });
}


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

#nullable disable

using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
    public class ModifierTests : CSharpTestBase
    {
        [Fact]
        public void Simple1()
        {
            var text =
@"abstract class A : Base
{
    void M1() { }
    public void M2() { }
    protected void M3() { }
    internal void M4() { }
    protected internal void M5() { }
    internal abstract protected void M5_1() { }
    abstract protected internal void M5_2() { }
    private void M6() { }
    extern void M7();
    override sealed internal void M8() { }
    override internal sealed void M8_1() { }
    internal override sealed void M8_2() { }
    abstract internal void M9();
    override internal void M10() { }
    virtual internal void M11() { }
    static void M12() { }
}
abstract class Base
{
    virtual internal void M8() { }
    abstract internal void M10();
}";
            var comp = CreateCompilation(text);
            var global = comp.GlobalNamespace;
            var a = global.GetTypeMembers("A", 0).Single();
            var m1 = a.GetMembers("M1").Single() as MethodSymbol;
            Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility);
            Assert.True(m1.ReturnsVoid);
            var m2 = a.GetMembers("M2").Single() as MethodSymbol;
            Assert.Equal(Accessibility.Public, m2.DeclaredAccessibility);
            var m3 = a.GetMembers("M3").Single() as MethodSymbol;
            Assert.Equal(Accessibility.Protected, m3.DeclaredAccessibility);
            var m4 = a.GetMembers("M4").Single() as MethodSymbol;
            Assert.Equal(Accessibility.Internal, m4.DeclaredAccessibility);
            var m5 = a.GetMembers("M5").Single() as MethodSymbol;
            Assert.Equal(Accessibility.ProtectedOrInternal, m5.DeclaredAccessibility);
            var m5_1 = a.GetMembers("M5_1").Single() as MethodSymbol;
            Assert.Equal(Accessibility.ProtectedOrInternal, m5_1.DeclaredAccessibility);
            Assert.True(m5_1.IsAbstract);
            var m5_2 = a.GetMembers("M5_2").Single() as MethodSymbol;
            Assert.Equal(Accessibility.ProtectedOrInternal, m5_2.DeclaredAccessibility);
            Assert.True(m5_2.IsAbstract);
            var m6 = a.GetMembers("M6").Single() as MethodSymbol;
            Assert.Equal(Accessibility.Private, m6.DeclaredAccessibility);
            var m7 = a.GetMembers("M7").Single() as MethodSymbol;
            Assert.True(m7.IsExtern);
            var m8 = a.GetMembers("M8").Single() as MethodSymbol;
            Assert.True(m8.IsOverride);
            Assert.True(m8.IsSealed);
            Assert.Equal(Accessibility.Internal, m8.DeclaredAccessibility);
            var m8_1 = a.GetMembers("M8_1").Single() as MethodSymbol;
            Assert.True(m8_1.IsOverride);
            Assert.True(m8_1.IsSealed);
            Assert.Equal(Accessibility.Internal, m8_1.DeclaredAccessibility);
            var m8_2 = a.GetMembers("M8_2").Single() as MethodSymbol;
            Assert.True(m8_2.IsOverride);
            Assert.True(m8_2.IsSealed);
            Assert.Equal(Accessibility.Internal, m8_2.DeclaredAccessibility);
            var m9 = a.GetMembers("M9").Single() as MethodSymbol;
            Assert.True(m9.IsAbstract);
            Assert.Equal(Accessibility.Internal, m9.DeclaredAccessibility);
            var m10 = a.GetMembers("M10").Single() as MethodSymbol;
            Assert.True(m10.IsOverride);
            Assert.Equal(Accessibility.Internal, m10.DeclaredAccessibility);
            var m11 = a.GetMembers("M11").Single() as MethodSymbol;
            Assert.True(m11.IsVirtual);
            Assert.Equal(Accessibility.Internal, m11.DeclaredAccessibility);
            var m12 = a.GetMembers("M12").Single() as MethodSymbol;
            Assert.True(m12.IsStatic);
        }

        [Fact]
        public void InScript()
        {
            var text =
@"
void M1() { }
public void M2() { }
protected void M3() { }
internal void M4() { }
protected internal void M5() { }
private void M6() { }
extern void M7();
static void M12() { }
";

            var comp = CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Script);
            var script = comp.ScriptClass;
            var m1 = script.GetMembers("M1").Single() as MethodSymbol;
            Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility);
            var m2 = script.GetMembers("M2").Single() as MethodSymbol;
            Assert.Equal(Accessibility.Public, m2.DeclaredAccessibility);
            var m3 = script.GetMembers("M3").Single() as MethodSymbol;
            Assert.Equal(Accessibility.Protected, m3.DeclaredAccessibility);
            var m4 = script.GetMembers("M4").Single() as MethodSymbol;
            Assert.Equal(Accessibility.Internal, m4.DeclaredAccessibility);
            var m5 = script.GetMembers("M5").Single() as MethodSymbol;
            Assert.Equal(Accessibility.ProtectedOrInternal, m5.DeclaredAccessibility);
            var m6 = script.GetMembers("M6").Single() as MethodSymbol;
            Assert.Equal(Accessibility.Private, m6.DeclaredAccessibility);
            var m7 = script.GetMembers("M7").Single() as MethodSymbol;
            Assert.True(m7.IsExtern);
            var m12 = script.GetMembers("M12").Single() as MethodSymbol;
            Assert.True(m12.IsStatic);

            comp.VerifyDiagnostics(
                // (4,16): warning CS0628: 'M3()': new protected member declared in sealed type
                Diagnostic(ErrorCode.WRN_ProtectedInSealed, "M3").WithArguments("M3()"),
                // (6,25): warning CS0628: 'M5()': new protected member declared in sealed type
                Diagnostic(ErrorCode.WRN_ProtectedInSealed, "M5").WithArguments("M5()"),
                // (8,13): warning CS0626: Method, operator, or accessor 'M7()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation.
                Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M7").WithArguments("M7()")
            );
        }

        [Fact]
        public void TypeMap()
        {
            var source = @"
struct S<T> where T : struct
{
}
";

            var comp = CreateCompilation(source);
            comp.VerifyDiagnostics();

            var intType = comp.GetSpecialType(SpecialType.System_Int32);
            var customModifiers = ImmutableArray.Create(CSharpCustomModifier.CreateOptional(intType));

            var structType = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("S");
            var typeParamType = structType.TypeParameters.Single();

            var pointerType = new PointerTypeSymbol(TypeWithAnnotations.Create(typeParamType, customModifiers: customModifiers)); // NOTE: We're constructing this manually, since it's illegal.
            var arrayType = ArrayTypeSymbol.CreateCSharpArray(comp.Assembly, TypeWithAnnotations.Create(typeParamType, customModifiers: customModifiers)); // This is legal, but we're already manually constructing types.

            var typeMap = new TypeMap(ImmutableArray.Create(typeParamType), ImmutableArray.Create(TypeWithAnnotations.Create(intType)));

            var substitutedPointerType = (PointerTypeSymbol)typeMap.SubstituteType(pointerType).AsTypeSymbolOnly();
            var substitutedArrayType = (ArrayTypeSymbol)typeMap.SubstituteType(arrayType).AsTypeSymbolOnly();

            // The map changed the types.
            Assert.Equal(intType, substitutedPointerType.PointedAtType);
            Assert.Equal(intType, substitutedArrayType.ElementType);

            // The map preserved the custom modifiers.
            Assert.Equal(customModifiers, substitutedPointerType.PointedAtTypeWithAnnotations.CustomModifiers);
            Assert.Equal(customModifiers, substitutedArrayType.ElementTypeWithAnnotations.CustomModifiers);
        }
    }
}


text:
package com.sixsq.slipstream.user;

import org.restlet.Context;
import org.restlet.resource.ServerResource;
import org.restlet.routing.Router;
import org.restlet.routing.Template;
import org.restlet.routing.TemplateRoute;
import org.restlet.security.Role;
import org.restlet.security.RoleAuthorizer;
import org.restlet.routing.Variable;
import java.util.Map;

import com.sixsq.slipstream.authz.SuperEnroler;

/**
 * User application to view and edit user data.
 *
 * The URL layout of this router is the following:
 *
 *

 *
/{user}?edit={edit}

 *
/{user}

 *
/

 *

 *
 * @author Marc-Elian Begin
 *
 */
public class UserRouter extends Router {

	public UserRouter(Context context) {
		super(context);

		attachPaths(new String[] { "/{" + UserResource.USERNAME_URI_ATTRIBUTE + "}" }, UserResource.class);

		attachPathsWithSuper(new String[] { "" }, UserListResource.class);
	}

	private void attachPaths(String[] paths,
			Class<? extends ServerResource> resourceClass) {
		attachPathsWithRole(paths, resourceClass, null);
	}

	private void attachPathsWithSuper(String[] paths,
			Class<? extends ServerResource> resourceClass) {
		attachPathsWithRole(paths, resourceClass, SuperEnroler.Super);
	}

	private void attachPathsWithRole(String[] paths,
			Class<? extends ServerResource> c, Role role) {
		for (String path : paths) {
			attachPath(path, c, role);
		}
	}

	private void attachPath(String path,
			Class<? extends ServerResource> resourceClass, Role role) {
		RoleAuthorizer ra = new RoleAuthorizer();
		TemplateRoute route;
		if (role != null) {
			ra.getAuthorizedRoles().add(role);
			ra.setNext(resourceClass);
			route = attach(path, ra);
		} else {
			route = attach(path, resourceClass);
		}
		route.setMatchingMode(Template.MODE_STARTS_WITH);

		// Allow the user variable to match any valid path characters.
		// Needed because usernames from external sources may contain slashes.
		Template template = route.getTemplate();
		Map<String, Variable> variables = template.getVariables();
		variables.put(UserResource.USERNAME_URI_ATTRIBUTE, new Variable(Variable.TYPE_URI_PATH));
		template.setVariables(variables);
	}
}


text:
=head1 LICENSE

Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

package EnsEMBL::Admin::Component::Changelog::Display;

use strict;
use warnings;

use base qw(EnsEMBL::ORM::Component::DbFrontend::Display);

sub record_tree {
  ## @overrides
  ## Adds a link 'Copy to current release' in case release on changelog is not same as current release
  my ($self, $record) = @_;

  my $hub         = $self->hub;
  my $object      = $self->object;
  my $record_div  = $self->SUPER::record_tree($record);
  my $current_rel = $object->current_release;

  if ($record->release_id ne $current_rel) {
    if (my $button_div = $record_div->get_nodes_by_flag($self->_FLAG_RECORD_BUTTONS)->[0]) {
      my $button = $button_div->append_HTML(sprintf('Copy to current release (%s)',
        $hub->url({'action' => 'Duplicate', 'id' => $record->get_primary_key_value, 'release' => $current_rel}),
        $current_rel)
      );
    }
  }

  return $record_div;
}

1;


text:
#import "BLETrigger.h"

#import "BLEKitPrivate.h"
#import "UNCodingUtil.h"

@implementation BLETrigger

- (instancetype) initWithBeacon:(BLEBeacon *)blebeacon
{
    if (self = [self init]) {
        self.beacon = blebeacon;
    }
    return self;
}

#pragma mark - BLEUpdatableFromDictionary

- (void)updatePropertiesFromDictionary:(NSDictionary *)dictionary
{
    self->_uniqueIdentifier = [dictionary[@"id"] description];
    self->_comment = dictionary[@"comment"];
    self->_name = dictionary[@"name"];

    if (dictionary[@"action"]) {
        id <BLEAction> action = [[BLEAction alloc] initWithUniqueIdentifier:[dictionary[@"action"][@"id"] description] andTrigger:self];

        if ([action conformsToProtocol:@protocol(BLEAction)]) {
            /**
             *  Called on <BLEAction>, not on custom actions because <BLEUpdatableFromDictionary> is private here
             */
            [action performSelector:@selector(updatePropertiesFromDictionary:) withObject:dictionary[@"action"]];
        }

        self->_action = action;
    }

    if (dictionary[@"conditions"]) {
        NSArray *array = dictionary[@"conditions"];
        NSMutableSet *set = [NSMutableSet setWithCapacity:array.count];

        for (NSDictionary *conditionDictionary in array) {
            BLECondition *condition = [[BLECondition alloc] initWithTrigger:self];
            [condition updatePropertiesFromDictionary:conditionDictionary];
            [set addObject:condition];
        }
        self->_conditions = [set copy];
    }
}

- (BOOL) validateConditionsWithOccurrence:(BLEEventType)eventType
{
    for (BLECondition *condition in self.conditions) {
        if (![condition validateForEventType:eventType] || ![condition validateForParameters:YES])
            return NO;
    }
    return self.conditions.count > 0 ? YES : NO;
}

- (BOOL) validateConditionsWithoutOccurrency:(BLEEventType)eventType
{
    for (BLECondition *condition in self.conditions) {
        if (![condition validateForEventType:eventType] || ![condition validateForParameters:NO])
            return NO;
    }
    return self.conditions.count > 0 ? YES : NO;
}

- (BOOL) validateEventType:(BLEEventType)eventType
{
    for (BLECondition *condition in self.conditions) {
        if (![condition validateForEventType:eventType])
            return NO;
    }
    return self.conditions.count > 0 ? YES : NO;
}

#pragma mark - NSSecureCoding

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    if (!self) {
        return nil;
    }

    [UNCodingUtil decodeObject:self withCoder:aDecoder];

    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [UNCodingUtil encodeObject:self withCoder:aCoder];
}

+ (BOOL)supportsSecureCoding
{
    return YES;
}

@end


text:
package com.vip.saturn.job.console.domain;

/**
 * @author hebelala
 */
public class ExportJobConfigPageStatus {

	private boolean exported;
	private boolean success;
	private int successNamespaceNum;
	private int successJobNum;

	public boolean isExported() {
		return exported;
	}

	public void setExported(boolean exported) {
		this.exported = exported;
	}

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public int getSuccessNamespaceNum() {
		return successNamespaceNum;
	}

	public void setSuccessNamespaceNum(int successNamespaceNum) {
		this.successNamespaceNum = successNamespaceNum;
	}

	public int getSuccessJobNum() {
		return successJobNum;
	}

	public void setSuccessJobNum(int successJobNum) {
		this.successJobNum = successJobNum;
	}

}


text:
struct StreamMesh;

bool exportMeshToFile(const std::string &fileName, const StreamMesh &meshData);


text:
/**
 * @package assets
 */

(function($) {

	/**
	 * This plugin inserts tags from a list into an input field. It offers three modes:
	 * singular - allowing only one tag at a time
	 * multiple - allowing multiple tags, comma separated
	 * inline - which adds tags at the current cursor position
	 *
	 * @param {Object} custom_settings
	 *  An object specifying the tag list items
	 */
	$.fn.symphonyTags = function(custom_settings) {
		var objects = this,
			settings = {
				items: 'li'
			};

		$.extend(settings, custom_settings);

	/*-----------------------------------------------------------------------*/

		return objects.delegate(settings.items, 'click.tags', function(event) {
			var item = $(this),
				object = item.parent(),
				input = object.prev().find('input'),
				value = input.val(),
				tag = item.attr('class') || item.text();

			// Singular
			if(object.is('.singular')) {
				input.val(tag);
			}

			// Inline
			else if(object.is('.inline')) {
				var start = input[0].selectionStart,
					end = input[0].selectionEnd,
					position = 0;

				// Insert tag
				if(start > 0) {
					input.val(value.substring(0, start) + tag + value.substring(end, value.length));
					position = start + tag.length;
				}

				// Append tag
				else {
					input.val(value + tag);
					position = value.length + tag.length;
				}

				// Reset cursor position
				input[0].selectionStart = position;
				input[0].selectionEnd = position;
			}

			// Multiple
			else {
				var exp = new RegExp('^' + tag + '$', 'i'),
					tags = value.split(/,\s*/),
					removed = false;

				// Check existing tags
				for(var index in tags) {

					// Remove existing tag
					if(tags[index].match(exp)) {
						tags.splice(index, 1);
						removed = true;
					}

					// Remove empty tags
					else if(tags[index] == '') {
						tags.splice(index, 1);
					}
				}

				// Add new tag
				if(removed === false) {
					tags.push(tag);
				}

				// Save tags
				input.val(tags.join(', '));
			}
		});
	};

})(jQuery.noConflict());


text:
phpStorm SpaceGray color scheme
==================

phpStorm SpaceGray color is based on SpaceGray theme http://kkga.github.io/spacegray for Sublime Text

## Fonts

* From Screenshots: [Souce Code Pro](https://github.com/adobe-fonts/source-code-pro) alternate  [Download link](http://www.fontsquirrel.com/fonts/source-code-pro)
* Other choice [Fira Mono](https://www.google.com/fonts/specimen/Fira+Mono), [Hack](http://sourcefoundry.org/hack/)

## SpaceGray Colors ##

### PHP Example ###
![Php example](http://i.imgur.com/Bb3gp3d.png)

### HTML Example ###
![HTML example](http://i.imgur.com/LLfVGdA.png)

----------

## Eighties Colors ##

### PHP Example ###
![PHP Eaxmple](http://i.imgur.com/y62LMf6.png)

### HTML Example ###

![HTML Example](http://i.imgur.com/lwWGRo8.png)
## Installation ##

- Place the `Spacegray.icls` and `Eighties.icls` file in your phpStorm folder paths are given below.
- Then go to `File` -> `Settings` -> `Editor` -> `Colors & Fonts`
- Select the `Spacegray` or `Eighties` theme from the drop down list
- Restart the phpStorm
- Install color IDE plugin to change the color of sidebar.

### Ubuntu Linux ###

    For phpstorm version 8.x
    cd ~/.WebIde80/config/colors
    For phpstorm version 9.x
    cd ~/.WebIde90/config/colors

### Mac OS X ###

    For phpstorm version 8.x
    cd ~/Library/Preferences/WebIde80/colors/
    For phpstorm version 9.x
    cd ~/Library/Preferences/WebIde90/colors/

### Windows ###

    For phpstorm version 8.x
    c:/Users/USERNAME/.WebIde70/config/colors
    For phpstorm version 9.x
    c:/Users/USERNAME/.WebIde90/config/colors

# Contribute

Feel free to contribute


text:
        Product Assignments for {{categoryAssignProd.Category.Name}}

    <ordercloud-search servicename="Products" controlleras="categoryAssignProd"></ordercloud-search>

        The selected buyer does not have any products,
        create one now

                <colgroup>
                    <col class="action-column"/>
                </colgroup>

ID

Name

                        <input name="{{'product_assign_' + $index}}"  type="checkbox" ng-model="product.selected">

                    {{product.ID}}
                    {{product.Name}}

        <button type="button" class="btn btn-default" ui-sref="^"> Back</button>
        <button type="button" class="btn btn-primary" ng-click="categoryAssignProd.saveAssignments()">Update Product Assignments</button>
        <button type="button" class="btn btn-default" ui-sref="^.assignParty({categoryid: categoryAssignProd.Category.ID})">Assign Parties</button>