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

#include "net/http/http_server_properties_impl.h"

#include <algorithm>

#include "base/bind.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/thread_task_runner_handle.h"
#include "base/values.h"

namespace net {

namespace {

const uint64 kBrokenAlternativeProtocolDelaySecs = 300;

}  // namespace

HttpServerPropertiesImpl::HttpServerPropertiesImpl()
    : spdy_servers_map_(SpdyServerHostPortMap::NO_AUTO_EVICT),
      alternative_service_map_(AlternativeServiceMap::NO_AUTO_EVICT),
      spdy_settings_map_(SpdySettingsMap::NO_AUTO_EVICT),
      server_network_stats_map_(ServerNetworkStatsMap::NO_AUTO_EVICT),
      alternative_service_probability_threshold_(1.0),
      quic_server_info_map_(kMaxQuicServersToPersist),
      weak_ptr_factory_(this) {
  canonical_suffixes_.push_back(".c.youtube.com");
  canonical_suffixes_.push_back(".googlevideo.com");
  canonical_suffixes_.push_back(".googleusercontent.com");
}

HttpServerPropertiesImpl::~HttpServerPropertiesImpl() {
}

void HttpServerPropertiesImpl::InitializeSpdyServers(
    std::vector<std::string>* spdy_servers,
    bool support_spdy) {
  DCHECK(CalledOnValidThread());
  if (!spdy_servers)
    return;
  // Add the entries from persisted data.
  for (std::vector<std::string>::reverse_iterator it = spdy_servers->rbegin();
       it != spdy_servers->rend(); ++it) {
    spdy_servers_map_.Put(*it, support_spdy);
  }
}

void HttpServerPropertiesImpl::InitializeAlternativeServiceServers(
    AlternativeServiceMap* alternative_service_map) {
  for (AlternativeServiceMap::iterator map_it =
           alternative_service_map_.begin();
       map_it != alternative_service_map_.end();) {
    for (AlternativeServiceInfoVector::iterator it = map_it->second.begin();
         it != map_it->second.end();) {
      // Keep all the broken ones since those do not get persisted.
      AlternativeService alternative_service(it->alternative_service);
      if (alternative_service.host.empty()) {
        alternative_service.host = map_it->first.host();
      }
      if (IsAlternativeServiceBroken(alternative_service)) {
        ++it;
        continue;
      }
      it = map_it->second.erase(it);
    }
    if (map_it->second.empty()) {
      RemoveCanonicalHost(map_it->first);
      map_it = alternative_service_map_.Erase(map_it);
      continue;
    }
    ++map_it;
  }

  // Add the entries from persisted data.
  for (AlternativeServiceMap::reverse_iterator input_it =
           alternative_service_map->rbegin();
       input_it != alternative_service_map->rend(); ++input_it) {
    DCHECK(!input_it->second.empty());
    AlternativeServiceMap::iterator output_it =
        alternative_service_map_.Peek(input_it->first);
    if (output_it == alternative_service_map_.end()) {
      // There is no value in alternative_service_map_ for input_it->first:
      // inserting in AlternativeServiceVectorInfo.
      alternative_service_map_.Put(input_it->first, input_it->second);
      continue;
    }
    // There are some broken alternative services in alternative_service_map_
    // for input_it->first: appending AlternativeServiceInfo one by one.
    for (const AlternativeServiceInfo& alternative_service_info :
         input_it->second) {
      output_it->second.push_back(alternative_service_info);
    }
  }

  // Attempt to find canonical servers.
  uint16 canonical_ports[] = { 80, 443 };
  for (size_t i = 0; i < canonical_suffixes_.size(); ++i) {
    std::string canonical_suffix = canonical_suffixes_[i];
    for (size_t j = 0; j < arraysize(canonical_ports); ++j) {
      HostPortPair canonical_host(canonical_suffix, canonical_ports[j]);
      // If we already have a valid canonical server, we're done.
      if (ContainsKey(canonical_host_to_origin_map_, canonical_host) &&
          (alternative_service_map_.Peek(
               canonical_host_to_origin_map_[canonical_host]) !=
           alternative_service_map_.end())) {
        continue;
      }
      // Now attempt to find a server which matches this origin and set it as
      // canonical.
      for (AlternativeServiceMap::const_iterator it =
               alternative_service_map_.begin();
           it != alternative_service_map_.end(); ++it) {
        if (base::EndsWith(it->first.host(), canonical_suffixes_[i],
                           base::CompareCase::INSENSITIVE_ASCII)) {
          canonical_host_to_origin_map_[canonical_host] = it->first;
          break;
        }
      }
    }
  }
}

void HttpServerPropertiesImpl::InitializeSpdySettingsServers(
    SpdySettingsMap* spdy_settings_map) {
  for (SpdySettingsMap::reverse_iterator it = spdy_settings_map->rbegin();
       it != spdy_settings_map->rend(); ++it) {
    spdy_settings_map_.Put(it->first, it->second);
  }
}

void HttpServerPropertiesImpl::InitializeSupportsQuic(
    IPAddressNumber* last_address) {
  if (last_address)
    last_quic_address_ = *last_address;
}

void HttpServerPropertiesImpl::InitializeServerNetworkStats(
    ServerNetworkStatsMap* server_network_stats_map) {
  for (ServerNetworkStatsMap::reverse_iterator it =
           server_network_stats_map->rbegin();
       it != server_network_stats_map->rend(); ++it) {
    server_network_stats_map_.Put(it->first, it->second);
  }
}

void HttpServerPropertiesImpl::InitializeQuicServerInfoMap(
    QuicServerInfoMap* quic_server_info_map) {
  for (const std::pair<QuicServerId, std::string>& entry :
       *quic_server_info_map) {
    quic_server_info_map_.Put(entry.first, entry.second);
  }
}

void HttpServerPropertiesImpl::GetSpdyServerList(
    base::ListValue* spdy_server_list,
    size_t max_size) const {
  DCHECK(CalledOnValidThread());
  DCHECK(spdy_server_list);
  spdy_server_list->Clear();
  size_t count = 0;
  // Get the list of servers (host/port) that support SPDY.
  for (SpdyServerHostPortMap::const_iterator it = spdy_servers_map_.begin();
       it != spdy_servers_map_.end() && count < max_size; ++it) {
    const std::string spdy_server_host_port = it->first;
    if (it->second) {
      spdy_server_list->Append(new base::StringValue(spdy_server_host_port));
      ++count;
    }
  }
}

base::WeakPtr<HttpServerProperties> HttpServerPropertiesImpl::GetWeakPtr() {
  return weak_ptr_factory_.GetWeakPtr();
}

void HttpServerPropertiesImpl::Clear() {
  DCHECK(CalledOnValidThread());
  spdy_servers_map_.Clear();
  alternative_service_map_.Clear();
  canonical_host_to_origin_map_.clear();
  spdy_settings_map_.Clear();
  last_quic_address_.clear();
  server_network_stats_map_.Clear();
  quic_server_info_map_.Clear();
}

bool HttpServerPropertiesImpl::SupportsRequestPriority(
    const HostPortPair& host_port_pair) {
  DCHECK(CalledOnValidThread());
  if (host_port_pair.host().empty())
    return false;

  if (GetSupportsSpdy(host_port_pair))
    return true;

  const AlternativeServiceVector alternative_service_vector =
      GetAlternativeServices(host_port_pair);
  for (const AlternativeService& alternative_service :
       alternative_service_vector) {
    if (alternative_service.protocol == QUIC) {
      return true;
    }
  }
  return false;
}

bool HttpServerPropertiesImpl::GetSupportsSpdy(
    const HostPortPair& host_port_pair) {
  DCHECK(CalledOnValidThread());
  if (host_port_pair.host().empty())
    return false;

  SpdyServerHostPortMap::iterator spdy_host_port =
      spdy_servers_map_.Get(host_port_pair.ToString());
  return spdy_host_port != spdy_servers_map_.end() && spdy_host_port->second;
}

void HttpServerPropertiesImpl::SetSupportsSpdy(
    const HostPortPair& host_port_pair,
    bool support_spdy) {
  DCHECK(CalledOnValidThread());
  if (host_port_pair.host().empty())
    return;

  SpdyServerHostPortMap::iterator spdy_host_port =
      spdy_servers_map_.Get(host_port_pair.ToString());
  if ((spdy_host_port != spdy_servers_map_.end()) &&
      (spdy_host_port->second == support_spdy)) {
    return;
  }
  // Cache the data.
  spdy_servers_map_.Put(host_port_pair.ToString(), support_spdy);
}

bool HttpServerPropertiesImpl::RequiresHTTP11(
    const HostPortPair& host_port_pair) {
  DCHECK(CalledOnValidThread());
  if (host_port_pair.host().empty())
    return false;

  return (http11_servers_.find(host_port_pair) != http11_servers_.end());
}

void HttpServerPropertiesImpl::SetHTTP11Required(
    const HostPortPair& host_port_pair) {
  DCHECK(CalledOnValidThread());
  if (host_port_pair.host().empty())
    return;

  http11_servers_.insert(host_port_pair);
}

void HttpServerPropertiesImpl::MaybeForceHTTP11(const HostPortPair& server,
                                                SSLConfig* ssl_config) {
  if (RequiresHTTP11(server)) {
    ForceHTTP11(ssl_config);
  }
}

std::string HttpServerPropertiesImpl::GetCanonicalSuffix(
    const std::string& host) {
  // If this host ends with a canonical suffix, then return the canonical
  // suffix.
  for (size_t i = 0; i < canonical_suffixes_.size(); ++i) {
    std::string canonical_suffix = canonical_suffixes_[i];
    if (base::EndsWith(host, canonical_suffixes_[i],
                       base::CompareCase::INSENSITIVE_ASCII)) {
      return canonical_suffix;
    }
  }
  return std::string();
}

AlternativeServiceVector HttpServerPropertiesImpl::GetAlternativeServices(
    const HostPortPair& origin) {
  // Copy alternative services with probability greater than or equal to the
  // threshold into |alternative_services_above_threshold|.
  AlternativeServiceVector alternative_services_above_threshold;
  const base::Time now = base::Time::Now();
  AlternativeServiceMap::iterator map_it = alternative_service_map_.Get(origin);
  if (map_it != alternative_service_map_.end()) {
    for (AlternativeServiceInfoVector::iterator it = map_it->second.begin();
         it != map_it->second.end();) {
      if (it->expiration < now) {
        it = map_it->second.erase(it);
        continue;
      }
      if (it->probability < alternative_service_probability_threshold_) {
        ++it;
        continue;
      }
      AlternativeService alternative_service(it->alternative_service);
      if (alternative_service.host.empty()) {
        alternative_service.host = origin.host();
      }
      // If the alternative service is equivalent to the origin (same host, same
      // port, and both TCP), then there is already a Job for it, so do not
      // return it here.
      if (origin.Equals(alternative_service.host_port_pair()) &&
          NPN_SPDY_MINIMUM_VERSION <= alternative_service.protocol &&
          alternative_service.protocol <= NPN_SPDY_MAXIMUM_VERSION) {
        ++it;
        continue;
      }
      alternative_services_above_threshold.push_back(alternative_service);
      ++it;
    }
    if (map_it->second.empty()) {
      alternative_service_map_.Erase(map_it);
    }
    return alternative_services_above_threshold;
  }

  CanonicalHostMap::const_iterator canonical = GetCanonicalHost(origin);
  if (canonical == canonical_host_to_origin_map_.end()) {
    return AlternativeServiceVector();
  }
  map_it = alternative_service_map_.Get(canonical->second);
  if (map_it == alternative_service_map_.end()) {
    return AlternativeServiceVector();
  }
  for (AlternativeServiceInfoVector::iterator it = map_it->second.begin();
       it != map_it->second.end();) {
    if (it->expiration < now) {
      it = map_it->second.erase(it);
      continue;
    }
    if (it->probability < alternative_service_probability_threshold_) {
      ++it;
      continue;
    }
    AlternativeService alternative_service(it->alternative_service);
    if (alternative_service.host.empty()) {
      alternative_service.host = canonical->second.host();
      if (IsAlternativeServiceBroken(alternative_service)) {
        ++it;
        continue;
      }
      alternative_service.host = origin.host();
    } else if (IsAlternativeServiceBroken(alternative_service)) {
      ++it;
      continue;
    }
    alternative_services_above_threshold.push_back(alternative_service);
    ++it;
  }
  if (map_it->second.empty()) {
    alternative_service_map_.Erase(map_it);
  }
  return alternative_services_above_threshold;
}

bool HttpServerPropertiesImpl::SetAlternativeService(
    const HostPortPair& origin,
    const AlternativeService& alternative_service,
    double alternative_probability,
    base::Time expiration) {
  return SetAlternativeServices(
      origin, AlternativeServiceInfoVector(
                  /*size=*/1,
                  AlternativeServiceInfo(alternative_service,
                                         alternative_probability, expiration)));
}

bool HttpServerPropertiesImpl::SetAlternativeServices(
    const HostPortPair& origin,
    const AlternativeServiceInfoVector& alternative_service_info_vector) {
  AlternativeServiceMap::iterator it = alternative_service_map_.Peek(origin);

  if (alternative_service_info_vector.empty()) {
    if (it == alternative_service_map_.end()) {
      return false;
    }
    ClearAlternativeServices(origin);
    return true;
  }

  bool changed = true;
  if (it != alternative_service_map_.end()) {
    DCHECK(!it->second.empty());
    if (it->second.size() == alternative_service_info_vector.size()) {
      changed = !std::equal(it->second.begin(), it->second.end(),
                            alternative_service_info_vector.begin());
    }
  }

  const bool previously_no_alternative_services =
      (GetAlternateProtocolIterator(origin) == alternative_service_map_.end());

  alternative_service_map_.Put(origin, alternative_service_info_vector);

  if (previously_no_alternative_services &&
      !GetAlternativeServices(origin).empty()) {
    // TODO(rch): Consider the case where multiple requests are started
    // before the first completes. In this case, only one of the jobs
    // would reach this code, whereas all of them should should have.
    HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_MAPPING_MISSING);
  }

