text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.maps.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

/** Metric specification of operation. */
@Fluent
public final class MetricSpecification {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(MetricSpecification.class);

    /*
     * Name of metric specification.
     */
    @JsonProperty(value = "name")
    private String name;

    /*
     * Display name of metric specification.
     */
    @JsonProperty(value = "displayName")
    private String displayName;

    /*
     * Display description of metric specification.
     */
    @JsonProperty(value = "displayDescription")
    private String displayDescription;

    /*
     * Unit could be Count.
     */
    @JsonProperty(value = "unit")
    private String unit;

    /*
     * Dimensions of map account.
     */
    @JsonProperty(value = "dimensions")
    private List<Dimension> dimensions;

    /*
     * Aggregation type could be Average.
     */
    @JsonProperty(value = "aggregationType")
    private String aggregationType;

    /*
     * The property to decide fill gap with zero or not.
     */
    @JsonProperty(value = "fillGapWithZero")
    private Boolean fillGapWithZero;

    /*
     * The category this metric specification belong to, could be Capacity.
     */
    @JsonProperty(value = "category")
    private String category;

    /*
     * Account Resource Id.
     */
    @JsonProperty(value = "resourceIdDimensionNameOverride")
    private String resourceIdDimensionNameOverride;

    /**
     * Get the name property: Name of metric specification.
     *
     * @return the name value.
     */
    public String name() {
        return this.name;
    }

    /**
     * Set the name property: Name of metric specification.
     *
     * @param name the name value to set.
     * @return the MetricSpecification object itself.
     */
    public MetricSpecification withName(String name) {
        this.name = name;
        return this;
    }

    /**
     * Get the displayName property: Display name of metric specification.
     *
     * @return the displayName value.
     */
    public String displayName() {
        return this.displayName;
    }

    /**
     * Set the displayName property: Display name of metric specification.
     *
     * @param displayName the displayName value to set.
     * @return the MetricSpecification object itself.
     */
    public MetricSpecification withDisplayName(String displayName) {
        this.displayName = displayName;
        return this;
    }

    /**
     * Get the displayDescription property: Display description of metric specification.
     *
     * @return the displayDescription value.
     */
    public String displayDescription() {
        return this.displayDescription;
    }

    /**
     * Set the displayDescription property: Display description of metric specification.
     *
     * @param displayDescription the displayDescription value to set.
     * @return the MetricSpecification object itself.
     */
    public MetricSpecification withDisplayDescription(String displayDescription) {
        this.displayDescription = displayDescription;
        return this;
    }

    /**
     * Get the unit property: Unit could be Count.
     *
     * @return the unit value.
     */
    public String unit() {
        return this.unit;
    }

    /**
     * Set the unit property: Unit could be Count.
     *
     * @param unit the unit value to set.
     * @return the MetricSpecification object itself.
     */
    public MetricSpecification withUnit(String unit) {
        this.unit = unit;
        return this;
    }

    /**
     * Get the dimensions property: Dimensions of map account.
     *
     * @return the dimensions value.
     */
    public List<Dimension> dimensions() {
        return this.dimensions;
    }

    /**
     * Set the dimensions property: Dimensions of map account.
     *
     * @param dimensions the dimensions value to set.
     * @return the MetricSpecification object itself.
     */
    public MetricSpecification withDimensions(List<Dimension> dimensions) {
        this.dimensions = dimensions;
        return this;
    }

    /**
     * Get the aggregationType property: Aggregation type could be Average.
     *
     * @return the aggregationType value.
     */
    public String aggregationType() {
        return this.aggregationType;
    }

    /**
     * Set the aggregationType property: Aggregation type could be Average.
     *
     * @param aggregationType the aggregationType value to set.
     * @return the MetricSpecification object itself.
     */
    public MetricSpecification withAggregationType(String aggregationType) {
        this.aggregationType = aggregationType;
        return this;
    }

    /**
     * Get the fillGapWithZero property: The property to decide fill gap with zero or not.
     *
     * @return the fillGapWithZero value.
     */
    public Boolean fillGapWithZero() {
        return this.fillGapWithZero;
    }

    /**
     * Set the fillGapWithZero property: The property to decide fill gap with zero or not.
     *
     * @param fillGapWithZero the fillGapWithZero value to set.
     * @return the MetricSpecification object itself.
     */
    public MetricSpecification withFillGapWithZero(Boolean fillGapWithZero) {
        this.fillGapWithZero = fillGapWithZero;
        return this;
    }

    /**
     * Get the category property: The category this metric specification belong to, could be Capacity.
     *
     * @return the category value.
     */
    public String category() {
        return this.category;
    }

    /**
     * Set the category property: The category this metric specification belong to, could be Capacity.
     *
     * @param category the category value to set.
     * @return the MetricSpecification object itself.
     */
    public MetricSpecification withCategory(String category) {
        this.category = category;
        return this;
    }

    /**
     * Get the resourceIdDimensionNameOverride property: Account Resource Id.
     *
     * @return the resourceIdDimensionNameOverride value.
     */
    public String resourceIdDimensionNameOverride() {
        return this.resourceIdDimensionNameOverride;
    }

    /**
     * Set the resourceIdDimensionNameOverride property: Account Resource Id.
     *
     * @param resourceIdDimensionNameOverride the resourceIdDimensionNameOverride value to set.
     * @return the MetricSpecification object itself.
     */
    public MetricSpecification withResourceIdDimensionNameOverride(String resourceIdDimensionNameOverride) {
        this.resourceIdDimensionNameOverride = resourceIdDimensionNameOverride;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (dimensions() != null) {
            dimensions().forEach(e -> e.validate());
        }
    }
}


text:
namespace gbase {

// Conversions between numeric keys/values and the types expected by Cache.
static std::string EncodeKey(int k) {
  std::string result;
  PutFixed32(&result, k);
  return result;
}
static int DecodeKey(const StringPiece& k) {
  assert(k.size() == 4);
  return DecodeFixed32(k.data());
}
static void* EncodeValue(uintptr_t v) { return reinterpret_cast<void*>(v); }
static int DecodeValue(void* v) { return reinterpret_cast<uintptr_t>(v); }

class CacheTest {
 public:
  static CacheTest* current_;

  static void Deleter(const StringPiece& key, void* v) {
    current_->deleted_keys_.push_back(DecodeKey(key));
    current_->deleted_values_.push_back(DecodeValue(v));
  }

  static const int kCacheSize = 1000;
  std::vector<int> deleted_keys_;
  std::vector<int> deleted_values_;
  Cache* cache_;

  CacheTest() : cache_(NewLRUCache(kCacheSize)) {
    current_ = this;
  }

  ~CacheTest() {
    delete cache_;
  }

  int Lookup(int key) {
    Cache::Handle* handle = cache_->Lookup(EncodeKey(key));
    const int r = (handle == NULL) ? -1 : DecodeValue(cache_->Value(handle));
    if (handle != NULL) {
      cache_->Release(handle);
    }
    return r;
  }

  void Insert(int key, int value, int charge = 1) {
    cache_->Release(cache_->Insert(EncodeKey(key), EncodeValue(value), charge,
                                   &CacheTest::Deleter));
  }

  Cache::Handle* InsertAndReturnHandle(int key, int value, int charge = 1) {
    return cache_->Insert(EncodeKey(key), EncodeValue(value), charge,
                          &CacheTest::Deleter);
  }

  void Erase(int key) {
    cache_->Erase(EncodeKey(key));
  }
};
CacheTest* CacheTest::current_;

TEST(CacheTest, HitAndMiss) {
  CacheTest ct;
  ASSERT_EQ(-1, ct.Lookup(100));

  ct.Insert(100, 101);
  ASSERT_EQ(101, ct.Lookup(100));
  ASSERT_EQ(-1,  ct.Lookup(200));
  ASSERT_EQ(-1,  ct.Lookup(300));

  ct.Insert(200, 201);
  ASSERT_EQ(101, ct.Lookup(100));
  ASSERT_EQ(201, ct.Lookup(200));
  ASSERT_EQ(-1,  ct.Lookup(300));

  ct.Insert(100, 102);
  ASSERT_EQ(102, ct.Lookup(100));
  ASSERT_EQ(201, ct.Lookup(200));
  ASSERT_EQ(-1,  ct.Lookup(300));

  ASSERT_EQ(1, ct.deleted_keys_.size());
  ASSERT_EQ(100, ct.deleted_keys_[0]);
  ASSERT_EQ(101, ct.deleted_values_[0]);
}

TEST(CacheTest, Erase) {
  CacheTest ct;
  ct.Erase(200);
  ASSERT_EQ(0, ct.deleted_keys_.size());

  ct.Insert(100, 101);
  ct.Insert(200, 201);
  ct.Erase(100);
  ASSERT_EQ(-1,  ct.Lookup(100));
  ASSERT_EQ(201, ct.Lookup(200));
  ASSERT_EQ(1, ct.deleted_keys_.size());
  ASSERT_EQ(100, ct.deleted_keys_[0]);
  ASSERT_EQ(101, ct.deleted_values_[0]);

  ct.Erase(100);
  ASSERT_EQ(-1,  ct.Lookup(100));
  ASSERT_EQ(201, ct.Lookup(200));
  ASSERT_EQ(1, ct.deleted_keys_.size());
}

TEST(CacheTest, EntriesArePinned) {
  CacheTest ct;
  ct.Insert(100, 101);
  Cache::Handle* h1 = ct.cache_->Lookup(EncodeKey(100));
  ASSERT_EQ(101, DecodeValue(ct.cache_->Value(h1)));

  ct.Insert(100, 102);
  Cache::Handle* h2 = ct.cache_->Lookup(EncodeKey(100));
  ASSERT_EQ(102, DecodeValue(ct.cache_->Value(h2)));
  ASSERT_EQ(0, ct.deleted_keys_.size());

  ct.cache_->Release(h1);
  ASSERT_EQ(1, ct.deleted_keys_.size());
  ASSERT_EQ(100, ct.deleted_keys_[0]);
  ASSERT_EQ(101, ct.deleted_values_[0]);

  ct.Erase(100);
  ASSERT_EQ(-1, ct.Lookup(100));
  ASSERT_EQ(1, ct.deleted_keys_.size());

  ct.cache_->Release(h2);
  ASSERT_EQ(2, ct.deleted_keys_.size());
  ASSERT_EQ(100, ct.deleted_keys_[1]);
  ASSERT_EQ(102, ct.deleted_values_[1]);
}

TEST(CacheTest, EvictionPolicy) {
  CacheTest ct;
  ct.Insert(100, 101);
  ct.Insert(200, 201);
  ct.Insert(300, 301);
  Cache::Handle* h = ct.cache_->Lookup(EncodeKey(300));

  // Frequently used entry must be kept around,
  // as must things that are still in use.
  for (int i = 0; i < ct.kCacheSize + 100; i++) {
    ct.Insert(1000+i, 2000+i);
    ASSERT_EQ(2000+i, ct.Lookup(1000+i));
    ASSERT_EQ(101, ct.Lookup(100));
  }
  ASSERT_EQ(101, ct.Lookup(100));
  ASSERT_EQ(-1, ct.Lookup(200));
  ASSERT_EQ(301, ct.Lookup(300));
  ct.cache_->Release(h);
}

TEST(CacheTest, UseExceedsCacheSize) {
  // Overfill the cache, keeping handles on all inserted entries.
  std::vector<Cache::Handle*> h;
  CacheTest ct;
  for (int i = 0; i < CacheTest::kCacheSize + 100; i++) {
    h.push_back(ct.InsertAndReturnHandle(1000+i, 2000+i));
  }

  // Check that all the entries can be found in the cache.
  for (int i = 0; i < h.size(); i++) {
    ASSERT_EQ(2000+i, ct.Lookup(1000+i));
  }

  for (int i = 0; i < h.size(); i++) {
    ct.cache_->Release(h[i]);
  }
}

TEST(CacheTest, HeavyEntries) {
  // Add a bunch of light and heavy entries and then count the combined
  // size of items still in the cache, which must be approximately the
  // same as the total capacity.
  const int kLight = 1;
  const int kHeavy = 10;
  int added = 0;
  int index = 0;
  CacheTest ct;
  while (added < 2*ct.kCacheSize) {
    const int weight = (index & 1) ? kLight : kHeavy;
    ct.Insert(index, 1000+index, weight);
    added += weight;
    index++;
  }

  int cached_weight = 0;
  for (int i = 0; i < index; i++) {
    const int weight = (i & 1 ? kLight : kHeavy);
    int r = ct.Lookup(i);
    if (r >= 0) {
      cached_weight += weight;
      ASSERT_EQ(1000+i, r);
    }
  }
  ASSERT_LE(cached_weight, ct.kCacheSize + ct.kCacheSize/10);
}

TEST(CacheTest, NewId) {
  CacheTest ct;
  uint64_t a = ct.cache_->NewId();
  uint64_t b = ct.cache_->NewId();
  ASSERT_NE(a, b);
}

TEST(CacheTest, Prune) {
  CacheTest ct;
  ct.Insert(1, 100);
  ct.Insert(2, 200);

  Cache::Handle* handle = ct.cache_->Lookup(EncodeKey(1));
  ASSERT_TRUE(handle);
  ct.cache_->Prune();
  ct.cache_->Release(handle);

  ASSERT_EQ(100, ct.Lookup(1));
  ASSERT_EQ(-1, ct.Lookup(2));
}

}  // namespace gbase