  // If this host ends with a canonical suffix, then set it as the
  // canonical host.
  for (size_t i = 0; i < canonical_suffixes_.size(); ++i) {
    std::string canonical_suffix = canonical_suffixes_[i];
    if (base::EndsWith(origin.host(), canonical_suffixes_[i],
                       base::CompareCase::INSENSITIVE_ASCII)) {
      HostPortPair canonical_host(canonical_suffix, origin.port());
      canonical_host_to_origin_map_[canonical_host] = origin;
      break;
    }
  }

  return changed;
}

void HttpServerPropertiesImpl::MarkAlternativeServiceBroken(
    const AlternativeService& alternative_service) {
  // Empty host means use host of origin, callers are supposed to substitute.
  DCHECK(!alternative_service.host.empty());
  if (alternative_service.protocol == UNINITIALIZED_ALTERNATE_PROTOCOL) {
    LOG(DFATAL) << "Trying to mark unknown alternate protocol broken.";
    return;
  }
  int count = ++recently_broken_alternative_services_[alternative_service];
  base::TimeDelta delay =
      base::TimeDelta::FromSeconds(kBrokenAlternativeProtocolDelaySecs);
  base::TimeTicks when = base::TimeTicks::Now() + delay * (1 << (count - 1));
  auto result = broken_alternative_services_.insert(
      std::make_pair(alternative_service, when));
  // Return if alternative service is already in expiration queue.
  if (!result.second) {
    return;
  }

  // If this is the only entry in the list, schedule an expiration task.
  // Otherwise it will be rescheduled automatically when the pending task runs.
  if (broken_alternative_services_.size() == 1) {
    ScheduleBrokenAlternateProtocolMappingsExpiration();
  }
}

void HttpServerPropertiesImpl::MarkAlternativeServiceRecentlyBroken(
    const AlternativeService& alternative_service) {
  if (!ContainsKey(recently_broken_alternative_services_, alternative_service))
    recently_broken_alternative_services_[alternative_service] = 1;
}

bool HttpServerPropertiesImpl::IsAlternativeServiceBroken(
    const AlternativeService& alternative_service) const {
  // Empty host means use host of origin, callers are supposed to substitute.
  DCHECK(!alternative_service.host.empty());
  return ContainsKey(broken_alternative_services_, alternative_service);
}

bool HttpServerPropertiesImpl::WasAlternativeServiceRecentlyBroken(
    const AlternativeService& alternative_service) {
  if (alternative_service.protocol == UNINITIALIZED_ALTERNATE_PROTOCOL)
    return false;
  return ContainsKey(recently_broken_alternative_services_,
                     alternative_service);
}

void HttpServerPropertiesImpl::ConfirmAlternativeService(
    const AlternativeService& alternative_service) {
  if (alternative_service.protocol == UNINITIALIZED_ALTERNATE_PROTOCOL)
    return;
  broken_alternative_services_.erase(alternative_service);
  recently_broken_alternative_services_.erase(alternative_service);
}

void HttpServerPropertiesImpl::ClearAlternativeServices(
    const HostPortPair& origin) {
  RemoveCanonicalHost(origin);

  AlternativeServiceMap::iterator it = alternative_service_map_.Peek(origin);
  if (it == alternative_service_map_.end()) {
    return;
  }
  alternative_service_map_.Erase(it);
}

const AlternativeServiceMap& HttpServerPropertiesImpl::alternative_service_map()
    const {
  return alternative_service_map_;
}

scoped_ptr<base::Value>
HttpServerPropertiesImpl::GetAlternativeServiceInfoAsValue()
    const {
  scoped_ptr<base::ListValue> dict_list(new base::ListValue);
  for (const auto& alternative_service_map_item : alternative_service_map_) {
    scoped_ptr<base::ListValue> alternative_service_list(new base::ListValue);
    const HostPortPair& host_port_pair = alternative_service_map_item.first;
    for (const AlternativeServiceInfo& alternative_service_info :
         alternative_service_map_item.second) {
      std::string alternative_service_string(
          alternative_service_info.ToString());
      AlternativeService alternative_service(
          alternative_service_info.alternative_service);
      if (alternative_service.host.empty()) {
        alternative_service.host = host_port_pair.host();
      }
      if (IsAlternativeServiceBroken(alternative_service)) {
        alternative_service_string.append(" (broken)");
      }
      alternative_service_list->Append(
          new base::StringValue(alternative_service_string));
    }
    if (alternative_service_list->empty())
      continue;
    scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
    dict->SetString("host_port_pair", host_port_pair.ToString());
    dict->Set("alternative_service",
              scoped_ptr<base::Value>(alternative_service_list.Pass()));
    dict_list->Append(dict.Pass());
  }
  return dict_list.Pass();
}

const SettingsMap& HttpServerPropertiesImpl::GetSpdySettings(
    const HostPortPair& host_port_pair) {
  SpdySettingsMap::iterator it = spdy_settings_map_.Get(host_port_pair);
  if (it == spdy_settings_map_.end()) {
    CR_DEFINE_STATIC_LOCAL(SettingsMap, kEmptySettingsMap, ());
    return kEmptySettingsMap;
  }
  return it->second;
}

bool HttpServerPropertiesImpl::SetSpdySetting(
    const HostPortPair& host_port_pair,
    SpdySettingsIds id,
    SpdySettingsFlags flags,
    uint32 value) {
  if (!(flags & SETTINGS_FLAG_PLEASE_PERSIST))
      return false;

  SettingsFlagsAndValue flags_and_value(SETTINGS_FLAG_PERSISTED, value);
  SpdySettingsMap::iterator it = spdy_settings_map_.Get(host_port_pair);
  if (it == spdy_settings_map_.end()) {
    SettingsMap settings_map;
    settings_map[id] = flags_and_value;
    spdy_settings_map_.Put(host_port_pair, settings_map);
  } else {
    SettingsMap& settings_map = it->second;
    settings_map[id] = flags_and_value;
  }
  return true;
}

void HttpServerPropertiesImpl::ClearSpdySettings(
    const HostPortPair& host_port_pair) {
  SpdySettingsMap::iterator it = spdy_settings_map_.Peek(host_port_pair);
  if (it != spdy_settings_map_.end())
    spdy_settings_map_.Erase(it);
}

void HttpServerPropertiesImpl::ClearAllSpdySettings() {
  spdy_settings_map_.Clear();
}

const SpdySettingsMap&
HttpServerPropertiesImpl::spdy_settings_map() const {
  return spdy_settings_map_;
}

bool HttpServerPropertiesImpl::GetSupportsQuic(
    IPAddressNumber* last_address) const {
  if (last_quic_address_.empty())
    return false;

  *last_address = last_quic_address_;
  return true;
}

void HttpServerPropertiesImpl::SetSupportsQuic(bool used_quic,
                                               const IPAddressNumber& address) {
  if (!used_quic) {
    last_quic_address_.clear();
  } else {
    last_quic_address_ = address;
  }
}

void HttpServerPropertiesImpl::SetServerNetworkStats(
    const HostPortPair& host_port_pair,
    ServerNetworkStats stats) {
  server_network_stats_map_.Put(host_port_pair, stats);
}

const ServerNetworkStats* HttpServerPropertiesImpl::GetServerNetworkStats(
    const HostPortPair& host_port_pair) {
  ServerNetworkStatsMap::iterator it =
      server_network_stats_map_.Get(host_port_pair);
  if (it == server_network_stats_map_.end()) {
    return NULL;
  }
  return &it->second;
}

const ServerNetworkStatsMap&
HttpServerPropertiesImpl::server_network_stats_map() const {
  return server_network_stats_map_;
}

bool HttpServerPropertiesImpl::SetQuicServerInfo(
    const QuicServerId& server_id,
    const std::string& server_info) {
  QuicServerInfoMap::iterator it = quic_server_info_map_.Peek(server_id);
  bool changed =
      (it == quic_server_info_map_.end() || it->second != server_info);
  quic_server_info_map_.Put(server_id, server_info);
  return changed;
}

const std::string* HttpServerPropertiesImpl::GetQuicServerInfo(
    const QuicServerId& server_id) {
  QuicServerInfoMap::iterator it = quic_server_info_map_.Get(server_id);
  if (it == quic_server_info_map_.end())
    return nullptr;
  return &it->second;
}

const QuicServerInfoMap& HttpServerPropertiesImpl::quic_server_info_map()
    const {
  return quic_server_info_map_;
}

void HttpServerPropertiesImpl::SetAlternativeServiceProbabilityThreshold(
    double threshold) {
  alternative_service_probability_threshold_ = threshold;
}

AlternativeServiceMap::const_iterator
HttpServerPropertiesImpl::GetAlternateProtocolIterator(
    const HostPortPair& server) {
  AlternativeServiceMap::const_iterator it =
      alternative_service_map_.Get(server);
  if (it != alternative_service_map_.end())
    return it;

  CanonicalHostMap::const_iterator canonical = GetCanonicalHost(server);
  if (canonical == canonical_host_to_origin_map_.end()) {
    return alternative_service_map_.end();
  }

  const HostPortPair canonical_host_port = canonical->second;
  it = alternative_service_map_.Get(canonical_host_port);
  if (it == alternative_service_map_.end()) {
    return alternative_service_map_.end();
  }

  for (const AlternativeServiceInfo& alternative_service_info : it->second) {
    AlternativeService alternative_service(
        alternative_service_info.alternative_service);
    if (alternative_service.host.empty()) {
      alternative_service.host = canonical_host_port.host();
    }
    if (!IsAlternativeServiceBroken(alternative_service)) {
      return it;
    }
  }

  RemoveCanonicalHost(canonical_host_port);
  return alternative_service_map_.end();
}

HttpServerPropertiesImpl::CanonicalHostMap::const_iterator
HttpServerPropertiesImpl::GetCanonicalHost(HostPortPair server) const {
  for (size_t i = 0; i < canonical_suffixes_.size(); ++i) {
    std::string canonical_suffix = canonical_suffixes_[i];
    if (base::EndsWith(server.host(), canonical_suffixes_[i],
                       base::CompareCase::INSENSITIVE_ASCII)) {
      HostPortPair canonical_host(canonical_suffix, server.port());
      return canonical_host_to_origin_map_.find(canonical_host);
    }
  }

  return canonical_host_to_origin_map_.end();
}

void HttpServerPropertiesImpl::RemoveCanonicalHost(
    const HostPortPair& server) {
  CanonicalHostMap::const_iterator canonical = GetCanonicalHost(server);
  if (canonical == canonical_host_to_origin_map_.end())
    return;

  if (!canonical->second.Equals(server))
    return;

  canonical_host_to_origin_map_.erase(canonical->first);
}

void HttpServerPropertiesImpl::ExpireBrokenAlternateProtocolMappings() {
  base::TimeTicks now = base::TimeTicks::Now();
  while (!broken_alternative_services_.empty()) {
    BrokenAlternativeServices::iterator it =
        broken_alternative_services_.begin();
    if (now < it->second) {
      break;
    }

    const AlternativeService expired_alternative_service = it->first;
    broken_alternative_services_.erase(it);

    // Remove every occurrence of |expired_alternative_service| from
    // |alternative_service_map_|.
    for (AlternativeServiceMap::iterator map_it =
             alternative_service_map_.begin();
         map_it != alternative_service_map_.end();) {
      for (AlternativeServiceInfoVector::iterator it = map_it->second.begin();
           it != map_it->second.end();) {
        AlternativeService alternative_service(it->alternative_service);
        // Empty hostname in map means hostname of key: substitute before
        // comparing to |expired_alternative_service|.
        if (alternative_service.host.empty()) {
          alternative_service.host = map_it->first.host();
        }
        if (alternative_service == expired_alternative_service) {
          it = map_it->second.erase(it);
          continue;
        }
        ++it;
      }
      // If an origin has an empty list of alternative services, then remove it
      // from both |canonical_host_to_origin_map_| and
      // |alternative_service_map_|.
      if (map_it->second.empty()) {
        RemoveCanonicalHost(map_it->first);
        map_it = alternative_service_map_.Erase(map_it);
        continue;
      }
      ++map_it;
    }
  }
  ScheduleBrokenAlternateProtocolMappingsExpiration();
}

void
HttpServerPropertiesImpl::ScheduleBrokenAlternateProtocolMappingsExpiration() {
  if (broken_alternative_services_.empty()) {
    return;
  }
  base::TimeTicks now = base::TimeTicks::Now();
  base::TimeTicks when = broken_alternative_services_.front().second;
  base::TimeDelta delay = when > now ? when - now : base::TimeDelta();
  base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
      FROM_HERE,
      base::Bind(
          &HttpServerPropertiesImpl::ExpireBrokenAlternateProtocolMappings,
          weak_ptr_factory_.GetWeakPtr()),
      delay);
}

}  // namespace net


text:
const { getTflTrainStatus } = require('./alexaActions')

jest.mock('./tflCalls', () => ({
  getTflTrainDisruption: jest.fn()
}))

const { getTflTrainDisruption } = require('./tflCalls')

const getTflTrainDisruptionResponse = [
  {
    $type:
      'Tfl.Api.Presentation.Entities.Disruption, Tfl.Api.Presentation.Entities',
    category: 'RealTime',
    type: 'routeInfo',
    categoryDescription: 'RealTime',
    description:
      'Northern Line: MINOR DELAYS between Camden Town and Kennington via Charing Cross due to a signal failure at Kennington. ',
    affectedRoutes: [],
    affectedStops: [],
    closureText: 'minorDelays'
  },
  {
    $type:
      'Tfl.Api.Presentation.Entities.Disruption, Tfl.Api.Presentation.Entities',
    category: 'RealTime',
    type: 'lineInfo',
    categoryDescription: 'RealTime',
    description:
      'Waterloo and City Line: The service will resume again at 0615 tomorrow. ',
    affectedRoutes: [],
    affectedStops: [],
    closureText: 'serviceClosed'
  }
]

describe('getTflTrainStatus', () => {
  it('returns the status of the TFL train network in a human readable format', async () => {
    getTflTrainDisruption.mockReturnValue(
      Promise.resolve(getTflTrainDisruptionResponse)
    )
    await expect(getTflTrainStatus()).resolves.toBe(
      'Northern Line: MINOR DELAYS between Camden Town and Kennington via Charing Cross due to a signal failure at Kennington. Waterloo and City Line: The service will resume again at 0615 tomorrow. '
    )
    expect(getTflTrainDisruption).toHaveBeenCalledTimes(1)
  })
})

redpajama_set_name: RedPajamaGithub


text:
package deb