redpajama_set_name: RedPajamaGithub


text:
/**
 *
 */
package com.sqli.echallenge.jformation.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.springframework.stereotype.Component;

/**
 * @author Mouad
 *
 */
@Component
public class ActionHelper {
	private static final String ACTIONS_PATH = "/util/actions.properties";

	public String getAction(String key){
		Properties prop = new Properties();
		InputStream input = null;

		try {
			//get file ressource
			input = ActionHelper.class.getResourceAsStream(ACTIONS_PATH);

			//load a properties file
			prop.load(input);

			//get action for key
			return prop.getProperty(key);

		} catch (IOException ex) {

		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {}
			}
		}
		return null;
	}
}


text:
#ifndef PROTOZERO_PBF_MESSAGE_HPP
#define PROTOZERO_PBF_MESSAGE_HPP

/*****************************************************************************

protozero - Minimalistic protocol buffer decoder and encoder in C++.

This file is from https://github.com/mapbox/protozero where you can find more
documentation.

*****************************************************************************/

/**
 * @file pbf_message.hpp
 *
 * @brief Contains the pbf_message template class.
 */

#include "pbf_reader.hpp"
#include "types.hpp"

#include <type_traits>

namespace protozero {

/**
 * This class represents a protobuf message. Either a top-level message or
 * a nested sub-message. Top-level messages can be created from any buffer
 * with a pointer and length:
 *
 * @code
 *    enum class Message : protozero::pbf_tag_type {
 *       ...
 *    };
 *
 *    std::string buffer;
 *    // fill buffer...
 *    pbf_message<Message> message{buffer.data(), buffer.size()};
 * @endcode
 *
 * Sub-messages are created using get_message():
 *
 * @code
 *    enum class SubMessage : protozero::pbf_tag_type {
 *       ...
 *    };
 *
 *    pbf_message<Message> message{...};
 *    message.next();
 *    pbf_message<SubMessage> submessage = message.get_message();
 * @endcode
 *
 * All methods of the pbf_message class except get_bytes() and get_string()
 * provide the strong exception guarantee, ie they either succeed or do not
 * change the pbf_message object they are called on. Use the get_data() method
 * instead of get_bytes() or get_string(), if you need this guarantee.
 *
 * This template class is based on the pbf_reader class and has all the same
 * methods. The difference is that whereever the pbf_reader class takes an
 * integer tag, this template class takes a tag of the template type T.
 *
 * Read the tutorial to understand how this class is used.
 */
template <typename T>
class pbf_message : public pbf_reader {

    static_assert(std::is_same<pbf_tag_type, typename std::underlying_type<T>::type>::value,
                  "T must be enum with underlying type protozero::pbf_tag_type");

public:

    /// The type of messages this class will read.
    using enum_type = T;

    /**
     * Construct a pbf_message. All arguments are forwarded to the pbf_reader
     * parent class.
     */
    template <typename... Args>
    pbf_message(Args&&... args) noexcept : // NOLINT(google-explicit-constructor, hicpp-explicit-conversions)
        pbf_reader{std::forward<Args>(args)...} {
    }

    /**
     * Set next field in the message as the current field. This is usually
     * called in a while loop:
     *
     * @code
     *    pbf_message<...> message(...);
     *    while (message.next()) {
     *        // handle field
     *    }
     * @endcode
     *
     * @returns `true` if there is a next field, `false` if not.
     * @pre There must be no current field.
     * @post If it returns `true` there is a current field now.
     */
    bool next() {
        return pbf_reader::next();
    }

    /**
     * Set next field with given tag in the message as the current field.
     * Fields with other tags are skipped. This is usually called in a while
     * loop for repeated fields:
     *
     * @code
     *    pbf_message<Example1> message{...};
     *    while (message.next(Example1::repeated_fixed64_r)) {
     *        // handle field
     *    }
     * @endcode
     *
     * or you can call it just once to get the one field with this tag:
     *
     * @code
     *    pbf_message<Example1> message{...};
     *    if (message.next(Example1::required_uint32_x)) {
     *        // handle field
     *    }
     * @endcode
     *
     * Note that this will not check the wire type. The two-argument version
     * of this function will also check the wire type.
     *
     * @returns `true` if there is a next field with this tag.
     * @pre There must be no current field.
     * @post If it returns `true` there is a current field now with the given tag.
     */
    bool next(T next_tag) {
        return pbf_reader::next(pbf_tag_type(next_tag));
    }

    /**
     * Set next field with given tag and wire type in the message as the
     * current field. Fields with other tags are skipped. This is usually
     * called in a while loop for repeated fields:
     *
     * @code
     *    pbf_message<Example1> message{...};
     *    while (message.next(Example1::repeated_fixed64_r, pbf_wire_type::varint)) {
     *        // handle field
     *    }
     * @endcode
     *
     * or you can call it just once to get the one field with this tag:
     *
     * @code
     *    pbf_message<Example1> message{...};
     *    if (message.next(Example1::required_uint32_x, pbf_wire_type::varint)) {
     *        // handle field
     *    }
     * @endcode
     *
     * Note that this will also check the wire type. The one-argument version
     * of this function will not check the wire type.
     *
     * @returns `true` if there is a next field with this tag.
     * @pre There must be no current field.
     * @post If it returns `true` there is a current field now with the given tag.
     */
    bool next(T next_tag, pbf_wire_type type) {
        return pbf_reader::next(pbf_tag_type(next_tag), type);
    }

    /**
     * The tag of the current field. The tag is the enum value for the field
     * number from the description in the .proto file.
     *
     * Call next() before calling this function to set the current field.
     *
     * @returns tag of the current field.
     * @pre There must be a current field (ie. next() must have returned `true`).
     */
    T tag() const noexcept {
        return T(pbf_reader::tag());
    }

}; // class pbf_message

} // end namespace protozero

#endif // PROTOZERO_PBF_MESSAGE_HPP


text:
<!DOCTYPE html>

  <title>HTTP charset</title>
<link rel='author' title='Richard Ishida' href='mailto:ishida@w3.org'>
<link rel='help' href='http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream'>
<link rel="stylesheet" type="text/css" href="./generatedtests.css">

<meta name='flags' content='http'>
<meta name="assert" content="The character encoding of a page can be set using the HTTP header charset declaration.">

<link rel="stylesheet" type="text/css" href="the-input-byte-stream/support/encodingtests-15.css">

HTTP charset

The character encoding of a page can be set using the HTTP header charset declaration.

The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector .test div.ÃœÃ€Ãš. This matches the sequence of bytes above when they are interpreted as ISO 8859-15. If the class name matches the selector then the test will pass.

The only character encoding declaration for this HTML file is in the HTTP header, which sets the encoding to ISO 8859-15.

Next test

HTML5

the-input-byte-stream-001
Result summary & related tests
Detailed results for this test
	Link to spec

Assumptions:

The default encoding for the browser you are testing is not set to ISO 8859-15.

The test is read from a server that supports HTTP.


text:
class SessionsController < ApplicationController

  skip_before_action :authorize, only: [:new, :create]

  def new
  end

  def create
    @user = User.find_or_create_from_auth_hash(auth_hash)
    login(@user)
    redirect_to '/'
  end

  def destroy
    session[:user_id] = nil
    flash[:success] = 'Signed out!'
    redirect_to signin_path
  end

  private
    def auth_hash
      request.env['omniauth.auth']
    end
end


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Revis. gen. pl. (Leipzig) 3(2): 515 (1898)

#### Original name
Hexagonia friesiana Speg., 1884

### Remarks
null


text:
package application;

import javafx.application.Application;
import javafx.stage.Stage;

public class Main extends Application {
	@Override
	public void start(Stage primaryStage) {
		try {
			setUserAgentStylesheet(STYLESHEET_CASPIAN);
			UI ui = new UI();
			primaryStage.setScene(ui.scene);
			primaryStage.setResizable(false);
			primaryStage.show();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		launch(args);
	}
}


text:
require "features2cards/platform"
require "features2cards/cli"

module Features2Cards#:nodoc:
  class VERSION #:nodoc:
    MAJOR = 0
    MINOR = 4
    TINY  = 0
    PATCH = nil # Set to nil for official release

    STRING = [MAJOR, MINOR, TINY, PATCH].compact.join('.')
    STABLE_STRING = [MAJOR, MINOR, TINY].join('.')
  end
end


text:
SYNONYM

#### According to
GRIN Taxonomy for Plants

#### Published in
J. Bellenden Ker, Bot. Reg. 6: t. 451. 1820

#### Original name
null

### Remarks
null


text:
from django.test import SimpleTestCase

from localflavor.lv.forms import LVMunicipalitySelect, LVPersonalCodeField, LVPostalCodeField

class LVLocalFlavorTests(SimpleTestCase):
    def test_LVPersonalCodeField(self):
        invalid_format = ['Enter a Latvian personal code in format XXXXXX-XXXXX.']
        invalid = ['Enter a valid Latvian personal code.']

        valid = {
            '261155-10410': '261155-10410',
            '010100-10005': '010100-10005',  # smallest valid code
            '311299-29999': '311299-29999',  # greatest valid code
            '290212-21232': '290212-21232',  # leap year
        }
        invalid = {
            '26115510410': invalid_format,  # missing dash
            '261155-90414': invalid_format,  # invalid century
            '123456-12345': invalid,  # invalid checksum
            '310200-10006': invalid,  # invalid date
            '000000-10007': invalid,  # invalid day/month
            '290214-21234': invalid,  # not leap year
        }

        self.assertFieldOutput(LVPersonalCodeField, valid, invalid)

    def test_LVPostalCodeField(self):
        invalid = [LVPostalCodeField().error_messages['invalid']]

        valid = {
            'LV-1023': 'LV-1023',
            'lv - 5750': 'LV-5750',
            '3036': 'LV-3036',
        }
        invalid = {
            '123': invalid,
            '12345': invalid,
            'LV-12345': invalid,
            '0123': invalid,  # out of range
            'LV-9999': invalid,  # out of range
        }
        self.assertFieldOutput(LVPostalCodeField, valid, invalid)

    def test_LVMunicipalitySelect(self):
        f = LVMunicipalitySelect()
        expected = '''
<select name="municipality">
<option value="DGV">Daugavpils</option>
<option value="JEL">Jelgava</option>
<option value="JKB">Jēkabpils</option>
<option value="JUR">Jūrmala</option>
<option value="LPX">Liepāja</option>
<option value="REZ">Rēzekne</option>
<option value="RIX">Riga</option>
<option value="VMR">Valmiera</option>
<option value="VEN">Ventspils</option>
<option value="001">Aglona municipality</option>
<option value="002">Aizkraukle municipality</option>
<option value="003">Aizpute municipality</option>
<option value="004">Aknīste municipality</option>
<option value="005">Aloja municipality</option>
<option value="006">Alsunga municipality</option>
<option value="007">Alūksne municipality</option>
<option value="008">Amata municipality</option>
<option value="009">Ape municipality</option>
<option value="010">Auce municipality</option>
<option value="011">Ādaži municipality</option>
<option value="012">Babīte municipality</option>
<option value="013">Baldone municipality</option>
<option value="014">Baltinava municipality</option>
<option value="015">Balvi municipality</option>
<option value="016">Bauska municipality</option>
<option value="017">Beverīna municipality</option>
<option value="018">Brocēni municipality</option>
<option value="019">Burtnieki municipality</option>
<option value="020">Carnikava municipality</option>
<option value="021">Cesvaine municipality</option>
<option value="022">Cēsis municipality</option>
<option value="023">Cibla municipality</option>
<option value="024">Dagda municipality</option>
<option value="025">Daugavpils municipality</option>
<option value="026">Dobele municipality</option>
<option value="027">Dundaga municipality</option>
<option value="028">Durbe municipality</option>
<option value="029">Engure municipality</option>
<option value="030">Ērgļi municipality</option>
<option value="031">Garkalne municipality</option>
<option value="032">Grobiņa municipality</option>
<option value="033">Gulbene municipality</option>
<option value="034">Iecava municipality</option>
<option value="035">Ikšķile municipality</option>
<option value="036">Ilūkste municipality</option>
<option value="037">Inčukalns municipality</option>
<option value="038">Jaunjelgava municipality</option>
<option value="039">Jaunpiebalga municipality</option>
<option value="040">Jaunpils municipality</option>
<option value="041">Jelgava municipality</option>
<option value="042">Jēkabpils municipality</option>
<option value="043">Kandava municipality</option>
<option value="044">Kārsava municipality</option>
<option value="045">Kocēni municipality</option>
<option value="046">Koknese municipality</option>
<option value="047">Krāslava municipality</option>
<option value="048">Krimulda municipality</option>
<option value="049">Krustpils municipality</option>
<option value="050">Kuldīga municipality</option>
<option value="051">Ķegums municipality</option>
<option value="052">Ķekava municipality</option>
<option value="053">Lielvārde municipality</option>
<option value="054">Limbaži municipality</option>
<option value="055">Līgatne municipality</option>
<option value="056">Līvāni municipality</option>
<option value="057">Lubāna municipality</option>
<option value="058">Ludza municipality</option>
<option value="059">Madona municipality</option>
<option value="060">Mazsalaca municipality</option>
<option value="061">Mālpils municipality</option>
<option value="062">Mārupe municipality</option>
<option value="063">Mērsrags municipality</option>
<option value="064">Naukšēni municipality</option>
<option value="065">Nereta municipality</option>
<option value="066">Nīca municipality</option>
<option value="067">Ogre municipality</option>
<option value="068">Olaine municipality</option>
<option value="069">Ozolnieki municipality</option>
<option value="070">Pārgauja municipality</option>
<option value="071">Pāvilosta municipality</option>
<option value="072">Pļaviņas municipality</option>
<option value="073">Preiļi municipality</option>
<option value="074">Priekule municipality</option>
<option value="075">Priekuļi municipality</option>
<option value="076">Rauna municipality</option>
<option value="077">Rēzekne municipality</option>
<option value="078">Riebiņi municipality</option>
<option value="079">Roja municipality</option>
<option value="080">Ropaži municipality</option>
<option value="081">Rucava municipality</option>
<option value="082">Rugāji municipality</option>
<option value="083">Rundāle municipality</option>
<option value="084">Rūjiena municipality</option>
<option value="085">Sala municipality</option>
<option value="086">Salacgrīva municipality</option>
<option value="087">Salaspils municipality</option>
<option value="088">Saldus municipality</option>
<option value="089">Saulkrasti municipality</option>
<option value="090">Sēja municipality</option>
<option value="091">Sigulda municipality</option>
<option value="092">Skrīveri municipality</option>
<option value="093">Skrunda municipality</option>
<option value="094">Smiltene municipality</option>
<option value="095">Stopiņi municipality</option>
<option value="096">Strenči municipality</option>
<option value="097">Talsi municipality</option>
<option value="098">Tērvete municipality</option>
<option value="099">Tukums municipality</option>
<option value="100">Vaiņode municipality</option>
<option value="101">Valka municipality</option>
<option value="102">Varakļāni municipality</option>
<option value="103">Vārkava municipality</option>
<option value="104">Vecpiebalga municipality</option>
<option value="105">Vecumnieki municipality</option>
<option value="106">Ventspils municipality</option>
<option value="107">Viesīte municipality</option>
<option value="108">Viļaka municipality</option>
<option value="109">Viļāni municipality</option>
<option value="110">Zilupe municipality</option>
</select>'''
        self.assertHTMLEqual(f.render('municipality', None), expected)


text:
package com.shiznatix.mediacomrade.android.tables;

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

import com.shiznatix.mediacomrade.android.entities.RandomShow;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class RandomShowsTable extends AbstractTables {
	static private final String LOG_TAG = "mc_RandomSettingsTable";

	protected static final String TABLE_NAME = "randomShows";

	protected static final String KEY_ID = "randomShowid";
	protected static final String KEY_TITLE = "title";

	public RandomShowsTable(Context context) {
		super(context);
	}

	public void addShow(String title) {
		SQLiteDatabase db = getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put(KEY_TITLE, title);

		db.insert(TABLE_NAME, null, values);
		db.close();
	}

	public RandomShow getShow(int id) {
		SQLiteDatabase db = getReadableDatabase();

		Cursor cursor = db.query(TABLE_NAME, new String[] { KEY_ID, KEY_TITLE }, KEY_ID+" = ?", new String[] { String.valueOf(id) }, null, null, null, null);

		if (cursor.getCount() > 0) {
			cursor.moveToFirst();

			RandomShow randomShow = new RandomShow(cursor.getInt(0), cursor.getString(1));

			db.close();
			cursor.close();

			return randomShow;
		}

		db.close();
		cursor.close();

	    return null;
	}

	public RandomShow getShowByTitle(String title) {
		SQLiteDatabase db = getReadableDatabase();
		Cursor cursor = db.query(TABLE_NAME, new String[] { KEY_ID, KEY_TITLE }, KEY_TITLE+" = ?", new String[] { title }, null, null, null, null);

		if (cursor.getCount() > 0) {
			cursor.moveToFirst();

			RandomShow randomShow = new RandomShow(cursor.getInt(0), cursor.getString(1));

			db.close();
			cursor.close();

			return randomShow;
		}

		db.close();
		cursor.close();

	    return null;
	}

	public List<RandomShow> getAllShows() {
		List<RandomShow> randomShowList = new ArrayList<RandomShow>();

		String selectQuery = "SELECT * FROM "+TABLE_NAME;

		SQLiteDatabase db = getWritableDatabase();
		Cursor cursor = db.rawQuery(selectQuery, null);

		if (cursor.moveToFirst()) {
			do {
				RandomShow randomShow = new RandomShow(cursor.getInt(0), cursor.getString(1));

				randomShowList.add(randomShow);
			}
			while (cursor.moveToNext());
		}

		db.close();
		cursor.close();

		return randomShowList;
	}

	public List<String> getAllShowTitles() {
		List<String> randomShowTitles = new ArrayList<String>();

		String selectQuery = "SELECT "+KEY_TITLE+" FROM "+TABLE_NAME;

		SQLiteDatabase db = getWritableDatabase();
		Cursor cursor = db.rawQuery(selectQuery, null);

		if (cursor.moveToFirst()) {
			do {
				randomShowTitles.add(cursor.getString(0));
			}
			while (cursor.moveToNext());
		}

		db.close();
		cursor.close();

		return randomShowTitles;
	}

	public void deleteShow(RandomShow randomShow) {
		SQLiteDatabase db = getWritableDatabase();
		db.delete(TABLE_NAME, KEY_ID+" = ?", new String[] { String.valueOf(randomShow.randomShowid) });
		db.close();

		Log.i(LOG_TAG, "show deleted");
	}
}


text:
package com.squareup.picasso;

import android.app.Notification;
import android.app.NotificationManager;
import android.appwidget.AppWidgetManager;
import android.graphics.Bitmap;
import android.widget.RemoteViews;

import static android.content.Context.NOTIFICATION_SERVICE;
import static com.squareup.picasso.Utils.getService;

abstract class RemoteViewsAction extends Action<RemoteViewsAction.RemoteViewsTarget> {
  final RemoteViews remoteViews;
  final int viewId;
  Callback callback;

  private RemoteViewsTarget target;

  RemoteViewsAction(Picasso picasso, Request data, RemoteViews remoteViews, int viewId,
      int errorResId, int memoryPolicy, int networkPolicy, Object tag, String key,
      Callback callback) {
    super(picasso, null, data, memoryPolicy, networkPolicy, errorResId, null, key, tag, false);
    this.remoteViews = remoteViews;
    this.viewId = viewId;
    this.callback = callback;
  }

  @Override void complete(Bitmap result, Picasso.LoadedFrom from) {
    remoteViews.setImageViewBitmap(viewId, result);
    update();
    if (callback != null) {
      callback.onSuccess();
    }
  }

  @Override void cancel() {
    super.cancel();
    if (callback != null) {
      callback = null;
    }
  }

  @Override public void error() {
    if (errorResId != 0) {
      setImageResource(errorResId);
    }
    if (callback != null) {
      callback.onError();
    }
  }

  @Override RemoteViewsTarget getTarget() {
    if (target == null) {
      target = new RemoteViewsTarget(remoteViews, viewId);
    }
    return target;
  }

  void setImageResource(int resId) {
    remoteViews.setImageViewResource(viewId, resId);
    update();
  }

  abstract void update();

  static class RemoteViewsTarget {
    final RemoteViews remoteViews;
    final int viewId;

    RemoteViewsTarget(RemoteViews remoteViews, int viewId) {
      this.remoteViews = remoteViews;
      this.viewId = viewId;
    }

    @Override public boolean equals(Object o) {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;
      RemoteViewsTarget remoteViewsTarget = (RemoteViewsTarget) o;
      return viewId == remoteViewsTarget.viewId && remoteViews.equals(
          remoteViewsTarget.remoteViews);
    }

    @Override public int hashCode() {
      return 31 * remoteViews.hashCode() + viewId;
    }
  }

  static class AppWidgetAction extends RemoteViewsAction {
    private final int[] appWidgetIds;

    AppWidgetAction(Picasso picasso, Request data, RemoteViews remoteViews, int viewId,
        int[] appWidgetIds, int memoryPolicy, int networkPolicy, String key, Object tag,
        int errorResId, Callback callback) {
      super(picasso, data, remoteViews, viewId, errorResId, memoryPolicy, networkPolicy, tag, key,
          callback);
      this.appWidgetIds = appWidgetIds;
    }

    @Override void update() {
      AppWidgetManager manager = AppWidgetManager.getInstance(picasso.context);
      manager.updateAppWidget(appWidgetIds, remoteViews);
    }
  }

  static class NotificationAction extends RemoteViewsAction {
    private final int notificationId;
    private final String notificationTag;
    private final Notification notification;