import (
	"archive/tar"
	"bytes"
	"compress/gzip"

	"github.com/stapelberg/godebiancontrol"

	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

// Package represents a debian Package on disk
type Package struct {
	Name, Version, Arch string

	file       string
	readone    bool
	archive    *tar.Reader
	fieldcache godebiancontrol.Paragraph
}

// NewPackage provides information of a debian Package on disk
func NewPackage(file string) *Package {
	basename := filepath.Base(file)
	split := strings.Split(basename, "_")
	if len(split) != 3 {
		return nil
	}
	return &Package{
		Name:    split[0],
		Version: strings.Replace(split[1], "%", ":", -1),
		Arch:    strings.TrimSuffix(split[2], ".deb"),
		file:    file,
	}

}

func (p *Package) updateFieldCache() error {
	cmd := exec.Command("dpkg-deb", "--field", p.file)

	o, err := cmd.Output()
	if err != nil {
		return err
	}

	b := bytes.NewBuffer(o)
	pp, err := godebiancontrol.Parse(b)
	if err != nil {
		return err
	}

	if len(pp) != 1 {
		return os.ErrInvalid

	}

	p.fieldcache = pp[0]
	return nil
}

// Source package this Debian package was generated from
func (p *Package) Source() (string, error) {
	if p.fieldcache == nil {
		err := p.updateFieldCache()
		if err != nil {
			return "", err
		}
	}
	return p.fieldcache["Source"], nil
}

func (p *Package) archiveOpen() (*tar.Reader, error) {
	if p.archive != nil {
		return p.archive, nil
	}
	cmd := exec.Command("dpkg-deb", "--fsys-tarfile", p.file)
	r, err := cmd.StdoutPipe()
	if err != nil {
		return nil, err
	}

	if err := cmd.Start(); err != nil {
		return nil, err
	}

	go func(c *exec.Cmd) {
		if err := c.Wait(); err != nil {
			log.Println("Cannot stream package in tar mode.", err)
		}
	}(cmd)
	p.archive = tar.NewReader(r)
	p.readone = false
	return p.archive, nil
}

// Find a file archived in this Debian package
func (p *Package) Find(file string) (io.ReadCloser, error) {
	archive, err := p.archiveOpen()
	if err != nil {
		return nil, err
	}

	rewind := !p.readone
	for {
		hdr, err := archive.Next()
		p.readone = true
		// end of tar archive
		if err == io.EOF {
			// if we started in the middle, try to start from the beginning again
			if rewind {
				p.archive = nil

				archive, err = p.archiveOpen()
				if err != nil {
					return nil, err
				}

				// and now back to searching...
				rewind = false
				continue
			}
			return nil, os.ErrNotExist
		}
		if err != nil {
			// b0rken tar archive
			return nil, err
		}

		// No match
		if hdr.Name != file {
			continue
		}

		// Only regular entries please
		if hdr.FileInfo().Mode().IsRegular() {
			switch filepath.Ext(file) {
			case ".gz":
				return gzip.NewReader(archive)
			default:
				return ioutil.NopCloser(archive), nil
			}
		}
		return nil, os.ErrInvalid
	}
	panic("Never reached")
}


text:
package org.locationtech.geomesa.web.core

import java.net.URLEncoder
import java.nio.file.Files

import org.json4s.{DefaultFormats, Formats}
import org.junit.runner.RunWith
import org.locationtech.geomesa.utils.cache.FilePersistence
import org.locationtech.geomesa.utils.classpath.PathUtils
import org.scalatra.Ok
import org.scalatra.json.NativeJsonSupport
import org.scalatra.test.specs2.MutableScalatraSpec
import org.specs2.runner.JUnitRunner
import org.specs2.specification.{Fragments, Step}

@RunWith(classOf[JUnitRunner])
class GeoMesaDataStoreServletTest extends MutableScalatraSpec {

  sequential

  val tmpDir = Files.createTempDirectory("gmServletTest")

  def urlEncode(s: String): String = URLEncoder.encode(s, "UTF-8")

  // cleanup tmp dir after tests run
  override def map(fragments: => Fragments) = super.map(fragments) ^ Step {
    PathUtils.deleteRecursively(tmpDir)
  }

  var calledTest = false

  addServlet(new GeoMesaDataStoreServlet with NativeJsonSupport {
    override def root: String = ""
    override val persistence: FilePersistence = new FilePersistence(tmpDir.toFile, "servlet")

    override protected implicit val jsonFormats: Formats = DefaultFormats

    before() {
      contentType = formats("json")
    }

    get("/test") {
      try {
        withDataStore((ds) => { calledTest = true; Ok() })
      } catch {
        case e: Exception => handleError(s"Error creating index:", e)
      }
    }
  }, "/*")

  implicit val formats: Formats = DefaultFormats

  val dsParams = Map("instanceId" -> "GeoMesaDataStoreServletTest", "user" -> "root", "password" -> "",
    "tableName" -> "GeoMesaDataStoreServlet", "useMock" -> "true")

  val jsonParams =
    dsParams.filterKeys(_ != "password").map { case (k, v) => s""""$k":"$v"""" } ++ Seq(""""password":"***"""")

  "GeoMesaDataStoreServlet" should {
    "register a datastore" in {
      post("/ds/servlettest", dsParams) {
        status mustEqual 200
      }
    }
    "allow datastore to be used by alias" in {
      calledTest = false
      get("test?alias=servlettest") {
        status mustEqual 200
        calledTest must beTrue
      }
    }
    "list registered datastore without password" in {
      get("/ds/servlettest") {
        status mustEqual 200
        body must startWith("{")
        body must endWith("}")
        forall(jsonParams)(param => body must contain(param))
      }
    }
    "list all registered datastores without passwords" in {
      get("/ds") {
        status mustEqual 200
        body must startWith("{")
        body must endWith("}")
        body must contain(""""servlettest":{""")
        forall(jsonParams)(param => body must contain(param))
      }
    }
    "delete a registered datastore" in {
      delete("/ds/servlettest") {
        status mustEqual 200
      }
      get("/ds/servlettest") {
        status mustEqual 404
      }
      get("/ds") {
        status mustEqual 200
        body mustEqual "{}"
      }
    }
  }
}


text:
author: robmyers
comments: true
date: 2008-10-18 06:24:38+00:00
layout: post
slug: flossart-book-launch
title: FLOSS+Art Book Launch
wordpress_id: 1682
categories:
- Free Culture
- Projects
---

[
FLOSS+Art: Book preview, panel discussion and software party
](http://code.goto10.org/projects/puredyne/wiki/pd4e-LaunchEvent)

<blockquote>_
Thursday 23 October
18:30 - 20:30
_
>
> _
@ Mute Magazine HQ
The Whitechapel Centre
85 Myrdle Street
London E1 1HL
_
>
> _
ABOUT THE BOOK:
_
>
> _
FLOSS+Art critically reflects on the growing relationship between Free
Software ideology, open content and digital art. It provides a view onto
the social, political and economic myths and realities linked to this
phenomenon.
_
>
> _
With contributions from: Fabianne Balvedi, Florian Cramer, Sher Doruff,
Nancy Mauro Flude, Olga Goriunova, Dave Griffiths, Ross Harley, Martin
Howse, Shahee Ilyas, Ricardo Lafuente, Ivan Monroy Lopez, Thor
Magnusson, Alex McLean,
Rob Myers, Alejandra Maria Perez Nuñez, Eleonora Oreggia, oRx-qX,
Julien Ottavi, Michael van Schaik, Femke Snelting, Pedro Soler, Hans
Christoph Steiner, Prodromos Tsiavos, Simon Yuill
_
>
> _
Compiled and edited by Aymeric Mansoux and Marloes de Valk.
_

>
> </blockquote>

My contribution to the book is a greatly expanded version of the most popular post from this blog, "Open Source Art Again", with additional quotations and references. I've seen one of the other contributions and I know several of the other contributors so I can say without being arrogant that I know there's going to be some very good stuff in this book.


text:
<SageTVPlugin>
    <Name>junit</Name>
    <Identifier>junit</Identifier>
    <Description>SageTV Dependency JAR Plugin - no need to download directly</Description>
    <Author>stuckless</Author>
    <CreationDate>2011.04.10</CreationDate>
    <ModificationDate>2015.12.12</ModificationDate>
    <Version>4.12.0</Version>
    <Dependency>
        <JVM />
        <MinVersion>1.5.0</MinVersion>
    </Dependency>
    <PluginType>Library</PluginType>
    <Package>
        <PackageType>JAR</PackageType>
        <Location>https://github.com/OpenSageTV/sagetv-plugin-repo/releases/download/1/junit-4.12.zip</Location>
        <MD5>631E4C16741B18D3203E2C15CD8A6E4D</MD5>
    </Package>
</SageTVPlugin>


text:
this is the code generator for GURD app

************************
Please check the db.json to see the required config for coretable; (ignore the data section)
Once you done the config, the table is done.

editWay: 参数: inline, modal

***********************
同时考虑Tree等的增删改查。同质化

***************************
Maybe a UI to generate the db.json later


text:
package com.groupon.sparklint.data

import org.apache.spark.util.StatCounter

/**
  * @author rxue
  * @since 9/23/16.
  */
class SparklintOutputCounter(_recordsWritten: StatCounter = StatCounter(),
                             _bytesWritten: StatCounter = StatCounter()) {
  def merge(that: SparklintOutputMetrics): SparklintOutputCounter = {
    _recordsWritten.merge(that.recordsWritten)
    _bytesWritten.merge(that.bytesWritten)
    this
  }

  def recordsWritten: StatCounter = _recordsWritten.copy()

  def bytesWritten: StatCounter = _bytesWritten.copy()
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>Raesene's Ramblings</title>

	<meta name="author" content="raesene">

	<meta name="viewport" content="width=device-width, initial-scale=1.0">

	<link href="https://raesene.github.io/assets/resources/bootstrap/css/bootstrap.min.css" rel="stylesheet">
	<link href="https://raesene.github.io/assets/resources/font-awesome/css/font-awesome.min.css" rel="stylesheet">
	<link href="https://raesene.github.io/assets/resources/syntax/syntax.css" rel="stylesheet">
	<link href="https://raesene.github.io/assets/css/style.css" rel="stylesheet">

	<link rel="alternate" type="application/rss+xml" title="" href="https://raesene.github.io/feed.xml">

			<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
				Toggle navigation

			</button>

				Raesene's Ramblings

Home

Categories

Tags

		<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">

		</button>

Home

Categories

Tags

Top of Page

        Raesene's Ramblings

	Security Geek, Kubernetes, Docker, Ruby, Hillwalking

Raesene's Ramblings

    December
    28th,

    2004

    Category-based Web content blocking... a bit useless really

Looking at a couple of tools I found on the web CGIProxy  and PHProxy it seems to me that content based blocking by companies becomes a bit pointless, as you can put one of these scripts on a home PC on a DSL/cable modem connection and bypass anything which blocks based on URL, unless you use a "everything not explicitly allowed is denied" setup, which is kind of a hard sell in most companies.

Additionally, if you access these over a SSL connection, any proxies or content checkers won't see anything apart from the original URL so content scanning wouldn't work either...

Just goes to show, open one port on a firewall and be prepared for the fact that almost any content can come through....

    December
    28th,

    2004

    An object lesson in the importance of maintaining domain names

Over at cryptome.org there's a page - British Military Intelligence Website Hijacked

Looks like the MOD forgot or didn't want to renew the DNS for intelligencecorps.co.uk!

As a result someone in the US (cryptome say that it's a former british agent, not sure where that info. comes from) has registered the domain, and will be getting e-mails sent by people using the Intelligence Corps part of the mod site... (as well as any other mail that may be sent to that domain!!)

DNS management.. It's important!

    December
    24th,

    2004

    Article on the relationship between ITIL and InfoSec

SecurityFocus HOME Infocus: How ITIL Can Improve Information Security

Internesting article on ITIL and InfoSec.

    December
    23rd,

    2004

    Know Your Enemy stats.. Linux getting harder to compromise...

Martin McKeay's Network Security Blog: KYE Trend Analysis

An interesting entry over at Martin McKeay's blog covering the info. from the Honeynet Project about trends seen in compromise of systems on the Internet from their research..

Looks like Linux systems are getting harder to compromise out of the box, while the time to compromise windows systems goes down..

Hopefully the windows time will go up as more machines ship with SP2 on by default (thus giving the user enough time to get the patches, before they're compromised)

    December
    21st,

    2004

    WEP ... toast this time?

Interesting article at SecurityFocus  SecurityFocus  on new tools which are available, which can crack WEP keys much more quickly than you'd expect based on their key length...

Time to start using WPA!

    December
    19th,

    2004

    [OT] Amarok Rules....

Not really security related at all, but I thought I'd post about a really cool media player I've been using recently on Linux...  Amarok  has many cool features, but the ones I like best are..

- Catalogues all your songs reading all the tags and sorting by artist

- Cover manager, automatically grabs the covers for the CD's from amazon

- Nice statistics down the left side with things like "other albums by this artist" and "most popular song"

- looks really nice...

    December
    19th,

    2004

    Implications of SOX for Security Professionals

HNS - Sarbanes-Oxley: An Opportunity for Security Professionals

This is a quite interesting article presenting Sarbanes-Oxley as an opportunity for Information Security teams to prove their worth to businesses.

    December
    19th,

    2004

    Chip and PIN... is it as secure as they say...?

BBC NEWS | Business | 'Chip and pin' security warning

Interesting article over at the BBC where Ross Anderson (author of the excellent "Security Engineering") is questioning the security of the new (in the UK) Chip and PIN rollout.

He makes an interesting point, which is that if crooks can create fake readers they can set up business and use them to gather credit card details...

Now I'd like to think that this shouldn't be possible (or at least easy), I'd have expected something like a mutual authentication between card and reader or something like that to mitigate this kind of attack, however the quote on the story from the representitive of the Chip and PIN companies doesn't make me feel too comfortable

"We don't think they can use fake machines because the machines themselves are engineered to read the chip so they must be reading the chip very carefully.  That makes the transaction itself extremely secure."

Now that kind of implies to me that they're relying on the difficulty of creating a reader to protect the card details, I really hope there's more to it than that, because we've been shown that that kind of protection doesn't last...

    December
    18th,

    2004

    Very nasty vulnerability in IE

Massive IE phishing exploit discovered - ZDNet UK News

Well if anyone needed another reason to avoid using Internet Explorer, I think that this vulnerability provides it.

If you have a look at the demonstration at  secunia you get a very scary (if you're responsible for the security of an e-commerce site) demonstration.

As far as I can remember, this is the first vulnerability I've seen where the SSL padlock is useless as an indicator of what site you're on, with the closest phishers have got in the past being graphical representations of the toolbar which were far from flawless.

The reason this is scary, is that if you look at the advice given by many banks and e-commerce sites, checking the SSL certificate via the padlock plays a major part in confirming you're on the right site, so now if a customer gets caught by this there's almost nothing they can do to tell they're on a fake site...

nasty....

    November
    29th,

    2004

    Sensible comment on Google Desktop Search

Over at Schneier on Security, there's a refreshingly sensible piece on Google's desktop search.

As Bruce points out, all that information that people are getting so worried about being found by the tool is ALREADY THERE, so if there's a shared PC and you're worried about people seeing the data of other users... Don't give them the rights to see those areas!!

If you're worried that users using Internet Cafe's will expose corporate data by it being indexed when it's put on the Internet Cafe PC, set your policy and technical controls so that you're users don't put corporate data on untrusted machines!!

Sorry, but the flow of "Google desktop is evil" stories made me cranky...

    ← Newer

    Page: 42 of 54

    Older →

				© 2022 raesene with Jekyll. Theme: dbyll by dbtek.


text:
module Canary
  module Types
    module InputObjects
      class CharacterFavoriteOrder < Canary::Types::InputObjects::Base
        argument :field, Canary::Types::Enums::CharacterFavoriteOrderField, required: true
        argument :direction, Canary::Types::Enums::OrderDirection, required: true
      end
    end
  end
end


text:
<?php

repair_el_type_collate();


text:
from pprint import pprint
from django.dispatch import receiver
from .signals import pixel_data

@receiver(pixel_data)
def example_receiver(**kwargs):
    """Example receiver of pixel_data signal."""

    pixel_data = kwargs['pixel_data']
    pprint(pixel_data)


text:
<!DOCTYPE html>

    <meta charset="utf-8">

    <title>Integrating a FAKE build script into TeamCity
</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="FAKE - F# Make">
    <meta name="author" content="Steffen Forkmann, Mauricio Scheffer, Colin Bull">

    <link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet">
    <link type="text/css" rel="stylesheet" href="content/style.css" />

fsharp.org

github page

FAKE - F# Make

Integrating a FAKE build script into TeamCity

Easy TeamCity integration was one of the major goals for the FAKE build system.

In this article you will learn how to set up a FAKE build script in TeamCity. We will use the CalculatorSample which you can build from the getting started guide.

Installing TeamCity

You can download the free professional edition of TeamCity from http://www.jetbrains.com/teamcity/. After the installation process you should be ready to configure your first build.

Creating a FAKE project on TeamCity

Now create a new project and add a build configuration:

You also need to set the artifacts paths:

Attach a VCS root

The next step is to attach a VCS root. For this sample we will use the official FAKE repository at https://github.com/forki/FAKE/.

Creating the build step

Now is the time to create two build steps. The first one downloads FAKE via Nuget and the second one runs the build script:

If you want you could also add a build trigger to your build script:

Running the build

Now if everything is configured correctly, you can run your build and the output should look like:

You can also inspect the NUnit results:

FAKE - F# Make

Home page

Get FAKE via NuGet

Source Code on GitHub

License (Apache 2)

Release Notes

Contributing to FAKE

Who is using FAKE?

Ask a question

Tutorials

Getting started

Build script caching

NuGet package restore

Using FxCop in a build

Generating AssemblyInfo

Create NuGet packages

Running specific targets

Running FAKE from command line

Running targets in parallel

Using the F# compiler from FAKE

Creating custom tasks

Soft dependencies

TeamCity integration

Running canopy tests

Octopus Deploy

TypeScript support

Azure WebJobs support

Azure Cloud Services support

SQL DACPAC support

FluentMigrator support

Android publisher

File Watcher

WiX Setup Generation

Using Chocolatey

Using Slack

Using Microsoft Teams

Using SonarQube

Fake.Deploy

Fake.IIS

Reference

API Reference


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity name="BlhInformacionPublica" table="blh_informacion_publica">
    <id name="id" type="integer" column="id">
      <generator strategy="SEQUENCE"/>
    </id>
    <field name="path" type="string" column="path" length="255" nullable="false"/>
    <field name="tipo" type="string" column="tipo" length="15" nullable="false"/>
    <field name="nombreDocumento" type="string" column="nombre_documento" length="30" nullable="false"/>
    <field name="fechaPublicacion" type="date" column="fecha_publicacion" nullable="false"/>
    <field name="usuario" type="integer" column="usuario" nullable="true"/>
    <many-to-one field="idBancoDeLeche" target-entity="BlhBancoDeLeche">
      <join-columns>
        <join-column name="id_banco_de_leche" referenced-column-name="id"/>
      </join-columns>
    </many-to-one>
  </entity>
</doctrine-mapping>


text:
import uuid
import json
import records
import requests
import os

#
# from couchbase.bucket import Bucket

class Couchbase:
    def __init__(self, host, port, credentials):
        """
        access Couchbase Server

        :param host:
        :param port:
        :param credentials:

        """
        self.host = host
        self.port = port
        self.credentials = credentials

        self.user = self.credentials.get('user')
        self.password = self.credentials.get('password')

        self.headers_text = {'Content-Type': 'text/plain'}
        self.url = 'http://{}:{}/query/service'.format(host, port)

    def write(self, path, data, credentials):
        pass
        # self.db.insert()

    def read(self, data, bucket):
        """

        :param data: 'result' can be '*' or single fields
                     'lookup_key' matching key
                     'lookup_value' value to search for
        :param bucket: Data Bucket
        :return: result from DB-Query

        """

        try:
            result = data['result']
            lookup = data['lookup_key']
            lookup_value = data['lookup_value']
            if type(lookup_value) == str:
                lookup_value = '{!r}'.format(lookup_value)

        except Exception as exc:
            return exc

        if result == '*':
            result = '{}.*'.format(bucket)

        query = 'SELECT {} FROM {} WHERE {} = {}'.format(result, bucket, lookup, lookup_value)

        try:
            r = requests.post(self.url, data=query, headers=self.headers_text, auth=None)
        except Exception as exc:
            print(exc)

        if r.status_code == 404:
            print('not found', r.status_code)

        elif r.status_code == 200:

            response = r.json()
            response = response['results']

            return response

        else:
            print('response: {}'.format(r.status_code))

        return r.status_code

    def _request(self, args_to_come):
        pass

    def uuid(self):
        uid = str(uuid.uuid4())
        return uid

    def test(self, path, data):
        pass


text:
title: "Modules for Theming"
permalink: /docs/theming/
excerpt: "Cras mattis iudicium purus sit amet fermentum."
last_modified_at: 2021-01-04T15:19:22-04:00
toc: false
---

Cras mattis iudicium purus sit amet fermentum at nos hinc posthac, sitientis piros afros. Lorem ipsum dolor sit amet, consectetur adipisici elit, petierunt uti sibi concilium totius Galliae in diem sed eius mod tempor incidunt ut labore et dolore magna aliqua. Pellentesque habitant morbi tristique senectus et netus piros labore et dolore magna.


text:
require 'rubygems'
require 'post_haste'
require 'csv'
require 'date'
include PostHaste

loop do
  date = Date.today.to_s.gsub('-','')
  mv_web = MostViewed.all('web', 100)
  mv_mobile = MostViewed.all('mobile', 100)
  file_name = "csv/#{date}.csv"
  unless mv_web.empty?
    begin
      f = File.open(file_name)
      wh = f.size > 50 ? false : true
      f.close
    rescue
      wh = true
    end
    CSV.open(file_name, "a+", :write_headers => wh, :headers => ['date','platform','type','datetime','title','byline','url','rank']) do |row|
      mv_web.each do |mv|
        row << [mv.datetime.to_date, mv.platform, mv.type, mv.datetime, mv.title, mv.byline, mv.url, mv.rank]
      end
      mv_mobile.each do |mv|
        row << [mv.datetime.to_date, mv.platform, mv.type, mv.datetime, mv.title, mv.byline, mv.url, mv.rank]
      end
    end
    system 'git add csv/'
    system "git commit -m 'updated from #{mv_web.first.datetime.to_s}'"
    system 'git push origin master'
    sleep(3600)
  end
end


text:
package controller;

import javafx.event.EventHandler;
import javafx.scene.input.MouseEvent;
import view.SudokuButton;
import view.SudokuGridPane;

public class SudokuFieldController<T> implements EventHandler<MouseEvent> {

	SudokuGridPane sudoku;
	SudokuButton field;

	public SudokuFieldController(SudokuGridPane sudoku, SudokuButton b) {
		this.sudoku = sudoku;
		this.field = b;
	}

	@Override
	public void handle(MouseEvent event) {
		sudoku.setSelectedField(field);
	}

}


text:
from setuptools import setup

setup(name='evapy',
      version='0.2.0',
      license='MIT',
      description='Extreme value analysis of time series',
      keywords='extreme value statistics',
      url='https://github.com/4Subsea/evapy',
      author='4Subsea',
      author_email='ace@4subsea.com',
      packages=[
          'evapy'
      ],
      include_package_data=True,
      classifiers=[
          'Development Status :: 4 - Beta',
          'Intended Audience :: Other Audience',
          'Topic :: Scientific/Engineering',
          'Programming Language :: Python :: 3',
          'Programming Language :: Python :: 3.5',
          'Programming Language :: Python :: 3.6',
          'Programming Language :: Python :: 3.7',
          'License :: OSI Approved :: MIT License'
      ],
      install_requires=[
          'numpy',
          'scipy'
      ],
      zip_safe=False)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<TITLE>
Uses of Class org.apache.noggit.CharArr (Solr 4.2.1 API)
</TITLE>

<META NAME="date" CONTENT="2013-03-26">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.noggit.CharArr

Packages that use CharArr

org.apache.noggit
JSON streaming parser and serializer.

org.apache.solr.common.cloud
Common Solr Cloud and ZooKeeper related classes reused on both clients & server.

org.apache.solr.common.util
Common utility classes reused on both clients & server.

Uses of CharArr in org.apache.noggit

Fields in org.apache.noggit declared as CharArr

protected  CharArr
JSONWriter.out

Methods in org.apache.noggit that return CharArr

 CharArr
JSONParser.getNumberChars()

          Returns the characters of a JSON numeric value.

 CharArr
JSONParser.getStringChars()

          Returns the characters of a JSON string value, decoding any escaped characters.

 CharArr
CharArr.subSequence(int start,
            int end)

Methods in org.apache.noggit with parameters of type CharArr

 void
JSONParser.getNumberChars(CharArr output)

          Reads a JSON numeric value into the output.

 void
JSONParser.getString(CharArr output)

          Reads a JSON string into the output, decoding any escaped characters.

static void
JSONUtil.unicodeEscape(int ch,
              CharArr out)

 void
CharArr.write(CharArr arr)

static void
JSONUtil.writeBoolean(boolean val,
             CharArr out)

static void
JSONUtil.writeNull(CharArr out)

 void
JSONWriter.writeNumber(CharArr digits)

static void
JSONUtil.writeNumber(double number,
            CharArr out)

static void
JSONUtil.writeNumber(float number,
            CharArr out)

static void
JSONUtil.writeNumber(int number,
            CharArr out)

static void
JSONUtil.writeNumber(long number,
            CharArr out)

 void
JSONWriter.writePartialNumber(CharArr digits)

static void
JSONUtil.writeString(char[] val,
            int start,
            int end,
            CharArr out)

 void
JSONWriter.writeString(CharArr str)

static void
JSONUtil.writeString(CharArr val,
            CharArr out)

static void
JSONUtil.writeString(CharSequence val,
            int start,
            int end,
            CharArr out)

 void
JSONWriter.writeStringChars(CharArr partialStr)

static void
JSONUtil.writeStringPart(char[] val,
                int start,
                int end,
                CharArr out)

static void
JSONUtil.writeStringPart(CharSequence chars,
                int start,
                int end,
                CharArr out)

Constructors in org.apache.noggit with parameters of type CharArr

JSONWriter(CharArr out)

JSONWriter(CharArr out,
           int indentSize)

Uses of CharArr in org.apache.solr.common.cloud

Methods in org.apache.solr.common.cloud with parameters of type CharArr

static byte[]
ZkStateReader.toUTF8(CharArr out)

Uses of CharArr in org.apache.solr.common.util

Methods in org.apache.solr.common.util with parameters of type CharArr

static void
ByteUtils.UTF8toUTF16(byte[] utf8,
            int offset,
            int len,
            CharArr out)

          Convert UTF8 bytes into UTF16 characters.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

          Copyright © 2000-2013 Apache Software Foundation.  All Rights Reserved.


text:
namespace Sitecore.Ecommerce.Search
{
  using System.Collections.Generic;
  using Catalogs;
  using Links;
  using Lucene.Net.Documents;
  using Sitecore.Data;
  using Sitecore.Data.Items;
  using Sitecore.Search;

  /// <summary>
  /// Search result contoller
  /// </summary>
  public class SearchResultController
  {
    /// <summary>
    /// Initializes a new instance of the <see cref="SearchResultController"/> class.
    /// </summary>
    public SearchResultController()
    {
      this.ProductResolver = Context.Entity.Resolve<VirtualProductResolver>();
    }

    /// <summary>
    /// Gets or sets the product resolver.
    /// </summary>
    /// <value>The product resolver.</value>
    protected VirtualProductResolver ProductResolver { get; set; }

    /// <summary>
    /// Gets the search result.
    /// </summary>
    /// <param name="searchHits">The search hits.</param>
    /// <returns>Returns collection of search results</returns>
    public virtual IEnumerable<SearchResult> GetSearchResult(SearchHits searchHits)
    {
      List<SearchResult> result = new List<SearchResult>();
      foreach (SearchHit hit in searchHits.Slice(0))
      {
        SearchResult sr = new SearchResult();
        Item parentItem = null;
        Item resultItem = null;

        if (hit.Document.GetField(BuiltinFields.CatalogItemUri) != null)
        {
          string catalogUri = this.GetFieldValue(hit.Document, BuiltinFields.CatalogItemUri);
          if (!string.IsNullOrEmpty(catalogUri))
          {
            parentItem = Database.GetItem(new ItemUri(catalogUri));
            resultItem = Database.GetItem(new ItemUri(hit.Url));
            if (resultItem != null && parentItem != null)
            {
              sr.ResultItem.ItemLink = this.ProductResolver.GetVirtualProductUrl(parentItem, resultItem);
            }
          }
        }
        else
        {
          resultItem = Database.GetItem(new ItemUri(hit.Url));
          if (resultItem != null)
          {
            ////remove items without visualization from search result.
            if (resultItem.Visualization != null && resultItem.Visualization.Layout == null)
            {
              continue;
            }

            sr.ResultItem.ItemLink = LinkManager.GetItemUrl(resultItem);
            parentItem = resultItem.Parent;
          }
        }

        if (parentItem != null && resultItem != null)
        {
          sr.ResultItem.ItemTitle = this.GetItemTitle(resultItem);
          sr.ResultItem.ItemUri = hit.Url;

          sr.ParentItem.ItemLink = LinkManager.GetItemUrl(parentItem);
          sr.ParentItem.ItemTitle = this.GetItemTitle(parentItem);
          sr.ParentItem.ItemUri = parentItem.Uri.ToString();
        }

        result.Add(sr);
      }

      return result;
    }

    /// <summary>
    /// Gets the field value.
    /// </summary>
    /// <param name="doc">The document.</param>
    /// <param name="fieldName">Name of the field.</param>
    /// <returns>Returns field value from document.</returns>
    protected virtual string GetFieldValue(Document doc, string fieldName)
    {
      return StringUtil.GetString(new[] { doc.Get(fieldName) });
    }

    /// <summary>
    /// Gets the item title.
    /// </summary>
    /// <param name="item">The item to prceed.</param>
    /// <returns>Returns the item tetle field value or item name.</returns>
    protected virtual string GetItemTitle(Item item)
    {
      return !string.IsNullOrEmpty(item["Title"]) ? item["Title"] : item.Name;
    }
  }
}


text:
package com.urbanairship.octobot

import java.util.Properties
import javax.mail.{Message, Session, Transport, MessagingException, PasswordAuthentication}
import javax.mail.internet.{InternetAddress, MimeMessage}
import java.util.concurrent.ArrayBlockingQueue
import org.apache.log4j.Logger

// This class provides an internal queue allowing us to asynchronously
// send email notifications rather than processing them in main app loop.

object MailQueue extends Runnable {
  val logger = Logger.getLogger("Email Queue")
  val from = Settings.get("Octobot", "email_from")
  val recipient = Settings.get("Octobot", "email_to")
  val server = Settings.get("Octobot", "email_server")
  val username = Settings.get("Octobot", "email_username")
  val password = Settings.get("Octobot", "email_password")
  val port = Settings.getAsInt("Octobot", "email_port")
  val useSSL = Settings.getAsBoolean("Octobot", "email_ssl")
  val useAuth = Settings.getAsBoolean("Octobot", "email_auth")

  // This internal queue is backed by an ArrayBlockingQueue. By specifying the
  // number of messages to be held here before the queue blocks (below), we
  // provide ourselves a safety threshold in terms of how many messages could
  // be backed up before we force the delivery of all current waiting messages.
  val messages = new ArrayBlockingQueue[String](100)

  def put(message: String) {
    messages.put(message)
  }

  def size() : Int = {
    messages.size()
  }

  // As this thread runs, it consumes messages from the internal queue and
  // delivers each to the recipients configured in the YML file.
  override def run() {
    if (!validSettings()) {
      logger.error("Email settings invalid check your configuration.")
      return
    }

    while (true)
      deliverMessage(messages.take())
  }

  // Delivers email error notificiations.
  def deliverMessage(message: String) {
    logger.info("Sending error notification to: " + recipient)

    try {
      val email = prepareEmail()

      email.setFrom(new InternetAddress(from))
      email.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient))
      email.setSubject("Task Error Notification")
      email.setText(message)

      // Send message
      Transport.send(email)
      logger.info("Sent error e-mail to " + recipient + ". "
          + "Message: \n\n" + message)

    } catch {
      case ex: MessagingException =>
        logger.error("Error delivering error notification.", ex)
    }
  }

  // Prepares a sendable email object based on Octobot's SMTP, SSL, and
  // Authentication setup specified in its YML config file.
  def prepareEmail() : MimeMessage = {
    val properties = System.getProperties()
    properties.setProperty("mail.smtp.host", server)
    properties.put("mail.smtp.auth", "true")

    // Configure SSL.
    if (useSSL) {
      properties.put("mail.smtp.socketFactory.port", port.asInstanceOf[AnyRef])
      properties.put("mail.smtp.starttls.enable","true")
      properties.put("mail.smtp.socketFactory.fallback", "false")
      properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
    }

    // Configure authentication.
    val session = {
      if (useAuth) {
        properties.setProperty("mail.smtp.submitter", username)
        val authenticator = new Authenticator(username, password)
        Session.getInstance(properties, authenticator)
      } else {
        Session.getDefaultInstance(properties)
      }
    }

    new MimeMessage(session)
  }

  // Provides an SMTP authenticator for messages sent with auth.
  class Authenticator(val user: String, val pass: String, var authenticator: Authenticator)
    extends javax.mail.Authenticator {

    def this(user: String, pass: String) {
      this(user, pass, new PasswordAuthentication(username, password).asInstanceOf[Authenticator])
    }
  }

  // Validates Octobot's e-mail settings, ensuring that everything's here
  // before spawning the queue and preparing to batch out messages.
  def validSettings() : Boolean = {
    var valid = true

    // Validate base settings.
    List(from, recipient, server, port).foreach { setting =>
      if (setting == null) valid = false
    }

    // Validate authentication.
    if (useAuth && (username == null || password == null))
      valid = false

    valid
  }
}


text:
Spree::Api::ShipmentsController.class_eval do

  def add
    variant = Spree::Variant.find(params[:variant_id])
    quantity = params[:quantity].to_i

    @order.contents.add(variant, quantity, nil, @shipment)

    update_shipments

    respond_with(@shipment, default_template: :show)
  end

  def remove
    variant = Spree::Variant.find(params[:variant_id])
    quantity = params[:quantity].to_i

    @order.contents.remove(variant, quantity, @shipment)

    if @shipment.persisted?
      @shipment.reload
      update_shipments
    end

    respond_with(@shipment, default_template: :show)
  end

  def update_shipments
    begin
      Newgistics.update_shipment_items @shipment if @shipment.external_id
    rescue Exception => e
      Rails.logger.warn e
    end
    @order.updater.update
  end
end


text:
class View {
public:
    virtual void render(Window &window) = 0;

    // TODO input event system passing events down view stack
};

#endif


text:
for i in `seq 10`;
do
        { time radical-synapse-emulate -i ~/bin/84.json ; } 2>> ~/bin/time_results_emulate_supermic;
done

sed -n '/cannot/!p' ~/bin/time_results_emulate_supermic | sed -n '/open/!p' | grep . > time_results_cleaned_emulate_supermic


text:
import sys
import re
import textwrap
from fn import F
from lib.parse_args import add_common_arguments
from lib.d3_fn import cons
from lib.d3_io import load_datasets, save_datasets
from lib.d3_utils import pct_change, flatten_expressions
import numpy as np

from math import *

def get_argument_settings():
    """@todo: Docstring for get_argument_settings.

    :returns: @todo

    """
    description = textwrap.dedent("""
    Joins two delimited files by common keys.
    """)

    epilog = textwrap.dedent("""

    Examples:

    """)

    m_overrides = []
    parser = add_common_arguments(m_overrides, description=description,
                                  epilog=epilog)
    parser.add_argument('--oc', '--output-columns',
                        dest='output_columns',
                        default=None,
                        required=False,
                        action='append',
                        help='XXX'
                        'XXX')

    parser.add_argument('--cw', '--output-columns-widths',
                        dest='column_widths',
                        default=None,
                        required=False,
                        action='append',
                        help='XXX'
                        'XXX')

    parser.add_argument('-m', '--monkey-readable',
                        dest='monkey_readable',
                        default=False,
                        required=False,
                        action='store_true',
                        help='XXX'
                        'XXX')

    return parser

def main():
    """@todo: Docstring for main.

    :returns: @todo

    """

    parser = get_argument_settings()
    args = parser.parse_args()

    delimiter = args.delimiter
    output_columns = (args.output_columns and flatten_expressions(args.output_columns, sep=r'\s*[,;]\s*')) or None
    column_widths = (args.column_widths and flatten_expressions(args.column_widths, sep=r'\s*[,;]\s*')) or None
    column_widths = (column_widths and map(lambda x: re.split('\s*:\s*', x), column_widths)) or None
    if column_widths:
        d = {}
        for k, v in column_widths:
            d[k] = v
        column_widths = d
    else:
        column_widths = {}

    input_files = args.input_files or [sys.stdin]
    data = map(F(load_datasets, delimiter), input_files)

    result = save_datasets(data, args.output_file,
                           delimiter=delimiter,
                           monkey_readable=args.monkey_readable,
                           columns=output_columns,
                           column_widths=column_widths)

    return result

if __name__ == '__main__':
    main()


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="JavaScriptLibraryMappings">
    <file url="file://$PROJECT_DIR$" libraries="{asus-router-web-scripts node_modules}" />
  </component>
</project>


text:
package org.overlord.rtgov.ui.client.local.services;

import java.util.List;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

import org.jboss.errai.common.client.api.Caller;
import org.jboss.errai.common.client.api.ErrorCallback;
import org.jboss.errai.common.client.api.RemoteCallback;
import org.overlord.rtgov.ui.client.local.services.rpc.DelegatingErrorCallback;
import org.overlord.rtgov.ui.client.local.services.rpc.DelegatingRemoteCallback;
import org.overlord.rtgov.ui.client.local.services.rpc.IRpcServiceInvocationHandler;
import org.overlord.rtgov.ui.client.model.QName;
import org.overlord.rtgov.ui.client.model.ReferenceBean;
import org.overlord.rtgov.ui.client.model.ServiceBean;
import org.overlord.rtgov.ui.client.model.ServiceResultSetBean;
import org.overlord.rtgov.ui.client.model.ServicesFilterBean;
import org.overlord.rtgov.ui.client.model.UiException;
import org.overlord.rtgov.ui.client.shared.services.IServicesService;

/**
 * Client-side service for making RPC calls to the remote deployments service.
 *
 * @author eric.wittmann@redhat.com
 */
@ApplicationScoped
public class ServicesRpcService {

    @Inject
    private Caller<IServicesService> remoteServicesService;

    /**
     * Constructor.
     */
    public ServicesRpcService() {
    }

    /**
     * @see org.overlord.rtgov.ui.client.shared.services.IServicesService#getApplicationNames()
     */
    public void getApplicationNames(final IRpcServiceInvocationHandler<List<QName>> handler) {
        RemoteCallback<List<QName>> successCallback = new DelegatingRemoteCallback<List<QName>>(handler);
        ErrorCallback<?> errorCallback = new DelegatingErrorCallback(handler);
        try {
            remoteServicesService.call(successCallback, errorCallback).getApplicationNames();
        } catch (UiException e) {
            errorCallback.error(null, e);
        }
    }

    /**
     * @see org.overlord.rtgov.ui.client.shared.services.IServicesService#findServices(ServicesFilterBean, int, String, boolean)
     */
    public void findServices(ServicesFilterBean filters, int page, String sortColumn, boolean ascending,
            final IRpcServiceInvocationHandler<ServiceResultSetBean> handler) {
        // TODO only allow one search at a time.  If another search comes in before the previous one
        // finished, cancel the previous one.  In other words, only return the results of the *last*
        // search performed.
        RemoteCallback<ServiceResultSetBean> successCallback = new DelegatingRemoteCallback<ServiceResultSetBean>(handler);
        ErrorCallback<?> errorCallback = new DelegatingErrorCallback(handler);
        try {
            remoteServicesService.call(successCallback, errorCallback).findServices(filters, page, sortColumn, ascending);
        } catch (UiException e) {
            errorCallback.error(null, e);
        }
    }

    /**
     * @see org.overlord.rtgov.ui.client.shared.services.IServicesService#getService(String)
     */
    public void getService(String serviceId, IRpcServiceInvocationHandler<ServiceBean> handler) {
        RemoteCallback<ServiceBean> successCallback = new DelegatingRemoteCallback<ServiceBean>(handler);
        ErrorCallback<?> errorCallback = new DelegatingErrorCallback(handler);
        try {
            remoteServicesService.call(successCallback, errorCallback).getService(serviceId);
        } catch (UiException e) {
            errorCallback.error(null, e);
        }
    }

    /**
     * @see org.overlord.rtgov.ui.client.shared.services.IServicesService#getReference(String)
     */
    public void getReference(String referenceId, IRpcServiceInvocationHandler<ReferenceBean> handler) {
        RemoteCallback<ReferenceBean> successCallback = new DelegatingRemoteCallback<ReferenceBean>(handler);
        ErrorCallback<?> errorCallback = new DelegatingErrorCallback(handler);
        try {
            remoteServicesService.call(successCallback, errorCallback).getReference(referenceId);
        } catch (UiException e) {
            errorCallback.error(null, e);
        }
    }

}


text:
package processor

import (
	"github.com/servehub/utils/gabs"
)

type AnchorMerger struct{}

func (t AnchorMerger) Process(tree *gabs.Container) error {
	return Repeat(3, func() error {
		return ProcessAll(tree, func(ktype string, output *gabs.Container, value interface{}, key interface{}) error {
			if ktype == "map" && key == "<<" {
				if mmap, ok := value.(map[string]interface{}); ok {
					for k, v := range mmap {
						if !output.Exists(k) {
							output.Set(v, k)
						}
					}

					return output.Delete("<<")
				}
			}

			return nil
		})
	})
}


text:
'use strict';

module.exports = require('../jest.base')(__dirname);


text:
using UnityEditor;
using UnityEngine;
using System.Collections;

namespace RootMotion.FinalIK {

	/*
	 * Custom inspector for LookAtIK.
	 * */
	[CustomEditor(typeof(LookAtIK))]
	public class LookAtIKInspector : IKInspector {

		private LookAtIK script { get { return target as LookAtIK; }}

		protected override MonoBehaviour GetMonoBehaviour(out int executionOrder) {
			executionOrder = 9997;
			return script;
		}

		protected override void OnApplyModifiedProperties() {
			if (!Application.isPlaying) script.solver.Initiate(script.transform);
		}

		protected override void AddInspector() {
			// Draw the inspector for IKSolverTrigonometric
			IKSolverLookAtInspector.AddInspector(solver, !Application.isPlaying, true);

			// Warning box
			if (!script.solver.IsValid(false)) AddWarningBox(script.solver);
		}

		void OnSceneGUI() {
			// Draw the scene veiw helpers
			IKSolverLookAtInspector.AddScene(script.solver, new Color(0f, 1f, 1f, 1f), true);
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<rootTag>
  <Award>
    <AwardTitle>CSR: Workshop: Computing Clouds for Cyber Physical Systems (CC-4-CPS), March 14-15, 2013, Arlington, VA</AwardTitle>
    <AwardEffectiveDate>09/15/2012</AwardEffectiveDate>
    <AwardExpirationDate>08/31/2014</AwardExpirationDate>
    <AwardAmount>73738</AwardAmount>
    <AwardInstrument>
      <Value>Standard Grant</Value>
    </AwardInstrument>
    <Organization>
      05050000
      <Directorate>
        <LongName>Direct For Computer & Info Scie & Enginr</LongName>
      </Directorate>
      <Division>
        <LongName>Division Of Computer and Network Systems</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>M. Mimi McClure</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration>This award allows the PIs to plan and run an NSF-sponsored workshop on the topic of ?Computing Clouds for Cyber-Physical Systems?. This workshop is to be held in Arlington, VA on March 14th and 15th, 2013</AbstractNarration>
    <MinAmdLetterDate>09/10/2012</MinAmdLetterDate>
    <MaxAmdLetterDate>09/10/2012</MaxAmdLetterDate>
    <ARRAAmount/>
    <AwardID>1255247</AwardID>
    <Investigator>
      <FirstName>Douglas</FirstName>
      <LastName>Schmidt</LastName>
      <EmailAddress>douglas.c.schmidt@vanderbilt.edu</EmailAddress>
      <StartDate>09/10/2012</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Investigator>
      <FirstName>Christopher</FirstName>
      <LastName>Gill</LastName>
      <EmailAddress>cdgill@cse.wustl.edu</EmailAddress>
      <StartDate>09/10/2012</StartDate>
      <EndDate/>
      <RoleCode>Co-Principal Investigator</RoleCode>
    </Investigator>
    <Investigator>
      <FirstName>Christopher</FirstName>
      <LastName>White</LastName>
      <EmailAddress>julesw@vt.edu</EmailAddress>
      <StartDate>09/10/2012</StartDate>
      <EndDate/>
      <RoleCode>Co-Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>Vanderbilt University</Name>
      <CityName>Nashville</CityName>
      <ZipCode>372350002</ZipCode>
      <PhoneNumber>6153222631</PhoneNumber>
      <StreetAddress>Sponsored Programs Administratio</StreetAddress>
      <CountryName>United States</CountryName>
      <StateName>Tennessee</StateName>
      <StateCode>TN</StateCode>
    </Institution>
    <ProgramElement>
      1714
      <Text>SPECIAL PROJECTS - CISE</Text>
    </ProgramElement>
    <ProgramReference>
      9150
      <Text>EXP PROG TO STIM COMP RES</Text>
    </ProgramReference>
    <ProgramReference>
      7556
      <Text>CONFERENCE AND WORKSHOPS</Text>
    </ProgramReference>
  </Award>
</rootTag>


text:
'use strict';

hexo.extend.helper.register('wordcount', require('./lib/helper'));


text:
/*
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.github.sakserv.minicluster.impl;

import com.github.sakserv.minicluster.config.ConfigVars;
import com.github.sakserv.minicluster.config.PropertyParser;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.sql.*;

import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

public class HsqldbLocalServerIntegrationTest {

    // Logger
    private static final Logger LOG = LoggerFactory.getLogger(HsqldbLocalServerIntegrationTest.class);

    // Setup the property parser
    private static PropertyParser propertyParser;
    static {
        try {
            propertyParser = new PropertyParser(ConfigVars.DEFAULT_PROPS_FILE);
            propertyParser.parsePropsFile();
        } catch(IOException e) {
            LOG.error("Unable to load property file: " + propertyParser.getProperty(ConfigVars.DEFAULT_PROPS_FILE));
        }
    }

    private static HsqldbLocalServer hsqldbLocalServer;

    @BeforeClass
    public static void setUp() throws Exception {
        hsqldbLocalServer = new HsqldbLocalServer.Builder()
            .setHsqldbHostName(propertyParser.getProperty(ConfigVars.HSQLDB_HOSTNAME_KEY))
            .setHsqldbPort(propertyParser.getProperty(ConfigVars.HSQLDB_PORT_KEY))
            .setHsqldbTempDir(propertyParser.getProperty(ConfigVars.HSQLDB_TEMP_DIR_KEY))
            .setHsqldbDatabaseName(propertyParser.getProperty(ConfigVars.HSQLDB_DATABASE_NAME_KEY))
            .setHsqldbCompatibilityMode(propertyParser.getProperty(ConfigVars.HSQLDB_COMPATIBILITY_MODE_KEY))
            .setHsqldbJdbcDriver(propertyParser.getProperty(ConfigVars.HSQLDB_JDBC_DRIVER_KEY))
            .setHsqldbJdbcConnectionStringPrefix(propertyParser.getProperty(
                    ConfigVars.HSQLDB_JDBC_CONNECTION_STRING_PREFIX_KEY))
            .build();
        hsqldbLocalServer.start();
    }

    @AfterClass
    public static void tearDown() throws Exception {
        hsqldbLocalServer.stop();
    }

    @Test
    public void testHsqldbLocalServer() throws ClassNotFoundException, SQLException {

        LOG.info("HSQLDB: Loading the JDBC Driver: " + propertyParser.getProperty(ConfigVars.HSQLDB_JDBC_DRIVER_KEY));
        Class.forName(propertyParser.getProperty(ConfigVars.HSQLDB_JDBC_DRIVER_KEY));

        // Get the connection
        Connection connection = DriverManager.getConnection(
                propertyParser.getProperty(ConfigVars.HSQLDB_JDBC_CONNECTION_STRING_PREFIX_KEY) +
                propertyParser.getProperty(ConfigVars.HSQLDB_HOSTNAME_KEY) + ":" +
                propertyParser.getProperty(ConfigVars.HSQLDB_PORT_KEY) + "/" +
                propertyParser.getProperty(ConfigVars.HSQLDB_DATABASE_NAME_KEY),
                "SA", "");
        LOG.info("DETAILS: " + connection.getMetaData().getURL());
        assertThat(connection.getMetaData().getURL(),
                containsString(propertyParser.getProperty(ConfigVars.HSQLDB_DATABASE_NAME_KEY)));
    }

    @Test
    public void testHsqldbMysqlCompatibilityMode() throws SQLException {
        Connection connection = DriverManager.getConnection(
                propertyParser.getProperty(ConfigVars.HSQLDB_JDBC_CONNECTION_STRING_PREFIX_KEY) +
                        propertyParser.getProperty(ConfigVars.HSQLDB_HOSTNAME_KEY) + ":" +
                        propertyParser.getProperty(ConfigVars.HSQLDB_PORT_KEY) + "/" +
                        propertyParser.getProperty(ConfigVars.HSQLDB_DATABASE_NAME_KEY),
                "SA", "");
        Statement statement = connection.createStatement();
        statement.executeQuery(hsqldbLocalServer.getHsqldbCompatibilityModeStatement());

        statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery("SELECT PROPERTY_VALUE FROM INFORMATION_SCHEMA.SYSTEM_PROPERTIES WHERE PROPERTY_NAME = 'sql.syntax_mys'");
        while(resultSet.next()) {
            assertTrue(Boolean.parseBoolean(resultSet.getString(1)));
        }
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package stallone.ui;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import static stallone.api.API.*;
import stallone.api.doubles.IDoubleArray;
import stallone.api.ints.IIntArray;

import stallone.util.Arguments;

/**
 *
 * @author noe
 */
public class MSM_Connectivity
{
    public static void main(String[] args)
            throws FileNotFoundException, IOException
    {
        if (args.length == 0)
        {
            System.out.println("MSM_Connectivity -iC <count-matrix> [-oGiant <file>]");
            System.out.println();
            System.out.println("Calculates the connectivity (strong components) of the specified count matrix. -oGiant writes out the giant component");
            System.exit(0);
        }

        Arguments arg = new Arguments(args);

        IDoubleArray C = doublesNew.fromFile(arg.getArgument("iC"));
        List<IIntArray> components = graph.connectedComponents(C);
        int[] I = intArrays.sortedIndexes(intseq.lengths(components));

        System.out.println("Strong Components: "+I.length);
        System.out.println("Lengths: "+intArrays.toString(I,", "));
        System.out.println("members: ");
        for (int i=0; i<I.length; i++)
        {
            IIntArray c = components.get(I[i]);
            System.out.println(ints.toString(c)+" ");
        }

        if (arg.hasCommand("oGiant"))
        {
            io.writeString(arg.getArgument("oGiant"), ints.toString(components.get(I[0]),"\n"));
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Page settings — PHPRtfLite v1.x documentation</title>
    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="PHPRtfLite v1.x documentation" href="index.html" />
    <link rel="next" title="Sections" href="sections.html" />
    <link rel="prev" title="Getting started" href="getting-started.html" />

Navigation

          index

          next |

          previous |

PHPRtfLite v1.x documentation »

Page settings¶

Page layout¶

Page orientation¶

You can use between <tt class="docutils literal">landscape</tt> and <tt class="docutils literal">portrait</tt> (default) page orientation.

<?php
// rtf document instance
$rtf = new PHPRtfLite();
// landscape page orientation
$rtf->setLandscape();

Page margins¶

You can set margins for the document and for sections, too. Section margins will overwrite document margins.

<?php
$rtf = new PHPRtfLite();
// margin left: 1cm
$rtf->setMarginLeft(1);
// margin right: 2cm
$rtf->setMarginRight(2);
// margin top: 3cm
$rtf->setMarginTop(3);
// margin bottom: 4cm
$rtf->setMarginBottom(4);

The code example below does the same in a shorter way.

<?php
$rtf = new PHPRtfLite();
// margins: left 1cm, top 3cm, right 2cm, bottom 4cm
$rtf->setMargins(1, 3, 2, 4);

You can define that odd and even pages uses mirrored margins.

<?php
$rtf = new PHPRtfLite();
// margin left: 2cm
$rtf->setMarginLeft(2);
// margin right: 1cm
$rtf->setMarginRight(1);
// odd pages: left 2cm, right 1 cm
// even pages: left 1cm, right 2 cm
$rtf->setMirrorMarings();

Page width / page height¶

<?php
$rtf = new PHPRtfLite();
$rtf->setPageWidth(14);  // in cm
$rtf->setPageHeight(25); // in cm

Character set (text input)¶

<?php
$rtf = new PHPRtfLite();
$rtf->setCharset('Latin1');  // use Latin1 instead of UTF-8

Hyphenation¶

<?php
$rtf = new PHPRtfLite();
$rtf->setHyphenation();

Table Of Contents

Page settings

Page layout

Page orientation

Page margins

Page width / page height

Character set (text input)

Hyphenation

Previous topic

Getting started

Next topic

Sections

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" size="18" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          next |

          previous |

PHPRtfLite v1.x documentation »

        © Copyright 2011, sigmaz.
      Created using Sphinx 1.0.7.


text:
namespace cmdline = utils::cmdline;

/// Creates a new command.
///
/// \param name_ The name of the command.  Must be unique within the context of
///     a program and have no spaces.
/// \param arg_list_ A textual description of the arguments received by the
///     command.  May be empty.
/// \param min_args_ The minimum number of arguments required by the command.
/// \param max_args_ The maximum number of arguments required by the command.
///     -1 means infinity.
/// \param short_description_ A description of the purpose of the command.
cmdline::command_proto::command_proto(const std::string& name_,
                                      const std::string& arg_list_,
                                      const int min_args_,
                                      const int max_args_,
                                      const std::string& short_description_) :
    _name(name_),
    _arg_list(arg_list_),
    _min_args(min_args_),
    _max_args(max_args_),
    _short_description(short_description_)
{
    PRE(name_.find(' ') == std::string::npos);
    PRE(max_args_ == -1 || min_args_ <= max_args_);
}

/// Destructor for a command.
cmdline::command_proto::~command_proto(void)
{
    for (options_vector::const_iterator iter = _options.begin();
         iter != _options.end(); iter++)
        delete *iter;
}

/// Internal method to register a dynamically-allocated option.
///
/// Always use add_option() from subclasses to add options.
///
/// \param option_ The option to add.  Must have been dynamically allocated.
///     This grabs ownership of the pointer, which is released when the command
///     is destroyed.
void
cmdline::command_proto::add_option_ptr(const cmdline::base_option* option_)
{
    try {
        _options.push_back(option_);
    } catch (...) {
        delete option_;
        throw;
    }
}

/// Processes the command line based on the command description.
///
/// \param args The raw command line to be processed.
///
/// \return An object containing the list of options and free arguments found in
/// args.
///
/// \throw cmdline::usage_error If there is a problem processing the command
///     line.  This error is caused by invalid input from the user.
cmdline::parsed_cmdline
cmdline::command_proto::parse_cmdline(const cmdline::args_vector& args) const
{
    PRE(name() == args[0]);
    const parsed_cmdline cmdline = cmdline::parse(args, options());

    const int argc = cmdline.arguments().size();
    if (argc < _min_args)
        throw usage_error("Not enough arguments");
    if (_max_args != -1 && argc > _max_args)
        throw usage_error("Too many arguments");

    return cmdline;
}

/// Gets the name of the command.
///
/// \return The command name.
const std::string&
cmdline::command_proto::name(void) const
{
    return _name;
}

/// Gets the textual representation of the arguments list.
///
/// \return The description of the arguments list.
const std::string&
cmdline::command_proto::arg_list(void) const
{
    return _arg_list;
}

/// Gets the description of the purpose of the command.
///
/// \return The description of the command.
const std::string&
cmdline::command_proto::short_description(void) const
{
    return _short_description;
}

/// Gets the definition of the options accepted by the command.
///
/// \return The list of options.
const cmdline::options_vector&
cmdline::command_proto::options(void) const
{
    return _options;
}

/// Creates a new command.
///
/// \param name_ The name of the command.  Must be unique within the context of
///     a program and have no spaces.
/// \param arg_list_ A textual description of the arguments received by the
///     command.  May be empty.
/// \param min_args_ The minimum number of arguments required by the command.
/// \param max_args_ The maximum number of arguments required by the command.
///     -1 means infinity.
/// \param short_description_ A description of the purpose of the command.
cmdline::base_command_no_data::base_command_no_data(
    const std::string& name_,
    const std::string& arg_list_,
    const int min_args_,
    const int max_args_,
    const std::string& short_description_) :
    command_proto(name_, arg_list_, min_args_, max_args_, short_description_)
{
}

/// Entry point for the command.
///
/// This delegates execution to the run() abstract function after the command
/// line provided in args has been parsed.
///
/// If this function returns, the command is assumed to have been executed
/// successfully.  Any error must be reported by means of exceptions.
///
/// \param ui Object to interact with the I/O of the command.  The command must
///     always use this object to write to stdout and stderr.
/// \param args The command line passed to the command broken by word, which
///     includes options and arguments.
///
/// \return The exit code that the program has to return.  0 on success, some
///     other value on error.
/// \throw usage_error If args is invalid (i.e. if the options are mispecified
///     or if the arguments are invalid).
int
cmdline::base_command_no_data::main(cmdline::ui* ui,
                                    const cmdline::args_vector& args)
{
    return run(ui, parse_cmdline(args));
}


text:
// Package ipamapi specifies the contract the IPAM service (built-in or remote) needs to satisfy.
package ipamapi

import (
	"net"

	"github.com/docker/libnetwork/discoverapi"
	"github.com/docker/libnetwork/types"
)

/********************
 * IPAM plugin types
 ********************/

const (
	// DefaultIPAM is the name of the built-in default ipam driver
	DefaultIPAM = "default"
	// NullIPAM is the name of the built-in null ipam driver
	NullIPAM = "null"
	// PluginEndpointType represents the Endpoint Type used by Plugin system
	PluginEndpointType = "IpamDriver"
	// RequestAddressType represents the Address Type used when requesting an address
	RequestAddressType = "RequestAddressType"
)

// Callback provides a Callback interface for registering an IPAM instance into LibNetwork
type Callback interface {
	// RegisterIpamDriver provides a way for Remote drivers to dynamically register with libnetwork
	RegisterIpamDriver(name string, driver Ipam) error
	// RegisterIpamDriverWithCapabilities provides a way for Remote drivers to dynamically register with libnetwork and specify cpaabilities
	RegisterIpamDriverWithCapabilities(name string, driver Ipam, capability *Capability) error
}

/**************
 * IPAM Errors
 **************/

// Well-known errors returned by IPAM
var (
	ErrIpamInternalError   = types.InternalErrorf("IPAM Internal Error")
	ErrInvalidAddressSpace = types.BadRequestErrorf("Invalid Address Space")
	ErrInvalidPool         = types.BadRequestErrorf("Invalid Address Pool")
	ErrInvalidSubPool      = types.BadRequestErrorf("Invalid Address SubPool")
	ErrInvalidRequest      = types.BadRequestErrorf("Invalid Request")
	ErrPoolNotFound        = types.BadRequestErrorf("Address Pool not found")
	ErrOverlapPool         = types.ForbiddenErrorf("Address pool overlaps with existing pool on this address space")
	ErrNoAvailablePool     = types.NoServiceErrorf("No available pool")
	ErrNoAvailableIPs      = types.NoServiceErrorf("No available addresses on this pool")
	ErrIPAlreadyAllocated  = types.ForbiddenErrorf("Address already in use")
	ErrIPOutOfRange        = types.BadRequestErrorf("Requested address is out of range")
	ErrPoolOverlap         = types.ForbiddenErrorf("Pool overlaps with other one on this address space")
	ErrBadPool             = types.BadRequestErrorf("Address space does not contain specified address pool")
)

/*******************************
 * IPAM Service Interface
 *******************************/

// Ipam represents the interface the IPAM service plugins must implement
// in order to allow injection/modification of IPAM database.
type Ipam interface {
	discoverapi.Discover

	// GetDefaultAddressSpaces returns the default local and global address spaces for this ipam
	GetDefaultAddressSpaces() (string, string, error)
	// RequestPool returns an address pool along with its unique id. Address space is a mandatory field
	// which denotes a set of non-overlapping pools. pool describes the pool of addresses in CIDR notation.
	// subpool indicates a smaller range of addresses from the pool, for now it is specified in CIDR notation.
	// Both pool and subpool are non mandatory fields. When they are not specified, Ipam driver may choose to
	// return a self chosen pool for this request. In such case the v6 flag needs to be set appropriately so
	// that the driver would return the expected ip version pool.
	RequestPool(addressSpace, pool, subPool string, options map[string]string, v6 bool) (string, *net.IPNet, map[string]string, error)
	// ReleasePool releases the address pool identified by the passed id
	ReleasePool(poolID string) error
	// Request address from the specified pool ID. Input options or required IP can be passed.
	RequestAddress(string, net.IP, map[string]string) (*net.IPNet, map[string]string, error)
	// Release the address from the specified pool ID
	ReleaseAddress(string, net.IP) error
}

// Capability represents the requirements and capabilities of the IPAM driver
type Capability struct {
	RequiresMACAddress bool
}