    NotificationAction(Picasso picasso, Request data, RemoteViews remoteViews, int viewId,
        int notificationId, Notification notification, String notificationTag, int memoryPolicy,
        int networkPolicy, String key, Object tag, int errorResId, Callback callback) {
      super(picasso, data, remoteViews, viewId, errorResId, memoryPolicy, networkPolicy, tag, key,
          callback);
      this.notificationId = notificationId;
      this.notificationTag = notificationTag;
      this.notification = notification;
    }

    @Override void update() {
      NotificationManager manager = getService(picasso.context, NOTIFICATION_SERVICE);
      manager.notify(notificationTag, notificationId, notification);
    }
  }
}


text:
SET(UEYE_SDK_ROOT_DIR
    "${UEYE_SDK_ROOT_DIR}"
    CACHE
    PATH
    "Root directory to search for UEye SDK")

# Look for the header file.
FIND_PATH(UEYE_SDK_INCLUDE_DIRS NAMES uEye.h HINTS
	${UEYE_SDK_ROOT_DIR}/include )

FIND_PATH(UEYE_SDK_INCLUDE_DIRS NAMES uEye.h HINTS
	${UEYE_SDK_ROOT_DIR}/include )

# Determine architecture
IF(CMAKE_SIZEOF_VOID_P MATCHES "8")
	FIND_LIBRARY(UEYE_SDK_LIBRARY NAMES uEye_api_64 ueye_tools_64 HINTS ${UEYE_SDK_ROOT_DIR} ${UEYE_SDK_ROOT_DIR}/Lib)
	FIND_LIBRARY(UEYE_SDK_LIBRARY_DEBUG NAMES uEye_api_64 ueye_tools_64 HINTS ${UEYE_SDK_ROOT_DIR} ${UEYE_SDK_ROOT_DIR}/Lib)
ELSE()
    # Look for the library.
	FIND_LIBRARY(UEYE_SDK_LIBRARY NAMES uEye_api uEye_tools HINTS ${UEYE_SDK_ROOT_DIR} ${UEYE_SDK_ROOT_DIR}/Lib)
	FIND_LIBRARY(UEYE_SDK_LIBRARY_DEBUG NAMES uEye_api uEye_tools HINTS ${UEYE_SDK_ROOT_DIR} ${UEYE_SDK_ROOT_DIR}/Lib)
ENDIF()

MARK_AS_ADVANCED(UEYE_SDK_LIBRARY)
MARK_AS_ADVANCED(UEYE_SDK_LIBRARY_DEBUG)

SET(UEYE_SDK_LIBRARIES optimized ${UEYE_SDK_LIBRARY} debug ${UEYE_SDK_LIBRARY_DEBUG})

# handle the QUIETLY and REQUIRED arguments and set UEYE_SDK_FOUND to TRUE if
# all listed variables are TRUE
INCLUDE(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(UEyeSDK DEFAULT_MSG UEYE_SDK_LIBRARIES UEYE_SDK_INCLUDE_DIRS)

MARK_AS_ADVANCED(UEYE_SDK_LIBRARIES UEYE_SDK_INCLUDE_DIRS)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Act. Soc. linn. Bordeaux, sér. A 40: 36 [repr. ] (1886)

#### Original name
Diplodia ditior var. petiolorum Brunaud

### Remarks
null


text:
#include <sys/param.h>
#include <sys/kernel.h>
#include <sys/types.h>

/*
 * This include will catch the libuinet sys/malloc.h, which redefines the
 * names malloc, free, realloc, and reallocf to be the uinet_ variants, then
 * includes the kernel sys/malloc.h.  This then provides us with the
 * prototypes for the uinet_ variants below, as well as the other
 * sys/malloc.h #defines and declarations to use.
 */
#include <sys/malloc.h>

/*
 * Now we undefine the names that were redefined by the libuinet
 * sys/malloc.h above so we can use the stdlib.h versions in the
 * implementation below.
 */
#undef malloc
#undef free
#undef realloc
#undef reallocf
#include <stdlib.h>
#include <strings.h>

MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");

MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");

void
malloc_init(void *data)
{
	/* Nothing to do here */
}

void
malloc_uninit(void *data)
{
	/* Nothing to do here */
}

/*
 * libuinet/include/sys/malloc.h redirects all malloc() and free() calls to
 * these routines for users of sys/malloc.h.
 */
void *
uinet_malloc(unsigned long size, struct malloc_type *type, int flags)
{
	void *alloc;
	alloc = malloc(size);

	if ((flags & M_ZERO) && alloc != NULL)
		bzero(alloc, size);
	return (alloc);
}

void
uinet_free(void *addr, struct malloc_type *type)
{

	free(addr);
}

void *
uinet_realloc(void *addr, unsigned long size, struct malloc_type *type,
	      int flags)
{
	return (realloc(addr, size));
}

void *
uinet_reallocf(void *addr, unsigned long size, struct malloc_type *type,
	      int flags)
{
	return (reallocf(addr, size));
}


text:
// @flow

import path from "path";
import Plugin from "./plugin";
import { mergeOptions } from "./util";
import { createItemFromDescriptor } from "./item";
import { buildRootChain, type ConfigContext } from "./config-chain";
import { getEnv } from "./helpers/environment";
import {
  validate,
  type ValidatedOptions,
  type RootMode,
} from "./validation/options";

import { findConfigUpwards, type ConfigFile, type IgnoreFile } from "./files";

function resolveRootMode(rootDir: string, rootMode: RootMode): string {
  switch (rootMode) {
    case "root":
      return rootDir;

    case "upward-optional": {
      const upwardRootDir = findConfigUpwards(rootDir);
      return upwardRootDir === null ? rootDir : upwardRootDir;
    }

    case "upward": {
      const upwardRootDir = findConfigUpwards(rootDir);
      if (upwardRootDir !== null) return upwardRootDir;

      throw Object.assign(
        (new Error(
          `Babel was run with rootMode:"upward" but a root could not ` +
            `be found when searching upward from "${rootDir}"`,
        ): any),
        {
          code: "BABEL_ROOT_NOT_FOUND",
          dirname: rootDir,
        },
      );
    }
    default:
      throw new Error(`Assertion failure - unknown rootMode value`);
  }
}

export default function loadPrivatePartialConfig(
  inputOpts: mixed,
): {
  options: ValidatedOptions,
  context: ConfigContext,
  ignore: IgnoreFile | void,
  babelrc: ConfigFile | void,
  config: ConfigFile | void,
} | null {
  if (
    inputOpts != null &&
    (typeof inputOpts !== "object" || Array.isArray(inputOpts))
  ) {
    throw new Error("Babel options must be an object, null, or undefined");
  }

  const args = inputOpts ? validate("arguments", inputOpts) : {};

  const {
    envName = getEnv(),
    cwd = ".",
    root: rootDir = ".",
    rootMode = "root",
    caller,
  } = args;
  const absoluteCwd = path.resolve(cwd);
  const absoluteRootDir = resolveRootMode(
    path.resolve(absoluteCwd, rootDir),
    rootMode,
  );

  const context: ConfigContext = {
    filename:
      typeof args.filename === "string"
        ? path.resolve(cwd, args.filename)
        : undefined,
    cwd: absoluteCwd,
    root: absoluteRootDir,
    envName,
    caller,
  };

  const configChain = buildRootChain(args, context);
  if (!configChain) return null;

  const options = {};
  configChain.options.forEach(opts => {
    mergeOptions(options, opts);
  });

  // Tack the passes onto the object itself so that, if this object is
  // passed back to Babel a second time, it will be in the right structure
  // to not change behavior.
  options.babelrc = false;
  options.configFile = false;
  options.passPerPreset = false;
  options.envName = context.envName;
  options.cwd = context.cwd;
  options.root = context.root;
  options.filename =
    typeof context.filename === "string" ? context.filename : undefined;

  options.plugins = configChain.plugins.map(descriptor =>
    createItemFromDescriptor(descriptor),
  );
  options.presets = configChain.presets.map(descriptor =>
    createItemFromDescriptor(descriptor),
  );

  return {
    options,
    context,
    ignore: configChain.ignore,
    babelrc: configChain.babelrc,
    config: configChain.config,
  };
}

export function loadPartialConfig(inputOpts: mixed): PartialConfig | null {
  const result = loadPrivatePartialConfig(inputOpts);
  if (!result) return null;

  const { options, babelrc, ignore, config } = result;

  (options.plugins || []).forEach(item => {
    if (item.value instanceof Plugin) {
      throw new Error(
        "Passing cached plugin instances is not supported in " +
          "babel.loadPartialConfig()",
      );
    }
  });

  return new PartialConfig(
    options,
    babelrc ? babelrc.filepath : undefined,
    ignore ? ignore.filepath : undefined,
    config ? config.filepath : undefined,
  );
}

export type { PartialConfig };

class PartialConfig {
  /**
   * These properties are public, so any changes to them should be considered
   * a breaking change to Babel's API.
   */
  options: ValidatedOptions;
  babelrc: string | void;
  babelignore: string | void;
  config: string | void;

  constructor(
    options: ValidatedOptions,
    babelrc: string | void,
    ignore: string | void,
    config: string | void,
  ) {
    this.options = options;
    this.babelignore = ignore;
    this.babelrc = babelrc;
    this.config = config;

    // Freeze since this is a public API and it should be extremely obvious that
    // reassigning properties on here does nothing.
    Object.freeze(this);
  }

  /**
   * Returns true if their is a config file in the filesystem for this config.
   *
   * While this only means .babelrc(.mjs)?/package.json#babel right now, it
   * may well expand in the future, so using this is recommended vs checking
   * this.babelrc directly.
   */
  hasFilesystemConfig(): boolean {
    return this.babelrc !== undefined || this.config !== undefined;
  }
}
Object.freeze(PartialConfig.prototype);


text:
layout: tag
title: "Pull Request"
slug: pull-request
permalink: /tag/pull-request/
---


text:
package us.kbase.typedobj.idref;

public class DefaultRemappedId implements RemappedId {

	private final String id;

	public DefaultRemappedId(String id) {
		super();
		this.id = id;
	}

	@Override
	public String getId() {
		return id;
	}

	@Override
	public String toString() {
		return "DefaultRemappedId [id=" + id + "]";
	}

}


text:
/**
 * Created by Papa on 10/16/2016.
 */
"use strict";
var SQLStringQuery_1 = require("../../SQLStringQuery");
var FlattenedQueryParser_1 = require("./FlattenedQueryParser");
var PlainQueryParser_1 = require("./PlainQueryParser");
var HierarchicalQueryParser_1 = require("./HierarchicalQueryParser");
var BridgedQueryParser_1 = require("./BridgedQueryParser");
var BridgedQueryConfiguration = (function () {
    function BridgedQueryConfiguration() {
        // This is for conflicts on OneToMany references
        this.strict = true;
        this.mapped = true;
    }
    return BridgedQueryConfiguration;
}());
exports.BridgedQueryConfiguration = BridgedQueryConfiguration;
function getObjectQueryParser(queryResultType, config, rootQEntity, qEntityMapByName) {
    switch (queryResultType) {
        case SQLStringQuery_1.QueryResultType.BRIDGED:
            return new BridgedQueryParser_1.BridgedQueryParser(config, rootQEntity, qEntityMapByName);
        case SQLStringQuery_1.QueryResultType.HIERARCHICAL:
            return new HierarchicalQueryParser_1.HierarchicalQueryParser();
        case SQLStringQuery_1.QueryResultType.PLAIN:
            return new PlainQueryParser_1.PlainQueryParser();
        case SQLStringQuery_1.QueryResultType.FLATTENED:
            return new FlattenedQueryParser_1.FlattenedQueryParser();
        default:
            throw "ObjectQueryParser not supported for QueryResultType: " + queryResultType;
    }
}
exports.getObjectQueryParser = getObjectQueryParser;
var AbstractObjectQueryParser = (function () {
    function AbstractObjectQueryParser() {
    }
    AbstractObjectQueryParser.prototype.addManyToOneStub = function (resultObject, propertyName, relationEntityMetadata, relatedEntityId) {
        var manyToOneStub = {};
        resultObject[propertyName] = manyToOneStub;
        manyToOneStub[relationEntityMetadata.idProperty] = relatedEntityId;
    };
    return AbstractObjectQueryParser;
}());
exports.AbstractObjectQueryParser = AbstractObjectQueryParser;
//# sourceMappingURL=IQueryParser.js.map


text:
package org.onosproject.drivers.server;

import org.onosproject.net.DeviceId;
import org.onosproject.net.MastershipRole;
import org.onosproject.net.device.DeviceHandshaker;
import org.onosproject.net.driver.DriverHandler;
import org.onosproject.net.flow.FlowRuleService;
import org.onosproject.net.flow.TableStatisticsEntry;
import org.onosproject.mastership.MastershipService;
import org.onosproject.protocol.rest.RestSBDevice;

import org.slf4j.Logger;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.Lists;

import java.io.ByteArrayInputStream;
import java.util.List;
import java.util.concurrent.CompletableFuture;

import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.CompletableFuture.completedFuture;
import static org.onosproject.drivers.server.Constants.JSON;
import static org.onosproject.drivers.server.Constants.PARAM_CONNECTION_STATUS;
import static org.onosproject.drivers.server.Constants.MSG_HANDLER_NULL;
import static org.onosproject.drivers.server.Constants.MSG_DEVICE_ID_NULL;
import static org.onosproject.drivers.server.Constants.MSG_DEVICE_NULL;
import static org.onosproject.drivers.server.Constants.URL_SRV_PROBE_CONNECT;
import static org.onosproject.drivers.server.Constants.URL_SRV_PROBE_DISCONNECT;
import static org.slf4j.LoggerFactory.getLogger;

/**
 * Implementation of device handshaker behaviour for server devices.
 */
public class ServerHandshaker
        extends BasicServerDriver
        implements DeviceHandshaker {

    private final Logger log = getLogger(getClass());

    public ServerHandshaker() {
        super();
        log.debug("Started");
    }

    @Override
    public DriverHandler handler() {
        return super.getHandler();
    }

    @Override
    public void setHandler(DriverHandler handler) {
        checkNotNull(handler, MSG_HANDLER_NULL);
        this.handler = handler;
    }

    @Override
    public boolean connect() throws IllegalStateException {
        // Retrieve the device ID from the handler
        DeviceId deviceId = super.getDeviceId();
        checkNotNull(deviceId, MSG_DEVICE_ID_NULL);

        // Create an object node
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode sendObjNode = mapper.createObjectNode();
        sendObjNode.put(PARAM_CONNECTION_STATUS, "connect");

        // Post the connect message to the server
        int response = getController().post(
            deviceId, URL_SRV_PROBE_CONNECT,
            new ByteArrayInputStream(sendObjNode.toString().getBytes()), JSON);

        // Upon an error, return an empty set of rules
        if (!checkStatusCode(response)) {
            log.error("Failed to connect to device {}", deviceId);
            return false;
        }

        log.info("Successfully connected to device {}", deviceId);

        return true;
    }

    @Override
    public boolean hasConnection() {
        return isReachable();
    }

    @Override
    public void disconnect() {
        // Retrieve the device ID from the handler
        DeviceId deviceId = super.getDeviceId();
        checkNotNull(deviceId, MSG_DEVICE_ID_NULL);

        // Create an object node
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode sendObjNode = mapper.createObjectNode();
        sendObjNode.put(PARAM_CONNECTION_STATUS, "disconnect");

        // Post the disconnect message to the server
        int response = getController().post(
            deviceId, URL_SRV_PROBE_DISCONNECT,
            new ByteArrayInputStream(sendObjNode.toString().getBytes()), JSON);

        if (!checkStatusCode(response)) {
            log.error("Failed to disconnect from device {}", deviceId);
            return;
        }

        log.info("Successfully disconnected from device {}", deviceId);

        return;
    }

    @Override
    public boolean isReachable() {
        // Retrieve the device ID from the handler
        DeviceId deviceId = super.getDeviceId();
        checkNotNull(deviceId, MSG_DEVICE_ID_NULL);

        // Get the device
        RestSBDevice device = super.getDevice(deviceId);
        checkNotNull(device, MSG_DEVICE_NULL);

        return deviceIsActive(device);
    }

    @Override
    public boolean isAvailable() {
        return isReachable();
    }

    @Override
    public CompletableFuture<Boolean> probeReachability() {
        // Retrieve the device ID from the handler
        DeviceId deviceId = super.getDeviceId();
        checkNotNull(deviceId, MSG_DEVICE_ID_NULL);

        // Probe the driver to ask for flow rule service
        FlowRuleService flowService = getHandler().get(FlowRuleService.class);
        List<TableStatisticsEntry> tableStats = Lists.newArrayList(
            flowService.getFlowTableStatistics(deviceId));

        // If no statistics fetched, the server is not reachable
        return completedFuture(tableStats.isEmpty() ? false : true);
    }

    @Override
    public CompletableFuture<Boolean> probeAvailability() {
        return probeReachability();
    }

    @Override
    public void roleChanged(MastershipRole newRole) {
        throw new UnsupportedOperationException("Mastership operation not supported");
    }

    @Override
    public MastershipRole getRole() {
        // Retrieve the device ID from the handler
        DeviceId deviceId = super.getDeviceId();
        checkNotNull(deviceId, MSG_DEVICE_ID_NULL);

        // Probe the driver to ask for mastership service
        MastershipService mastershipService = getHandler().get(MastershipService.class);
        return mastershipService.getLocalRole(deviceId);
    }

}


text:
Ext.Loader.setConfig({enabled: true});
Ext.Loader.setPath('Ext.ux', '../ux');
Ext.require([
    'Ext.data.*',
    'Ext.panel.Panel',
    'Ext.view.View',
    'Ext.layout.container.Fit',
    'Ext.toolbar.Paging',
    'Ext.ux.form.SearchField'
]);

Ext.define('Post', {
    extend: 'Ext.data.Model',
    idProperty: 'post_id',
    fields: [
        {name: 'postId', mapping: 'post_id'},
        {name: 'title', mapping: 'topic_title'},
        {name: 'topicId', mapping: 'topic_id'},
        {name: 'author', mapping: 'author'},
        {name: 'lastPost', mapping: 'post_time', type: 'date', dateFormat: 'timestamp'},
        {name: 'excerpt', mapping: 'post_text'}
    ]
});

Ext.onReady(function(){

    var forumId = 4;

    var store = Ext.create('Ext.data.Store', {
        model: 'Post',
        proxy: {
            type: 'jsonp',
            url: 'http://sencha.com/forum/topics-remote.php',
            extraParams: {
                forumId: forumId
            },
            reader: {
                type: 'json',
                root: 'topics',
                totalProperty: 'totalCount'
            }
        },
        listeners: {
            beforeload: function(){
                var params = store.getProxy().extraParams;
                if (params.query) {
                    delete params.forumId;
                } else {
                    params.forumId = forumId;
                }
            }
        }
    });
    store.loadPage(1);

    var resultTpl = Ext.create('Ext.XTemplate',
        '<tpl for=".">',
        '
',
            '
{lastPost:this.formatDate}
by {author}',
            '{title}
',
            '
{excerpt}
',
        '
</tpl>',
    {
        formatDate: function(value){
            return Ext.Date.format(value, 'M j, Y');
        }
    });

    var panel = Ext.create('Ext.panel.Panel', {
        title: 'Forum Search',
        height: 300,
        width: 600,
        renderTo: 'search-panel',
        id: 'search-results',
        layout: 'fit',
        items: {
            autoScroll: true,
            xtype: 'dataview',
            tpl: resultTpl,
            store: store,
            itemSelector: 'div.search-item'
        },
        dockedItems: [{
            dock: 'top',
            xtype: 'toolbar',
            items: {
                width: 400,
                fieldLabel: 'Search',
                labelWidth: 50,
                xtype: 'searchfield',
                store: store
            }
        }, {
            dock: 'bottom',
            xtype: 'pagingtoolbar',
            store: store,
            pageSize: 25,
            displayInfo: true,
            displayMsg: 'Topics {0} - {1} of {2}',
            emptyMsg: 'No topics to display'
        }]
    });
});


text:
// Add a class that will be the first entry in the dex cache, to
// avoid having the OtherDex and Main classes share the same cache index.
class AAA {
}

public class Main {

  // CHECK-START: void Main.inlineEmptyMethod() inliner (before)
  // CHECK-DAG:     [[Invoke:v\d+]]  InvokeStaticOrDirect
  // CHECK-DAG:                      ReturnVoid

  // CHECK-START: void Main.inlineEmptyMethod() inliner (after)
  // CHECK-NOT:                      InvokeStaticOrDirect

  public static void inlineEmptyMethod() {
    OtherDex.emptyMethod();
  }

  // CHECK-START: int Main.inlineReturnIntMethod() inliner (before)
  // CHECK-DAG:     [[Invoke:i\d+]]  InvokeStaticOrDirect
  // CHECK-DAG:                      Return [ [[Invoke]] ]

  // CHECK-START: int Main.inlineReturnIntMethod() inliner (after)
  // CHECK-NOT:                      InvokeStaticOrDirect

  // CHECK-START: int Main.inlineReturnIntMethod() inliner (after)
  // CHECK-DAG:     [[Const38:i\d+]] IntConstant 38
  // CHECK-DAG:                      Return [ [[Const38]] ]

  public static int inlineReturnIntMethod() {
    return OtherDex.returnIntMethod();
  }

  // CHECK-START: int Main.dontInlineOtherDexStatic() inliner (before)
  // CHECK-DAG:     [[Invoke:i\d+]]  InvokeStaticOrDirect
  // CHECK-DAG:                      Return [ [[Invoke]] ]

  // CHECK-START: int Main.dontInlineOtherDexStatic() inliner (after)
  // CHECK-DAG:     [[Invoke:i\d+]]  InvokeStaticOrDirect
  // CHECK-DAG:                      Return [ [[Invoke]] ]

  public static int dontInlineOtherDexStatic() {
    return OtherDex.returnOtherDexStatic();
  }

  // CHECK-START: int Main.inlineMainStatic() inliner (before)
  // CHECK-DAG:     [[Invoke:i\d+]]  InvokeStaticOrDirect
  // CHECK-DAG:                      Return [ [[Invoke]] ]

  // CHECK-START: int Main.inlineMainStatic() inliner (after)
  // CHECK-NOT:                      InvokeStaticOrDirect

  // CHECK-START: int Main.inlineMainStatic() inliner (after)
  // CHECK-DAG:     [[Static:i\d+]]  StaticFieldGet
  // CHECK-DAG:                      Return [ [[Static]] ]

  public static int inlineMainStatic() {
    return OtherDex.returnMainStatic();
  }

  // CHECK-START: int Main.dontInlineRecursiveCall() inliner (before)
  // CHECK-DAG:     [[Invoke:i\d+]]  InvokeStaticOrDirect
  // CHECK-DAG:                      Return [ [[Invoke]] ]

  // CHECK-START: int Main.dontInlineRecursiveCall() inliner (after)
  // CHECK-DAG:     [[Invoke:i\d+]]  InvokeStaticOrDirect
  // CHECK-DAG:                      Return [ [[Invoke]] ]

  public static int dontInlineRecursiveCall() {
    return OtherDex.recursiveCall();
  }

  // CHECK-START: java.lang.String Main.dontInlineReturnString() inliner (before)
  // CHECK-DAG:     [[Invoke:l\d+]]  InvokeStaticOrDirect
  // CHECK-DAG:                      Return [ [[Invoke]] ]

  // CHECK-START: java.lang.String Main.dontInlineReturnString() inliner (after)
  // CHECK-DAG:     [[Invoke:l\d+]]  InvokeStaticOrDirect
  // CHECK-DAG:                      Return [ [[Invoke]] ]

  public static String dontInlineReturnString() {
    return OtherDex.returnString();
  }

  // CHECK-START: java.lang.Class Main.dontInlineOtherDexClass() inliner (before)
  // CHECK-DAG:     [[Invoke:l\d+]]  InvokeStaticOrDirect
  // CHECK-DAG:                      Return [ [[Invoke]] ]

  // CHECK-START: java.lang.Class Main.dontInlineOtherDexClass() inliner (after)
  // CHECK-DAG:     [[Invoke:l\d+]]  InvokeStaticOrDirect
  // CHECK-DAG:                      Return [ [[Invoke]] ]

  public static Class dontInlineOtherDexClass() {
    return OtherDex.returnOtherDexClass();
  }

  // CHECK-START: java.lang.Class Main.inlineMainClass() inliner (before)
  // CHECK-DAG:     [[Invoke:l\d+]]  InvokeStaticOrDirect
  // CHECK-DAG:                      Return [ [[Invoke]] ]

  // CHECK-START: java.lang.Class Main.inlineMainClass() inliner (after)
  // CHECK-NOT:                      InvokeStaticOrDirect

  // CHECK-START: java.lang.Class Main.inlineMainClass() inliner (after)
  // CHECK-DAG:     [[Class:l\d+]]  LoadClass
  // CHECK-DAG:                     Return [ [[Class]] ]

  public static Class inlineMainClass() {
    return OtherDex.returnMainClass();
  }

  // CHECK-START: java.lang.Class Main.dontInlineOtherDexClassStaticCall() inliner (before)
  // CHECK-DAG:     [[Invoke:l\d+]]  InvokeStaticOrDirect
  // CHECK-DAG:                      Return [ [[Invoke]] ]

  // CHECK-START: java.lang.Class Main.dontInlineOtherDexClassStaticCall() inliner (after)
  // CHECK-DAG:     [[Invoke:l\d+]]  InvokeStaticOrDirect
  // CHECK-DAG:                      Return [ [[Invoke]] ]

  public static Class dontInlineOtherDexClassStaticCall() {
    return OtherDex.returnOtherDexClassStaticCall();
  }

  // CHECK-START: java.lang.Class Main.inlineOtherDexCallingMain() inliner (before)
  // CHECK-DAG:     [[Invoke:l\d+]]  InvokeStaticOrDirect
  // CHECK-DAG:                      Return [ [[Invoke]] ]

  // CHECK-START: java.lang.Class Main.inlineOtherDexCallingMain() inliner (after)
  // CHECK-NOT:                      InvokeStaticOrDirect

  // CHECK-START: java.lang.Class Main.inlineOtherDexCallingMain() inliner (after)
  // CHECK-DAG:     [[Class:l\d+]]  LoadClass
  // CHECK-DAG:                     Return [ [[Class]] ]

  public static Class inlineOtherDexCallingMain() {
    return OtherDex.returnOtherDexCallingMain();
  }

  public static Class getOtherClass() {
    return Main.class;
  }

  public static void main(String[] args) {
    inlineEmptyMethod();
    if (inlineReturnIntMethod() != 38) {
      throw new Error("Expected 38");
    }

    if (dontInlineOtherDexStatic() != 1) {
      throw new Error("Expected 1");
    }

    if (inlineMainStatic() != 42) {
      throw new Error("Expected 42");
    }

    if (dontInlineReturnString() != "OtherDex") {
      throw new Error("Expected OtherDex");
    }

    if (dontInlineOtherDexClass() != OtherDex.class) {
      throw new Error("Expected " + OtherDex.class);
    }

    if (dontInlineOtherDexClassStaticCall() != OtherDex.class) {
      throw new Error("Expected " + OtherDex.class);
    }

    if (inlineMainClass() != Main.class) {
      throw new Error("Expected " + Main.class);
    }

    if (inlineOtherDexCallingMain() != Main.class) {
      throw new Error("Expected " + Main.class);
    }
  }

  // Reference the AAA class to ensure it is in the dex cache.
  public static Class<?> cls = AAA.class;

  // Add a field that will be the first entry in the dex cache, to
  // avoid having the OtherDex.myStatic and Main.myStatic fields
  // share the same cache index.
  public static int aaa = 32;
  public static int myStatic = 42;
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="shortcut icon" href="../../docs-assets/ico/favicon.png">

    <title>AgMIP Login Page</title>

    <link href="static/css/agmip_custom.css" rel="stylesheet">
    <link href="static/css/bootstrap.css" rel="stylesheet">
    <link rel="stylesheet" href="static/font-awesome/css/font-awesome.min.css">
    <link href="static/css/agmip_custom.css" rel="stylesheet">

    <link href="static/css/footer.css" rel="stylesheet">

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
              Toggle navigation

            </button>

| Data Exchange

                Databases

AgMIP Crop Database (Site-based)

 Upload Data

                AgMIP Sites

AgMIP.org

AgMIP Research

AgMIP Toolshed

             		 Login

              		Sign Up

        <form class="form-signin col-sm-4 loginForm" role="form">

        		<input type="text" class="form-control loginInput" placeholder="Username" required autofocus>

        		<input type="password" class="form-control loginInput" placeholder="Password" required>

        <button class="btn btn-lg btn-primary btn-block greenBtn loginBtn" type="submit">Login</button>

          Remember me

      </form>

 AgMIP IT is based at the University of Florida

       		  Email: it@agmip.org

       				AgMIP's mission is to improve substantially the characterization of world food security as affected by climate variability and change, and to enhance adaptation capacity in both developing and developed countries.

       				AgMIP gratefully acknowledges major support from the UK Department for International Development's UKaid in partnership with the US Department of Agriculture Agricultural Research Service.


text:
<form class="sanfrancisco" action="/sanfrancisco/" method="POST" accept-charset="utf-8">

  {% include "includes/csrf_field.html" %}

	<legend>
    How would you like us to contact you?
  </legend>

		Code for America will use this to update you about your application.

	        <input type="checkbox" name="prefers_email" value="yes">

		        Email

	        <input type="checkbox" name="prefers_sms" value="yes">

		        Text message

	        <input type="checkbox" name="prefers_voicemail" value="yes">

		        Voicemail

	        <input type="checkbox" name="prefers_snailmail" value="yes">

		        Paper mail

				What is your first name?

			<input type="text" name="first_name" value="">

				What is your middle name?
				(optional)

			<input type="text" name="middle_name" value="">

				What is your last name?

			<input type="text" name="last_name" value="">

				What is your phone number?
				(optional)

				Code for America and the public defender will use this to contact you about your application.

			<input type="text" name="phone_number" value="">

				What is your email?
				(optional)

				For example "yourname@example.com"

			<input type="text" name="email" value="">

		<fieldset>

	    <legend>
		    What is your date of birth?
	    </legend>

		    For example: 4/28/1986

							Month

		        <input name="dob_month" pattern="0?[1-9]|1[012]" type="number" min="1" max="12">

							Day

		        <input name="dob_day" pattern="0?[1-9]|1[0-9]|2[0-9]|3[01]" type="number" min="1" max="31">

							Year

		        <input name="dob_year" pattern="[0-9]{4}" type="number" min="1900" max="2016">

	  </fieldset>

				What is your Social Security Number?

				The public defender's office will use this to get your San Francisco RAP sheet and find any convictions that can be reduced or dismissed.

			<input type="text" name="ssn" value="">

	<legend>
	    Are you a U.S. citizen?
    </legend>

		The public defender handles non-citizen cases differently and has staff who can help with citizenship issues.

	        <input type="radio" name="us_citizen" value="yes">
	        Yes

	        <input type="radio" name="us_citizen" value="no">
	        No

		<fieldset>

					What is your mailing address?

					The public defender will need to send you important papers.

				<input type="text" name="address_street" value="">

							City

						<input type="text" name="address_city" value="">

							State

						<input type="text" name="address_state" value="CA">

							Zip code

						<input type="text" name="address_zip" value="">

	  </fieldset>

		<legend>
	    Are you on probation or parole?
    </legend>

	        <input type="radio" name="on_probation_parole" value="yes">
	        Yes

	        <input type="radio" name="on_probation_parole" value="no">
	        No

				Where is your probation or parole?

			<input type="text" name="where_probation_or_parole" value="">

				When does your probation or parole end?

			<input type="text" name="when_probation_or_parole" value="">

		<legend>
	    Are you currently serving a sentence?
    </legend>

	        <input type="radio" name="serving_sentence" value="yes">
	        Yes

	        <input type="radio" name="serving_sentence" value="no">
	        No

		<legend>
	    Are you currently being charged with a crime?
    </legend>

	        <input type="radio" name="being_charged" value="yes">
	        Yes

	        <input type="radio" name="being_charged" value="no">
	        No

		<legend>
	    Have you ever been arrested or convicted outside of San Francisco?
    </legend>

	        <input type="radio" name="rap_outside_sf" value="yes">
	        Yes

	        <input type="radio" name="rap_outside_sf" value="no">
	        No

				When and where were you arrested or convicted outside of San Francisco?

			<input type="text" name="when_where_outside_sf" value="">

		<legend>
	    Are you currently employed?
    </legend>

				The Clean Slate program is free for you, but the public defender uses this information to get money from government programs.

	        <input type="radio" name="currently_employed" value="yes">
	        Yes

	        <input type="radio" name="currently_employed" value="no">
	        No

				What is your monthly income?

				The Clean Slate program is free for you, but the public defender uses this information to get money from government programs.

			<input type="text" name="monthly_income" value="">

				How much do you spend each month on things like rent, groceries, utilities, medical expenses, or childcare expenses?

				The Clean Slate program is free for you, but the public defender uses this information to get money from government programs.

			<input type="text" name="monthly_expenses" value="">

				How did you hear about this program or website?
				(optional)

			<input type="text" name="how_did_you_hear" value="">

			By clicking "Submit",  you are:

Giving the San Francisco Public Defender's office permission to get your San Francisco RAP Sheet.

Acknowledging that filling out this form is not a guarantee that a public defender will represent you.

	<button type="submit">Submit</button>
</form>


text:
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/paper-icon-button/paper-icon-button.html">

<link rel="import" href="../styles/shared-styles.html">
<link rel="import" href="../styles/et2f-styles.html">
<link rel="import" href="../app-elements/action-points-elements/action-points-list.html">
<link rel="import" href="../app-elements/page-elements/page-header.html">

<dom-module id="page-action-points-list">

  <style include="shared-styles et2f-styles">
    :host {
      display: block;
    }

  </style>

  <template>

    <!-- This comes from the template
      not DRY like this, but without it, it isn't showing correctly -->
    <app-header-layout>

      <app-header fixed shadow>

        <page-header user="[[user]]" structure="[[structure]]"></page-header>

      </app-header>

      <action-points-list user="[[user]]"
        structure="[[structure]]"
        route="{{route}}"
        user="[[user]]"
        list-loading="{{listLoading}}"
      ></action-points-list>
    </app-header-layout>

  </template>

  <script>
    Polymer({
      is: 'page-action-points-list',
      properties: {
        refreshData: {
          type: Boolean,
          notify: true,
        },
        structure: Object,
        user: Object,
        route: Object,
        listLoading: {
          type: Boolean,
          notify: true
        }
      }
    });
  </script>
</dom-module>


text:
/*jslint node: true, indent: 4, maxlen: 80 */
/*properties
    annotations, contributors, coordinates, created_at, current_user_retweet,
    entities, exports, favorite_count, favorited, filter_level, format, geo,
    hasOwnProperty, id, id_str, in_reply_to_screen_name, in_reply_to_status_id,
    in_reply_to_status_id_str, in_reply_to_user_id, in_reply_to_user_id_str,
    isArray, join, lang, length, place, placeId, possibly_sensitive,
    possibly_sensitive_editable, push, retweet_count, retweet_rel, retweeted,
    retweeted_status, scopes, screen_name, source, stringify, text, truncated,
    type, user, userId, withheld_copyright, withheld_in_countries,
    withheld_scope
*/
var format = require('util').format,
    isArray = require('util').isArray,
    entities = require('./entities'),
    place = require('./place'),
    user = require('./user'),
    retweet = require('./retweet'),
    /**
     * The VALUE template for the INSERT SQL-statement
     * @type {string}
     */
    insContributorsValues = "(%s, %s, %s)",
    /**
    * Template of the INSERT Statement to store this object
    * @type {string}
    */
    insContributors = 'INSERT INTO wut_contributors (tweet_id, user_id,' +
        ' screen_name) VALUES %s ON DUPLICATE KEY UPDATE' +
        ' screen_name=VALUES(screen_name);',
    /**
     * Static string template for the INSERT-statement
     * @type {string}
     */
    insGeoObjects = 'INSERT INTO wut_geo_objects (tweet_id, type) VALUES (%s,' +
        ' %s) ON DUPLICATE KEY UPDATE type=VALUES(type);',
    /**
     * Static string template for the VALUES part of the INSERT-statement
     * @type {string}
     */
    insGeoObjectsCoordinatesValue = '(%s, %d, %d, %d)',
    /**
     * Static string template for the INSERT-statement
     * @type {string}
     */
    insGeoObjectsCoordinates = 'INSERT INTO wut_geo_objects_coordinates' +
        ' (tweet_id, index_of, longitude, latitude) VALUES %s ON DUPLICATE' +
        ' KEY UPDATE longitude=VALUES(longitude), latitude=VALUES(latitude);',
    /**
     * Static string template for the INSERT-statement of the Tweet
     * @type {string}
     */
    insTweets = 'INSERT INTO wut_tweets (id, annotations, created_at,' +
        ' current_user_retweet, favorite_count, favorited, filter_level, geo,' +
        ' in_reply_to_screen_name,' +
        ' in_reply_to_status_id, in_reply_to_user_id, lang, place,' +
        ' possibly_sensitive, possibly_sensitive_editable,' +
        ' scopes, retweet_count, retweeted, source, text, truncated, user,' +
        ' withheld_copyright, withheld_in_countries, withheld_scope) VALUES' +
        ' (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,' +
        ' %s, %s, %s, %s, %s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE' +
        ' annotations=VALUES(annotations), created_at=VALUES(created_at),' +
        ' current_user_retweet=VALUES(current_user_retweet),' +
        ' favorite_count=VALUES(favorite_count),' +
        ' favorited=VALUES(favorited), geo=VALUES(geo),' +
        ' filter_level=VALUES(filter_level),' +
        ' in_reply_to_screen_name=VALUES(in_reply_to_screen_name),' +
        ' in_reply_to_status_id=VALUES(in_reply_to_status_id),' +
        ' in_reply_to_user_id=VALUES(in_reply_to_user_id),' +
        ' lang=VALUES(lang),' +
        ' place=VALUES(place), possibly_sensitive=VALUES(possibly_sensitive),' +
        ' possibly_sensitive_editable=VALUES(possibly_sensitive_editable),' +
        ' scopes=VALUES(scopes), retweet_count=VALUES(retweet_count),' +
        ' retweeted=VALUES(retweeted), source=VALUES(source),' +
        ' text=VALUES(text), truncated=VALUES(truncated), user=VALUES(user),' +
        ' withheld_copyright=VALUES(withheld_copyright),' +
        ' withheld_in_countries=VALUES(withheld_in_countries),' +
        ' withheld_scope=VALUES(withheld_scope);',
    /**
     * Static string template for the INSERT-statement for unknown objects
     * in the Tweet
     * @type {string}
     */
    insUnknownTweetObjs = 'INSERT INTO wut_unknown_tweet_objs (tweet_id,' +
        ' timestamp, unknown) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE' +
        ' timestamp=VALUES(timestamp), unknown=VALUES(unknown);';

/**
 * Returns an SQL-statement INSERT from the Contributors object.

 * Nullable. An collection of brief user objects (usually only one) indicating
 * users who contributed to the authorship of the tweet, on behalf of the
 * official tweet author.
 * @param {object} cont content of the contributors collection from the Tweet
 * @param {string} tweet_id id of the parrent Tweet SQL-escaped
 * @param {function} sqlEscFunc Function used to escape values for
 *     SQL-statements, usually the connection.escape() function
 * @return {string}
 * @author Kai Koch
 */
function contributors(cont, tweet_id, sqlEscFunc) {
    'use strict';
    var i, len, values = [], valuesCount = 0,
    /**
     * A collection of the contributing users usually just one
     * @type {array}
     */
        contributs = [];
    if (isArray(cont)) {
        len = cont.length;
        for (i = 0; i < len; i += 1) {
            if (cont[i].id_str) {
                contributs.push({
                    id_str: sqlEscFunc(cont[i].id_str),
                    screen_name: sqlEscFunc(cont[i].screen_name)
                });
            }
        }
    }
    len = contributs.length;
    for (i = 0; i < len; i += 1) {
        valuesCount = values.push(format(insContributorsValues,
            tweet_id,
            contributs[i].id_str,
            contributs[i].screen_name));
    }
    if (valuesCount) {
        return format(insContributors, values.join(','));
    }
    return '';
}

/**
 * Returns the INSERT - statements for the Coordinates Object
 * @param {object} coor
 * @param {string} tweet_id id of the parrent Tweet SQL-escaped
 * @param {function} sqlEscFunc Function used to escape values for
 *     SQL-statements, usually the connection.escape() function
 * @return {string}
 * @author Kai Koch
 */
function coordinates(coor, tweet_id, sqlEscFunc) {
    'use strict';
    var i = 0, len = 0, values = [], valuesCount = 0, sql = [],
        /**
         * The longitude and latitude of the Tweet's location, as an collection
         * of floats in the form of [longitude, latitude].

         * Example:

         * Type:"Point" [[ [-122.400612831116,37.7821120598956] ]]

         * Type:"Polygon" [[[-77.119759,38.791645],[-76.909393,38.791645],
         *     [-76.909393,38.995548],[-77.119759,38.995548]]]
         * @type {array}
         */
        coords = [],
        /**
         * The type of data encoded in the coordinates property. This will be
         * "Point" for Tweet coordinates fields.
         * See also @link http://www.geojson.org/
         * @type {string}
         */
        type = '';
    if (coor !== null) {
        type = sqlEscFunc(coor.type);
        switch (coor.type) {
        case "Point":
            // Bring Point Coordinates in line with other Coordinate types
            coords = [[coor.coordinates]];
            break;
        case "Polygon":
            coords = coor.coordinates;
            break;
        default:
            coords = coor.coordinates;
        }
    }
    sql.push(format(insGeoObjects,
        tweet_id,
        type));
    len = coords[0].length;
    for (i = 0; i < len; i += 1) {
        valuesCount = values.push(format(insGeoObjectsCoordinatesValue,
            tweet_id,
            i,
            coords[0][i][0],
            coords[0][i][1]));
    }
    if (valuesCount) {
        sql.push(format(insGeoObjectsCoordinates, values.join(',')));
    }
    return sql.join('\n');
}

/**
 * Returns SQL-statements from the Tweet object and all its child objects as
 * multi line SQL-string.

 * Does not use the int64 id-fields of any Twitter-object since JavaScript can't
 * handle int64 values, uses always [attribute_]id_str instead.

 * see: dev.twitter.com/docs/platform-objects/tweets
 * @param {object} t the JSON-object representing the tweet
 * @param {function} sqlEscFunc Reference to the function used to escape values
 *      for SQL-statements, usually the connection.escape() function
 * @param {boolean} [fromUserStatus]
 * @return {string} Multiline SQL-Statements
 * @author Kai Koch
 * @link https://dev.twitter.com/docs/platform-objects/tweets
 */
function tweet(t, sqlEscFunc, fromUserStatus) {
    'use strict';
    /**
     * To prevent a cyclic behaviour, when the Tweet object is instanciated by
     * an user object
     * @default defaults to false
     * @type {boolean}
     */
    fromUserStatus = fromUserStatus || false;
    var rows = [],
        /**
         * SQL-escaped JSON string of Tweet's unknown child objects,
         * that were added after to the Twitter-API
         * @default defaults to an empty string
         * @type {string}
         */
        unknown = '',
        /**
        * Holds the data of the Tweet
        * @type {object}
        */
        dat = {
            /**
             * Unused. Future/beta home for status annotations. If it occures it
             * will be stringified JSON
             * @default defaults to SQL-string null
             * @type {string}
             */
            annotations: 'null',
            /**
             * Nullable. Collection of Contributors as SQL-string
             * @default defaults to null
             * @type {string}
             */
            contributors: '',
            /**
             * Nullable. Collection of Coordinates as SQL-string
             * @default defaults to null
             * @type {Coordinates}
             */
            coordinates: '',
            /**
             * UTC time when this Tweet was created.

             * Transformed into MySQL-date format
             * @default defaults to empty string
             * @type {string}
             */
            created_at: '',
            /**
             * Perspectival. Only surfaces on methods supporting the
             * include_my_retweet parameter, when set to true. Details the Tweet
             * ID of the user's own retweet (if existent) of this Tweet.

             * Example: {"id": 26815871309,"id_str": "26815871309"} uses only
             * id_str
             * @default defaults to SQL-string null
             * @type {string}
             */
            current_user_retweet: 'null',
            /**
             * Entities which have been parsed out of the text of the Tweet.

             * Example:  {
             *     "hashtags":[],
             *     "media":[],
             *     "symbols": [],
             *     "urls":[],
             *     "user_mentions":[]
             * }
             * @default defaults to null
             * @type {string}
             */
            entities: '',
            /**
             * Nullable. Indicates approximately how many times this Tweet has
             * been "favorited" by Twitter users.
             * Example: 1585
             * @default defaults to null
             * @type {number}
             */
            favorite_count: null,
            /**
             * Nullable. Perspectival. Indicates whether this Tweet has been
             * favorited by the authenticating user.
             * @default defaults to SQL-string null
             * @type {string} String 'null', 'true' or 'false'
             */
            favorited: 'null',
            /**
             * Indicates the maximum value of the filter_level parameter which
             * may be used and still stream this Tweet. So a value of medium
             * will be streamed on none, low, and medium streams.
             * @see dev.twitter.com/blog/introducing-new-metadata-for-tweets
             * @default defaults to SQL-string null
             * @type {string} String 'null' OR 'none', 'low', 'medium', 'high'
             */
            filter_level: 'null',
            /**
             * Deprecated. Nullable. Use the "coordinates" field instead.
             * @type {object}
             */
            geo: 'null',
            /**
             * Nullable. If the represented Tweet is a reply, this field will
             * contain the screen name of the original Tweet's author.

             * Example: "twitterapi"
             * @default defaults to SQL-string null
             * @type {string}
             */
            in_reply_to_screen_name: 'null',
            /**
             * Nullable. If the represented Tweet is a reply, this field will
             * contain the string representation of the original Tweet's ID.
             * Example: "114749583439036416"
             * @default defaults to SQL-string null
             * @type {string}
             */
            in_reply_to_status_id_str: 'null',
            /**
             * Nullable. If the represented Tweet is a reply, this field will
             * contain the string representation of the original Tweet's author
             * ID.
             *
Example:"819797"
             * @default defaults to SQL-string null
             * @type {string}
             */
            in_reply_to_user_id_str: 'null',
            /**
             * Nullable. When present, indicates a BCP 47 language identifier
             * corresponding to the machine-detected language of the Tweet text,
             * or "und" if no language could be detected.
             * @see http://tools.ietf.org/html/bcp47
             * @default defaults to SQL-string null
             * @type {string}
             */
            lang: 'null',
            /**
             * Nullable. When present, indicates that the tweet is associated
             * (but not necessarily originating from) a Place.
             * @default defaults to null
             * @type {Place}
             */
            place: null,
            /**
             * Place_id as string
             * @type {string}
             */
            placeId: 'null',
            /**
             * Nullable. This field only surfaces when a tweet contains a link.
             * The meaning of the field doesn't pertain to the tweet content
             * itself, but instead it is an indicator that the URL contained in
             * the tweet may contain content or media identified as sensitive
             * content.
             * @default defaults to SQL-string null
             * @type {string} String 'null', 'true' or 'false'
             */
            possibly_sensitive: 'null',
            /**
             * !!!Undocumented Twitter field!!!
             * @default defaults to SQL-string null
             * @type {string} String 'null', 'true' or 'false'
             */
            possibly_sensitive_editable: 'null',
            /**
             * A set of key-value pairs indicating the intended contextual
             * delivery of the containing Tweet. Currently used by Twitter's
             * Promoted Products. Stored as SQL-escaped JSON string

             * Example: {"followers":false}
             * @default defaults to SQL-string null
             * @type {string}
             */
            scopes: 'null',
            /**
             * Number of times this Tweet has been retweeted. This field is no
             * longer capped at 99 and will not turn into a String for
             * "100+"

             * Example: 1585
             * @default defaults to SQL-string null
             * @type {number}
             */
            retweet_count: 0,
            /**
             * Perspectival. Indicates whether this Tweet has been retweeted by
             * the authenticating user.
             * @default defaults to SQL-string null
             * @type {string} String 'null', 'true' or 'false'
             */
            retweeted: 'null',
            /**
             * If the tweet is a re-tweet, it will include a node called
             * retweeted_status that within contains the tweet that has been
             * retweeted. The outer-most elements of the structure represent
             * the "new tweet" created to house the retweet.

             * see: https://dev.twitter.com/discussions/2994
             * @default defaults to empty String
             * @type {string}
             * @link https://dev.twitter.com/discussions/2994
             */
            retweeted_status: '',
            /**
             * If a tweet is a re-tweet, here the SQL-Statement for the
             * tweet->re-tweet relation is stored
             * @default defaults to empty String
             * @type {string}
             */
            retweet_rel: '',
            /**
             * Utility used to post the Tweet, as an HTML-formatted string.
             * Tweets from the Twitter website have a source value of web.

             * Example:

             * '\u003Ca href="http://itunes.apple.com/us/app/twitter/id409789998
             * ?mt=12" rel="nofollow"\u003ETwitter for Mac\u003C\/a\u003E'
             * @default defaults to SQL-string null
             * @type {string}
             */
            source: 'null',
            /**
             * The actual UTF-8 text of the status update. See twitter-text for
             * details on what is currently considered valid characters.

             * Example: "Tweet Button, Follow Button, and Web Intents javascript
             * now support SSL http:\/\/t.co\/9fbA0oYy ^TS"
             * @default defaults to empty string
             * @type {string}
             */
            text: '',
            /**
             * Indicates whether the value of the text parameter was truncated,
             * for example, as a result of a retweet exceeding the 140 character
             * Tweet length. Truncated text will end in ellipsis, like this ...
             * @default defaults to SQL-string null
             * @type {string} String 'null', 'true' or 'false'
             */
            truncated: 'null',
            /**
             * Users can be anyone or anything. They tweet, follow, create
             * lists, have a home_timeline, can be mentioned, and can be looked
             * up in bulk.
             * @default defaults to null
             * @type {string}
             */
            user: '',
            /**
             * User ID
             * @default defaults to empty string
             * @type {string}
             */
            userId: '',
            /**
             * When present and set to "true", it indicates that this piece of
             * content has been withheld due to a DMCA complaint.
             * @default defaults to SQL-string null
             * @type {string} String 'null', 'true' or 'false'
             */
            withheld_copyright: 'null',
            /**
             * When present, indicates a textual representation of the
             * two-letter country codes this content is withheld from. See New
             * Withheld Content Fields in API Responses.

             * Example:  "GR, HK, MY"
             * @default defaults to SQL-string null
             * @type {string}
             */
            withheld_in_countries: 'null',
            /**
             * When present, indicates whether the content being withheld is the
             * "status" or a "user."

             * Example: "status"
             * @default defaults to SQL-string null
             * @type {string}
             */
            withheld_scope: 'null'
        };
    // remove all int64 entries, we can not handle them in JS!
    delete t.id;
    delete t.in_reply_to_status_id;
    delete t.in_reply_to_user_id;
    /**
     * The string representation of the unique identifier for this Tweet.
     * Implementations should use this rather than the large integer in id.
     * Example: "114749583439036416"
     * @type {string}
     */
    dat.id_str = sqlEscFunc(t.id_str);
    delete t.id_str;
    if (t.annotations) {
        dat.annotations = sqlEscFunc(JSON.stringify(t.annotations));
    }
    delete t.annotations;
    if (t.contributors !== null) {
        dat.contributors = contributors(t.contributors, dat.id_str, sqlEscFunc);
    }
    delete t.contributors;
    if (t.coordinates !== null) {
        dat.coordinates = coordinates(t.coordinates, dat.id_str, sqlEscFunc);
    }
    delete t.coordinates;
    dat.created_at = sqlEscFunc(new Date(t.created_at));
    delete t.created_at;
    if (t.current_user_retweet) {
        dat.current_user_retweet = sqlEscFunc(t.current_user_retweet.id_str);
    }
    delete t.current_user_retweet;
    if (t.entities !== null) {
        dat.entities = entities(t.entities, dat.id_str, sqlEscFunc);
    }
    delete t.entities;
    if (t.favorite_count || t.favorite_count === 0) {
        dat.favorite_count = sqlEscFunc(t.favorite_count);
    }
    delete t.favorite_count;
    if (t.favorited === false) {
        dat.favorited = "'false'";
    } else if (t.favorited === true) {
        dat.favorited = "'true'";
    }
    delete t.favorited;
    if (t.filter_level) {
        dat.filter_level = sqlEscFunc(t.filter_level);
    }
    delete t.filter_level;
    if (t.geo !== null) {
        dat.geo = sqlEscFunc(JSON.stringify(t.geo));
    }
    delete t.geo;
    if (t.in_reply_to_screen_name) {
        dat.in_reply_to_screen_name = sqlEscFunc(t.in_reply_to_screen_name);
    }
    delete t.in_reply_to_screen_name;
    if (t.in_reply_to_status_id_str) {
        dat.in_reply_to_status_id_str = sqlEscFunc(t.in_reply_to_status_id_str);
    }
    delete t.in_reply_to_status_id_str;
    if (t.in_reply_to_user_id_str) {
        dat.in_reply_to_user_id_str = sqlEscFunc(t.in_reply_to_user_id_str);
    }
    delete t.in_reply_to_user_id_str;
    if (t.lang) {
        dat.lang = sqlEscFunc(t.lang);
    }
    delete t.lang;
    if (t.place !== null) {
        dat.place = place(t.place, sqlEscFunc);
        dat.placeId = sqlEscFunc(t.place.id);
    }
    delete t.place;
    if (t.possibly_sensitive === false) {
        dat.possibly_sensitive = "'false'";
    } else if (t.possibly_sensitive === true) {
        dat.possibly_sensitive = "'true'";
    }
    delete t.possibly_sensitive;
    if (t.possibly_sensitive_editable === false) {
        dat.possibly_sensitive_editable = "'false'";
    } else if (t.possibly_sensitive_editable === true) {
        dat.possibly_sensitive_editable = "'true'";
    }
    delete t.possibly_sensitive_editable;
    if (t.scopes) {
        dat.scopes = sqlEscFunc(JSON.stringify(t.scopes));
    }
    delete t.scopes;
    if (typeof t.retweet_count === 'number') {
        dat.retweet_count = t.retweet_count;
    }
    delete t.retweet_count;
    if (t.retweeted === false) {
        dat.retweeted = "'false'";
    } else if (t.retweeted === true) {
        dat.retweeted = "'true'";
    }
    delete t.retweeted;
    if (t.retweeted_status) {
        if (t.retweeted_status.hasOwnProperty("lang")) {
            dat.lang = sqlEscFunc(t.retweeted_status.lang);
        }
        dat.retweet_rel = retweet(
            dat.id_str,
            sqlEscFunc(t.retweeted_status.id_str)
        );
        dat.retweeted_status = tweet(t.retweeted_status, sqlEscFunc, false);
    }
    delete t.retweeted_status;
    if (t.source) {
        dat.source = sqlEscFunc(t.source);
    }
    delete t.source;
    if (t.text) {
        dat.text = sqlEscFunc(t.text);
    }
    delete t.text;
    if (t.truncated === false) {
        dat.truncated = "'false'";
    } else if (t.truncated === true) {
        dat.truncated = "'true'";
    }
    delete t.truncated;
    // if this tweet originates from user.status, do not
    // instanciate a new User object
    dat.userId = sqlEscFunc(t.user.id_str);
    if (!fromUserStatus) {
        dat.user = user(t.user, sqlEscFunc);
    }
    delete t.user;
    if (t.withheld_copyright === false) {
        dat.withheld_copyright = "'false'";
    } else if (t.withheld_copyright === true) {
        dat.withheld_copyright = "'true'";
    }
    delete t.withheld_copyright;
    if (t.withheld_in_countries) {
        dat.withheld_in_countries = sqlEscFunc(t.withheld_in_countries);
    }
    delete t.withheld_in_countries;
    if (t.withheld_scope) {
        dat.withheld_scope = sqlEscFunc(t.withheld_scope);
    }
    delete t.withheld_scope;
    unknown = JSON.stringify(t);
    if (unknown === '{}') {
        unknown = '';
    } else {
        unknown = sqlEscFunc(unknown);
    }
    // Insert original tweet it it was retweeted and a Node in the current tweet
    if (dat.retweeted_status) {
        rows.push(dat.retweeted_status);
    }
    // Insert the User, we might get another Tweet from the
    // User object, that contains less information and would overwrite the tweet
    // containing more information
    if (dat.user) {
        rows.push(dat.user);
    }
    rows.push(format(insTweets,
        dat.id_str,
        dat.annotations,
        dat.created_at,
        dat.current_user_retweet,
        dat.favorite_count,
        dat.favorited,
        dat.filter_level,
        dat.geo,
        dat.in_reply_to_screen_name,
        dat.in_reply_to_status_id_str,
        dat.in_reply_to_user_id_str,
        dat.lang,
        dat.placeId,
        dat.possibly_sensitive,
        dat.possibly_sensitive_editable,
        dat.scopes,
        dat.retweet_count,
        dat.retweeted,
        dat.source,
        dat.text,
        dat.truncated,
        dat.userId,
        dat.withheld_copyright,
        dat.withheld_in_countries,
        dat.withheld_scope));
    if (dat.retweet_rel) {
        rows.push(dat.retweet_rel);
    }
    if (dat.contributors) {
        rows.push(dat.contributors);
    }
    if (dat.coordinates) {
        rows.push(dat.coordinates);
    }
    if (dat.entities) {
        rows.push(dat.entities);
    }
    if (dat.place) {
        rows.push(dat.place);
    }
    if (unknown) {
        rows.push(format(insUnknownTweetObjs,
            dat.id_str,
            dat.created_at,
            unknown));
    }
    return rows.join('\n');
}
module.exports = tweet;