text:
package org.apache.camel.builder.endpoint.dsl;

import javax.annotation.Generated;
import org.apache.camel.builder.EndpointConsumerBuilder;
import org.apache.camel.builder.EndpointProducerBuilder;
import org.apache.camel.builder.endpoint.AbstractEndpointBuilder;

/**
 * The cm-sms component allows to integrate with CM SMS Gateway.
 *
 * Generated by camel-package-maven-plugin - do not edit this file!
 */
@Generated("org.apache.camel.maven.packaging.EndpointDslMojo")
public interface CMEndpointBuilderFactory {

    /**
     * Builder for endpoint for the CM SMS Gateway component.
     */
    public interface CMEndpointBuilder extends EndpointProducerBuilder {
        default AdvancedCMEndpointBuilder advanced() {
            return (AdvancedCMEndpointBuilder) this;
        }
        /**
         * This is the sender name. The maximum length is 11 characters.
         *
         * The option is a: java.lang.String type.
         *
         * Required: true
         * Group: producer
         */
        default CMEndpointBuilder defaultFrom(String defaultFrom) {
            setProperty("defaultFrom", defaultFrom);
            return this;
        }
        /**
         * If it is a multipart message forces the max number. Message can be
         * truncated. Technically the gateway will first check if a message is
         * larger than 160 characters, if so, the message will be cut into
         * multiple 153 characters parts limited by these parameters.
         *
         * The option is a: int type.
         *
         * Group: producer
         */
        default CMEndpointBuilder defaultMaxNumberOfParts(
                int defaultMaxNumberOfParts) {
            setProperty("defaultMaxNumberOfParts", defaultMaxNumberOfParts);
            return this;
        }
        /**
         * If it is a multipart message forces the max number. Message can be
         * truncated. Technically the gateway will first check if a message is
         * larger than 160 characters, if so, the message will be cut into
         * multiple 153 characters parts limited by these parameters.
         *
         * The option will be converted to a int type.
         *
         * Group: producer
         */
        default CMEndpointBuilder defaultMaxNumberOfParts(
                String defaultMaxNumberOfParts) {
            setProperty("defaultMaxNumberOfParts", defaultMaxNumberOfParts);
            return this;
        }
        /**
         * The unique token to use.
         *
         * The option is a: java.lang.String type.
         *
         * Required: true
         * Group: producer
         */
        default CMEndpointBuilder productToken(String productToken) {
            setProperty("productToken", productToken);
            return this;
        }
        /**
         * Whether to test the connection to the SMS Gateway on startup.
         *
         * The option is a: boolean type.
         *
         * Group: producer
         */
        default CMEndpointBuilder testConnectionOnStartup(
                boolean testConnectionOnStartup) {
            setProperty("testConnectionOnStartup", testConnectionOnStartup);
            return this;
        }
        /**
         * Whether to test the connection to the SMS Gateway on startup.
         *
         * The option will be converted to a boolean type.
         *
         * Group: producer
         */
        default CMEndpointBuilder testConnectionOnStartup(
                String testConnectionOnStartup) {
            setProperty("testConnectionOnStartup", testConnectionOnStartup);
            return this;
        }
    }

    /**
     * Advanced builder for endpoint for the CM SMS Gateway component.
     */
    public interface AdvancedCMEndpointBuilder
            extends
                EndpointProducerBuilder {
        default CMEndpointBuilder basic() {
            return (CMEndpointBuilder) this;
        }
        /**
         * Whether the endpoint should use basic property binding (Camel 2.x) or
         * the newer property binding with additional capabilities.
         *
         * The option is a: boolean type.
         *
         * Group: advanced
         */
        default AdvancedCMEndpointBuilder basicPropertyBinding(
                boolean basicPropertyBinding) {
            setProperty("basicPropertyBinding", basicPropertyBinding);
            return this;
        }
        /**
         * Whether the endpoint should use basic property binding (Camel 2.x) or
         * the newer property binding with additional capabilities.
         *
         * The option will be converted to a boolean type.
         *
         * Group: advanced
         */
        default AdvancedCMEndpointBuilder basicPropertyBinding(
                String basicPropertyBinding) {
            setProperty("basicPropertyBinding", basicPropertyBinding);
            return this;
        }
        /**
         * Sets whether synchronous processing should be strictly used, or Camel
         * is allowed to use asynchronous processing (if supported).
         *
         * The option is a: boolean type.
         *
         * Group: advanced
         */
        default AdvancedCMEndpointBuilder synchronous(boolean synchronous) {
            setProperty("synchronous", synchronous);
            return this;
        }
        /**
         * Sets whether synchronous processing should be strictly used, or Camel
         * is allowed to use asynchronous processing (if supported).
         *
         * The option will be converted to a boolean type.
         *
         * Group: advanced
         */
        default AdvancedCMEndpointBuilder synchronous(String synchronous) {
            setProperty("synchronous", synchronous);
            return this;
        }
    }
    /**
     * CM SMS Gateway (camel-cm-sms)
     * The cm-sms component allows to integrate with CM SMS Gateway.
     *
     * Category: mobile
     * Available as of version: 2.18
     * Maven coordinates: org.apache.camel:camel-cm-sms
     *
     * Syntax: cm-sms:host
     *
     * Path parameter: host (required)
     * SMS Provider HOST with scheme
     */
    default CMEndpointBuilder cM(String path) {
        class CMEndpointBuilderImpl extends AbstractEndpointBuilder implements CMEndpointBuilder, AdvancedCMEndpointBuilder {
            public CMEndpointBuilderImpl(String path) {
                super("cm-sms", path);
            }
        }
        return new CMEndpointBuilderImpl(path);
    }
}


text:
#include <unistd.h>

#include <iostream>
#include <thread>

#include "gtest/gtest.h"

#include "ray/common/status.h"

#include "ray/object_manager/object_manager.h"

namespace {
std::string store_executable;
int64_t wait_timeout_ms;
}  // namespace

namespace ray {

using rpc::GcsNodeInfo;

static inline void flushall_redis(void) {
  redisContext *context = redisConnect("127.0.0.1", 6379);
  freeReplyObject(redisCommand(context, "FLUSHALL"));
  redisFree(context);
}

class MockServer {
 public:
  MockServer(boost::asio::io_service &main_service,
             const ObjectManagerConfig &object_manager_config,
             std::shared_ptr<gcs::GcsClient> gcs_client)
      : node_id_(ClientID::FromRandom()),
        config_(object_manager_config),
        gcs_client_(gcs_client),
        object_manager_(main_service, node_id_, object_manager_config,
                        std::make_shared<ObjectDirectory>(main_service, gcs_client_)) {
    RAY_CHECK_OK(RegisterGcs(main_service));
  }

  ~MockServer() { RAY_CHECK_OK(gcs_client_->Nodes().UnregisterSelf()); }

 private:
  ray::Status RegisterGcs(boost::asio::io_service &io_service) {
    auto object_manager_port = object_manager_.GetServerPort();
    GcsNodeInfo node_info;
    node_info.set_node_id(node_id_.Binary());
    node_info.set_node_manager_address("127.0.0.1");
    node_info.set_node_manager_port(object_manager_port);
    node_info.set_object_manager_port(object_manager_port);

    ray::Status status = gcs_client_->Nodes().RegisterSelf(node_info);
    return status;
  }

  friend class TestObjectManager;

  ClientID node_id_;
  ObjectManagerConfig config_;
  std::shared_ptr<gcs::GcsClient> gcs_client_;
  ObjectManager object_manager_;
};

class TestObjectManagerBase : public ::testing::Test {
 public:
  TestObjectManagerBase() {}

  std::string StartStore(const std::string &id) {
    std::string store_id = "/tmp/store";
    store_id = store_id + id;
    std::string store_pid = store_id + ".pid";
    std::string plasma_command = store_executable + " -m 1000000000 -s " + store_id +
                                 " 1> /dev/null 2> /dev/null &" + " echo $! > " +
                                 store_pid;

    RAY_LOG(DEBUG) << plasma_command;
    int ec = system(plasma_command.c_str());
    RAY_CHECK(ec == 0);
    sleep(1);
    return store_id;
  }

  void StopStore(std::string store_id) {
    std::string store_pid = store_id + ".pid";
    std::string kill_1 = "kill -9 `cat " + store_pid + "`";
    ASSERT_TRUE(!system(kill_1.c_str()));
  }

  void SetUp() {
    flushall_redis();

    // start store
    store_id_1 = StartStore(UniqueID::FromRandom().Hex());
    store_id_2 = StartStore(UniqueID::FromRandom().Hex());

    unsigned int pull_timeout_ms = 1;
    push_timeout_ms = 1000;

    // start first server
    gcs::GcsClientOptions client_options("127.0.0.1", 6379, /*password*/ "",
                                         /*is_test_client=*/true);
    gcs_client_1 = std::make_shared<gcs::RedisGcsClient>(client_options);
    RAY_CHECK_OK(gcs_client_1->Connect(main_service));
    ObjectManagerConfig om_config_1;
    om_config_1.store_socket_name = store_id_1;
    om_config_1.pull_timeout_ms = pull_timeout_ms;
    om_config_1.object_chunk_size = object_chunk_size;
    om_config_1.push_timeout_ms = push_timeout_ms;
    om_config_1.object_manager_port = 0;
    om_config_1.rpc_service_threads_number = 3;
    server1.reset(new MockServer(main_service, om_config_1, gcs_client_1));

    // start second server
    gcs_client_2 = std::make_shared<gcs::RedisGcsClient>(client_options);
    RAY_CHECK_OK(gcs_client_2->Connect(main_service));
    ObjectManagerConfig om_config_2;
    om_config_2.store_socket_name = store_id_2;
    om_config_2.pull_timeout_ms = pull_timeout_ms;
    om_config_2.object_chunk_size = object_chunk_size;
    om_config_2.push_timeout_ms = push_timeout_ms;
    om_config_2.object_manager_port = 0;
    om_config_2.rpc_service_threads_number = 3;
    server2.reset(new MockServer(main_service, om_config_2, gcs_client_2));

    // connect to stores.
    RAY_ARROW_CHECK_OK(client1.Connect(store_id_1));
    RAY_ARROW_CHECK_OK(client2.Connect(store_id_2));
  }

  void TearDown() {
    arrow::Status client1_status = client1.Disconnect();
    arrow::Status client2_status = client2.Disconnect();
    ASSERT_TRUE(client1_status.ok() && client2_status.ok());

    gcs_client_1->Disconnect();
    gcs_client_2->Disconnect();

    this->server1.reset();
    this->server2.reset();

    StopStore(store_id_1);
    StopStore(store_id_2);
  }

  ObjectID WriteDataToClient(plasma::PlasmaClient &client, int64_t data_size) {
    return WriteDataToClient(client, data_size, ObjectID::FromRandom());
  }

  ObjectID WriteDataToClient(plasma::PlasmaClient &client, int64_t data_size,
                             ObjectID object_id) {
    RAY_LOG(DEBUG) << "ObjectID Created: " << object_id;
    uint8_t metadata[] = {5};
    int64_t metadata_size = sizeof(metadata);
    std::shared_ptr<Buffer> data;
    RAY_ARROW_CHECK_OK(
        client.Create(object_id.ToPlasmaId(), data_size, metadata, metadata_size, &data));
    RAY_ARROW_CHECK_OK(client.Seal(object_id.ToPlasmaId()));
    return object_id;
  }

  void object_added_handler_1(ObjectID object_id) { v1.push_back(object_id); };

  void object_added_handler_2(ObjectID object_id) { v2.push_back(object_id); };

 protected:
  std::thread p;
  boost::asio::io_service main_service;
  std::shared_ptr<gcs::GcsClient> gcs_client_1;
  std::shared_ptr<gcs::GcsClient> gcs_client_2;
  std::unique_ptr<MockServer> server1;
  std::unique_ptr<MockServer> server2;

  plasma::PlasmaClient client1;
  plasma::PlasmaClient client2;
  std::vector<ObjectID> v1;
  std::vector<ObjectID> v2;

  std::string store_id_1;
  std::string store_id_2;

  unsigned int push_timeout_ms;

  uint64_t object_chunk_size = static_cast<uint64_t>(std::pow(10, 3));
};

class TestObjectManager : public TestObjectManagerBase {
 public:
  int current_wait_test = -1;
  int num_connected_clients = 0;
  ClientID node_id_1;
  ClientID node_id_2;

  ObjectID created_object_id1;
  ObjectID created_object_id2;

  std::unique_ptr<boost::asio::deadline_timer> timer;

  void WaitConnections() {
    node_id_1 = gcs_client_1->Nodes().GetSelfId();
    node_id_2 = gcs_client_2->Nodes().GetSelfId();
    RAY_CHECK_OK(gcs_client_1->Nodes().AsyncSubscribeToNodeChange(
        [this](const ClientID &node_id, const GcsNodeInfo &data) {
          if (node_id == node_id_1 || node_id == node_id_2) {
            num_connected_clients += 1;
          }
          if (num_connected_clients == 2) {
            StartTests();
          }
        },
        nullptr));
  }

  void StartTests() {
    TestConnections();
    TestNotifications();
  }

  void TestNotifications() {
    ray::Status status = ray::Status::OK();
    status = server1->object_manager_.SubscribeObjAdded(
        [this](const object_manager::protocol::ObjectInfoT &object_info) {
          object_added_handler_1(ObjectID::FromBinary(object_info.object_id));
          NotificationTestCompleteIfSatisfied();
        });
    RAY_CHECK_OK(status);
    status = server2->object_manager_.SubscribeObjAdded(
        [this](const object_manager::protocol::ObjectInfoT &object_info) {
          object_added_handler_2(ObjectID::FromBinary(object_info.object_id));
          NotificationTestCompleteIfSatisfied();
        });
    RAY_CHECK_OK(status);

    size_t data_size = 1000000;

    // dummy_id is not local. The push function will timeout.
    ObjectID dummy_id = ObjectID::FromRandom();
    server1->object_manager_.Push(dummy_id, gcs_client_2->Nodes().GetSelfId());

    created_object_id1 = ObjectID::FromRandom();
    WriteDataToClient(client1, data_size, created_object_id1);
    // Server1 holds Object1 so this Push call will success.
    server1->object_manager_.Push(created_object_id1, gcs_client_2->Nodes().GetSelfId());

    // This timer is used to guarantee that the Push function for dummy_id will timeout.
    timer.reset(new boost::asio::deadline_timer(main_service));
    auto period = boost::posix_time::milliseconds(push_timeout_ms + 10);
    timer->expires_from_now(period);
    created_object_id2 = ObjectID::FromRandom();
    timer->async_wait([this, data_size](const boost::system::error_code &error) {
      WriteDataToClient(client2, data_size, created_object_id2);
    });
  }

  void NotificationTestCompleteIfSatisfied() {
    size_t num_expected_objects1 = 1;
    size_t num_expected_objects2 = 2;
    if (v1.size() == num_expected_objects1 && v2.size() == num_expected_objects2) {
      SubscribeObjectThenWait();
    }
  }

  void SubscribeObjectThenWait() {
    int data_size = 100;
    // Test to ensure Wait works properly during an active subscription to the same
    // object.
    ObjectID object_1 = WriteDataToClient(client2, data_size);
    ObjectID object_2 = WriteDataToClient(client2, data_size);
    UniqueID sub_id = ray::UniqueID::FromRandom();

    RAY_CHECK_OK(server1->object_manager_.object_directory_->SubscribeObjectLocations(
        sub_id, object_1,
        [this, sub_id, object_1, object_2](
            const ray::ObjectID &object_id,
            const std::unordered_set<ray::ClientID> &clients) {
          if (!clients.empty()) {
            TestWaitWhileSubscribed(sub_id, object_1, object_2);
          }
        }));
  }

  void TestWaitWhileSubscribed(UniqueID sub_id, ObjectID object_1, ObjectID object_2) {
    int required_objects = 1;
    int timeout_ms = 1000;

    std::vector<ObjectID> object_ids = {object_1, object_2};
    boost::posix_time::ptime start_time = boost::posix_time::second_clock::local_time();

    UniqueID wait_id = UniqueID::FromRandom();

    RAY_CHECK_OK(server1->object_manager_.AddWaitRequest(
        wait_id, object_ids, timeout_ms, required_objects, false,
        [this, sub_id, object_1, object_ids, start_time](
            const std::vector<ray::ObjectID> &found,
            const std::vector<ray::ObjectID> &remaining) {
          int64_t elapsed = (boost::posix_time::second_clock::local_time() - start_time)
                                .total_milliseconds();
          RAY_LOG(DEBUG) << "elapsed " << elapsed;
          RAY_LOG(DEBUG) << "found " << found.size();
          RAY_LOG(DEBUG) << "remaining " << remaining.size();
          RAY_CHECK(found.size() == 1);
          // There's nothing more to test. A check will fail if unexpected behavior is
          // triggered.
          RAY_CHECK_OK(
              server1->object_manager_.object_directory_->UnsubscribeObjectLocations(
                  sub_id, object_1));
          NextWaitTest();
        }));

    // Skip lookups and rely on Subscribe only to test subscribe interaction.
    server1->object_manager_.SubscribeRemainingWaitObjects(wait_id);
  }

  void NextWaitTest() {
    int data_size = 600;
    current_wait_test += 1;
    switch (current_wait_test) {
    case 0: {
      // Ensure timeout_ms = 0 is handled correctly.
      // Out of 5 objects, we expect 3 ready objects and 2 remaining objects.
      TestWait(data_size, 5, 3, /*timeout_ms=*/0, false, false);
    } break;
    case 1: {
      // Ensure timeout_ms = 1000 is handled correctly.
      // Out of 5 objects, we expect 3 ready objects and 2 remaining objects.
      TestWait(data_size, 5, 3, wait_timeout_ms, false, false);
    } break;
    case 2: {
      // Generate objects locally to ensure local object code-path works properly.
      // Out of 5 objects, we expect 3 ready objects and 2 remaining objects.
      TestWait(data_size, 5, 3, wait_timeout_ms, false, /*test_local=*/true);
    } break;
    case 3: {
      // Wait on an object that's never registered with GCS to ensure timeout works
      // properly.
      TestWait(data_size, /*num_objects=*/5, /*required_objects=*/6, wait_timeout_ms,
               /*include_nonexistent=*/true, false);
    } break;
    case 4: {
      // Ensure infinite time code-path works properly.
      TestWait(data_size, 5, 5, /*timeout_ms=*/-1, false, false);
    } break;
    }
  }

  void TestWait(int data_size, int num_objects, uint64_t required_objects, int timeout_ms,
                bool include_nonexistent, bool test_local) {
    std::vector<ObjectID> object_ids;
    for (int i = -1; ++i < num_objects;) {
      ObjectID oid;
      if (test_local) {
        oid = WriteDataToClient(client1, data_size);
      } else {
        oid = WriteDataToClient(client2, data_size);
      }
      object_ids.push_back(oid);
    }
    if (include_nonexistent) {
      num_objects += 1;
      object_ids.push_back(ObjectID::FromRandom());
    }

    boost::posix_time::ptime start_time = boost::posix_time::second_clock::local_time();
    RAY_CHECK_OK(server1->object_manager_.Wait(
        object_ids, timeout_ms, required_objects, false,
        [this, object_ids, num_objects, timeout_ms, required_objects, start_time](
            const std::vector<ray::ObjectID> &found,
            const std::vector<ray::ObjectID> &remaining) {
          int64_t elapsed = (boost::posix_time::second_clock::local_time() - start_time)
                                .total_milliseconds();
          RAY_LOG(DEBUG) << "elapsed " << elapsed;
          RAY_LOG(DEBUG) << "found " << found.size();
          RAY_LOG(DEBUG) << "remaining " << remaining.size();

          // Ensure object order is preserved for all invocations.
          size_t j = 0;
          size_t k = 0;
          for (size_t i = 0; i < object_ids.size(); ++i) {
            ObjectID oid = object_ids[i];
            // Make sure the object is in either the found vector or the remaining vector.
            if (j < found.size() && found[j] == oid) {
              j += 1;
            }
            if (k < remaining.size() && remaining[k] == oid) {
              k += 1;
            }
          }
          if (!found.empty()) {
            ASSERT_EQ(j, found.size());
          }
          if (!remaining.empty()) {
            ASSERT_EQ(k, remaining.size());
          }

          switch (current_wait_test) {
          case 0: {
            // Ensure timeout_ms = 0 returns expected number of found and remaining
            // objects.
            ASSERT_TRUE(found.size() <= required_objects);
            ASSERT_TRUE(static_cast<int>(found.size() + remaining.size()) == num_objects);
            NextWaitTest();
          } break;
          case 1: {
            // Ensure lookup succeeds as expected when timeout_ms = 1000.
            ASSERT_TRUE(found.size() >= required_objects);
            ASSERT_TRUE(static_cast<int>(found.size() + remaining.size()) == num_objects);
            NextWaitTest();
          } break;
          case 2: {
            // Ensure lookup succeeds as expected when objects are local.
            ASSERT_TRUE(found.size() >= required_objects);
            ASSERT_TRUE(static_cast<int>(found.size() + remaining.size()) == num_objects);
            NextWaitTest();
          } break;
          case 3: {
            // Ensure lookup returns after timeout_ms elapses when one object doesn't
            // exist.
            ASSERT_TRUE(elapsed >= timeout_ms);
            ASSERT_TRUE(static_cast<int>(found.size() + remaining.size()) == num_objects);
            NextWaitTest();
          } break;
          case 4: {
            // Ensure timeout_ms = -1 works properly.
            ASSERT_TRUE(static_cast<int>(found.size()) == num_objects);
            ASSERT_TRUE(remaining.size() == 0);
            TestWaitComplete();
          } break;
          }
        }));
  }

  void TestWaitComplete() { main_service.stop(); }

  void TestConnections() {
    RAY_LOG(DEBUG) << "\n"
                   << "Server node ids:"
                   << "\n";
    auto data = gcs_client_1->Nodes().Get(node_id_1);
    RAY_LOG(DEBUG) << (ClientID::FromBinary(data->node_id()).IsNil());
    RAY_LOG(DEBUG) << "Server 1 NodeID=" << ClientID::FromBinary(data->node_id());
    RAY_LOG(DEBUG) << "Server 1 NodeIp=" << data->node_manager_address();
    RAY_LOG(DEBUG) << "Server 1 NodePort=" << data->node_manager_port();
    ASSERT_EQ(node_id_1, ClientID::FromBinary(data->node_id()));
    auto data2 = gcs_client_1->Nodes().Get(node_id_2);
    RAY_LOG(DEBUG) << "Server 2 NodeID=" << ClientID::FromBinary(data2->node_id());
    RAY_LOG(DEBUG) << "Server 2 NodeIp=" << data2->node_manager_address();
    RAY_LOG(DEBUG) << "Server 2 NodePort=" << data2->node_manager_port();
    ASSERT_EQ(node_id_2, ClientID::FromBinary(data2->node_id()));
  }
};

TEST_F(TestObjectManager, StartTestObjectManager) {
  // TODO: Break this test suite into unit tests.
  auto AsyncStartTests = main_service.wrap([this]() { WaitConnections(); });
  AsyncStartTests();
  main_service.run();
}

}  // namespace ray

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  store_executable = std::string(argv[1]);
  wait_timeout_ms = std::stoi(std::string(argv[2]));
  return RUN_ALL_TESTS();
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef _MACH_MACHINE_RPC_H_
#define _MACH_MACHINE_RPC_H_

#if   defined (__arm__) || defined (__arm64__)
#include "mach/arm/rpc.h"
#else
#error architecture not supported
#endif

#endif	/* _MACH_MACHINE_RPC_H_ */


text:
.outer .container .table-form {margin-top: 0;}
.outer .table tr > th:first-child, .outer .table tr > td:first-child {padding-left: 5px;}

.modal-dialog {margin-top: 10%;}

.table-form thead > tr > th {background: none; border: none}


text:
permalink: "test-neato-robotics-connected/"
date: "2017-01-26 15:00:00"
layout: "product-page"
title: "Test Neato Robotics Connected"
categories:
  - product
  - robot
image: "neato-connected-mini.png"
model: "Neato Robotics Connected"
type-vacuum: "Aspirador robot"
technology: "Wi-fi y LaserSmart"
power: "40 V"
power-op: "5"
capacity: "0,7 L"
capacity-op: "5"
sound: "69 dB"
sound-op: "4"
filter: "Ultra para mascotas y alergias"
filter-op: "5"
weight: "3,7 kg"
weight-op: "4"
dimensions: "33,5 x 32,1 x 10 cm"
radius: "400 m²"
radius-op: "5"
garanty: "2 años"
brush: "cepillos: combo para mascotas, lateral, Spiral Blade"
brush-op: "5"
charge: "2h-3h"
charge-op: "5"
Battery: "120 min ECO y 90 min TURBO"
clasification: "4,6"
comments: "Inteligente, autonomo y practico"
price-before: "759,00 €"
price-now: "759,00"
discount: "0%"
stars: "5"
description: "Guia de compra del Neato Robotics Botvac Connected, funcionamiento, aspirado, características y las mejores ofertas."
link: "https://www.amazon.es/Neato-Robotics-Botvac-Connected-metalizado/dp/B014J7N1KA/ref=as_li_ss_tl?s=kitchen&ie=UTF8&qid=1488718582&sr=1-1&keywords=Neato+Robotics+Connected&linkCode=ll1&tag=lasaspirad-21&linkId=2ed34fd2e10fc99c43fd0ed68e86f4a9"
link-ebay: "https://rover.ebay.com/rover/1/1185-53479-19255-0/1?icep_id=114&ipn=icep&toolid=20004&campid=5338046469&mpre=http%3A%2F%2Fwww.ebay.es%2Fitm%2FNeato-Botvac-Connected-Robot-Aspirapolvere-Connessione-Wifi-Neato-Robotics-%2F291643856507%3Fhash%3Ditem43e754167b%3Ag%3AQVcAAOSwxN5WY0Nx"
---

  {% include components/button-buy-amazon.html %}
  {% include components/button-buy-ebay.html %}

  ✔ Puntos fuertes  | ❌ Debilidades
  --|--
  Paquete de accesorios completos. |  Un poco ruidoso.
  Actualizaciones de software disponibles.| No pasa por debajo de algunos muebles (10 cm) y puede quedar atascado.
  Excelente succión en todos los suelos.|
  Conectividad que funciona para lanzar el robot a distancia. |
  Muy buena cobertura de las superficies.|
  Buena gestión Obstáculos.|

#### Presentación

  Provisto de los principales atributos que han sabido convencernos en las anteriores generaciones: un sistema de navegación que utiliza la telemetría láser para cartografiar las habitaciones, una forma en D que le permite limpiar las esquinas y a lo largo de las paredes y una aspiración eficaz.

  El robot Neato BotVac Connected ha heredado también una pantalla con un menú ergonómico.
  Además de la posibilidad de conectarse al Wifi de casa para empezar a limpiar desde cualquier lugar, este nuevo BotVac cuenta con mejoras notables, entre ellas una batería de ión-litio y un nuevo filtro que parece más robusto y que necesitaría menos limpieza. El aumento de la autonomía permite limpiar hasta 400 m² y el robot Neato BotVac Connected presenta ahora dos modos: "eco" y "Turbo".

  Si estás pensando en comprar el Neato Robotics Botvac Connected aquí te contamos todo lo que necesitas saber antes de hacer tu compra.

    {% include components/button-buy-amazon.html %}
    {% include components/button-buy-ebay.html %}

#### Comodidad de uso

  En apariencia, aunque el robot Neato BotVac Connected siempre toma la forma de una D y su telémetro sigue siendo importante, es mucho más sobrio que sus predecesores y encontrará su lugar más fácilmente en el salon.

  En la armadura encontramos los botones tradicionales con dibujos de una casa y una rejilla. El primero consiste en lanzar una limpieza a fondo de la casa, mientras que el segundo corresponde a una limpieza localizada. Ahora es posible seleccionar entre dos tamaños de zonas para limpiar de manera local, lo que sólo es posible a partir de la aplicación. De forma predeterminada, la limpieza localizada en el aparato limpia un área de 2 x 2 m.

  En el dispositivo también hay una pantalla con retroiluminación, que se apaga cuando no se utiliza la aspiradora.
  La pantalla muestra los menús en los que navegamos con unas pocas teclas, como en las generaciones anteriores.

  Los botones son agradables, legibles y reactivos. Rápidamente nos hacemos con su comando, que se resume en a ir hacia arriba o hacia abajo en el menú, volver atrás y confirmar.

  A pesar de este robot está conectado, todas las características que había en el antiguo modelo de serie D siguen siendo accesibles sin smartphone: la programación, el lanzamiento de la limpieza total o localizada y varios ajustes (reloj, alarmas cuando hemos hecho una selección, brillo de la pantalla ...).

  Hay una nueva función la presencia de los modos Eco o Turbo (en la zona de limpieza del menú). El modo Eco alarga la vida de la batería, proporcionando una limpieza un poco más lenta pero promete más silencio. En el modo turbo, la aspiración sería más fuerte pero más ruidosa.

La conectividad

  Para conectar el dispositivo la aplicación es didáctica y sencilla. Primero hay que conectar el robot en Wi-Fi al smartphone (iOS o Android) y a continuación la aplicación puede conectarse a la red Wi-Fi de casa.

    {% include components/button-buy-amazon.html %}
    {% include components/button-buy-ebay.html %}

#### Aspirado

  La succión del Neato BotVac Connected es excepcional.

  En alfombra fina y suelo duro, los únicos residuos no aspirados se encuentran bajo nuestra mesa de café por la que no pasa. Sin ella aspira todos los materiales tanto en el modo Eco como en modo Turbo con el cepillo de láminas.

  En alfombra gruesa de pelo duro, conseguimos también excelentes resultados y mejor incluso en el modo Turbo (hasta el 96% con el cepillo combinado) en el modo Eco (91%). Sobre esta superficie, el cepillo combinado proporciona mejores resultados.

    {% include components/button-buy-amazon.html %}
    {% include components/button-buy-ebay.html %}

#### Ruido

  No hay diferencia con la aspiradora robot D85 ya que esta era más silenciosa que la primera Neato robot. Con el modo Eco obtenemos 65 dB mientras que con el modo turbo llega hasta 68 dB. Esto no es un gran inconveniente en un aspirador robot, ya que puede ser programado y además ponerse  en marcha de forma remota desde la aplicación.

#### Consumo

  El  BotVac Connected cuenta con una batería de ion-litio. Su consumo es de 40 W durante la carga y por desgracia no es un cero cuando la batería está cargada.Medimos alrededor de 3 W.

    {% include components/button-buy-amazon.html %}
    {% include components/button-buy-ebay.html %}

#### Modos y funciones complementarias

  Las funciones y los accesorios son completos. El BotVac Connected viene con su base de carga, tres filtros de nueva generación, una pequeña herramienta de limpieza y una ingeniosa etiqueta magnética para cortar al formato deseado. Viene sin mando a distancia, lo que no se echa de menos gracias a su pantalla fácil de leer y también al smartphone se convierte en un "súper mando a distancia".

  El BotVac Connected cuenta también con un puerto USB que permite actualizaciones de software regulares. Neato ha incluido un cable adaptador USB / micro-USB para facilitar esta manipulación, que es nueva.

  Apreciamos que el dispositivo tiene una batería de ion-litio, más duraderas que las baterías de NiMH.

  Este robot es programable día a día en diferentes momentos, ya sea desde la pantalla o de la aplicación.
  En términos de características y accesorios, difícil pedir más.

  La aplicación: funcionalidades e impresiones

  La aplicación, llamada simplemente Neato está disponible en iOS y Android. Es relativamente sencilla de usar, aunque pudiera ser un poco más intuitiva. Como todo al principio hay que probar.
  Como el robot está conectado a través de Wi-Fi puedes iniciar la limpieza, aunque estes en la oficina o en al otro lado del mundo.

  La aplicación también permite el control del robot, como si se tratara de un mando a distancia.
  Controlar la aspiradora con el smartphone sin duda es divertido, pero no es muy útil.

  Por último, la aplicación te permite elegir el modo de limpieza (Eco o Turbo), hacer una pausa en una limpieza en marcha o una limpieza de áreas de diferente tamaño. Esta opción sólo está disponible en la aplicación - una sola dimensión está disponible directamente en el robot. Si la zona está muy sucia, otra opción puede ser activarla en la aplicación: dos pases en lugar de uno.

  En este caso, la BotVac limpia el área una vez en zigzag y la segunda vez haciendo zigzags perpendiculares a la primera pasada.
  Nos gustaría que la aplicación ofrezca más información en un futuro con notificaciones adicionales. A día de hoy, Neato envía una notificación cuando la limpieza está acabada, pero podría ampliarlas y notificar los incidente durante la limpieza o la necesidad de vaciar el depósito. Incluso por qué no añadir aconsejos de mantenimiento como propone iRobot Roomba 980.

    {% include components/button-buy-amazon.html %}
    {% include components/button-buy-ebay.html %}

#### Mantenimiento

  El depósito tiene la forma de un pequeño cassette, cerrado por el filtro que hay que quitar para vaciarlo (Atención porque permanece abierto de un lado). Al igual que la generación anterior, el robot Neato BotVac D85, tiene una capacidad de 0,7 litros.

  La forma del filtro ha cambiado en dos niveles. En primer lugar, está ahora equipada con una pinza pequeña que facilita en gran medida la apertura del depósito.

  Por otra parte, el mantenimiento de las láminas del filtro puede ser un poco tedioso, ya que el polvo tiende a quedarse ahi. Olvidamos pronto este inconveniente ya que el filtro se cubre con una pequeña rejilla que retiene el polvo más grueso y la pelusa. Solo hay que quitar el cepillo principal para eliminar los cabellos o el pelo de mascotas que todavía se enredan un poco, lo cual es inevitable.

  Si bien los modelos anteriores de la marca eran ya de fácil mantenimiento, Neato ha dado un paso más en esta dirección.

    {% include components/button-buy-amazon.html %}
    {% include components/button-buy-ebay.html %}

#### Sistema de Navegación

  Neato ha proporcionado a su modelo conectado del mismo sistema de navegación que a sus predecesores. Esta es la característica principal de los robots Neato, usar un telémetro láser que permite a la aspiradora hacer un mapa del piso para anticipar así los obstáculos. Se desplaza sistemáticamente en zigzag y durante su trayecto rodea los obstáculos que encuentra.

  Con este sistema de navegación, no sólo la cobertura de la superficie es perfecta, sino que además el robot se las arregla para limpiar todas las partes de la casa y encontrar su base de carga fácilmente. Vuelve a la base cuando ha terminado la limpieza o si la superficie es demasiado grande a mitad de ciclo para recargarse.

  Otra ventaja del telémetro: funciona tanto en la oscuridad como con la luz del día (en una habitación con las persianas bajadas o debajo de los muebles, por ejemplo).

  Por último, observamos que la precisión cumple, y cada obstáculo que encuentra lo rodea con gran cuidado, por ejemplo, el contorno de los pies de mesas o sillas.

  Si bien el robot aspirador Neato promete una mayor precisión, es difícil de cuantificar porque las versiones anteriores ya estaban ofreciendo una precisión asombrosa en este tema. El sistema de navegación que utiliza Neato es uno de los más inteligentes y más eficaz.

#### Gestión de obstáculos

  Estamos siempre cerca de la perfección y el robot aspirador Neato BotVac Connected como era de esperar gestiona los obstáculos con brio. Aunque como siempre es mejor evitar dejar cables eléctricos en el medio de la habitación.

  Como comente anteriormente, hace su trabajo en las patas de los muebles, donde limpia meticulosamente el contorno. Cuando monta en una "superficie"" un poco alta para él - los pies del árbol para el gato, por ejemplo, o la esquina de la alfombra gruesa- es capaz de levantarse sobre sus ruedas para salir.

  Los pocos casos que son problemáticos son los muebles apenas un poco más alto que él,  su telémetro no los detecta y se puede quedar atrapado debajo. Hay que saber que con su telémetro, el Neato es un poco más grueso de lo normal (10 cm).

#### Conclusión 4,6 pts / 5

  El BotVac Connected disfruta de las ventajas de sus predecesores: la exactitud  de las superficies, muy buena gestión de obstáculos y la aspiración eficiente en todo tipo de suelos.

  Neato ha logrado incluso facilitar el mantenimiento del robot con nuevos filtros. En cuanto a la conectividad, es facil de poner en marcha y se utiliza principalmente para iniciar un barrido remoto. Este es un buen primer paso en el mundo del hogar conectado, aunque esperamos ver evolucionar la aplicación.

  ¿Quieres consultar otro modelo? No te preocupes, vuelve a la lista de las mejores aspiradoras del mercado. He seleccionado para ti los productos más interesantes.

     Consulta nuestra lista de mejores aspiradoras


text:
package hashset

import (
	"fmt"
	"testing"
)

func TestHashSet(t *testing.T) {

	set := New()

	// insertions
	set.Add()
	set.Add(1)
	set.Add(2)
	set.Add(2, 3)
	set.Add()

	if actualValue := set.Empty(); actualValue != false {
		t.Errorf("Got %v expected %v", actualValue, false)
	}

	if actualValue := set.Size(); actualValue != 3 {
		t.Errorf("Got %v expected %v", actualValue, 3)
	}

	// Asking if a set is superset of nothing, thus it's true
	if actualValue := set.Contains(); actualValue != true {
		t.Errorf("Got %v expected %v", actualValue, true)
	}

	if actualValue := set.Contains(1); actualValue != true {
		t.Errorf("Got %v expected %v", actualValue, true)
	}

	if actualValue := set.Contains(1, 2, 3); actualValue != true {
		t.Errorf("Got %v expected %v", actualValue, true)
	}

	if actualValue := set.Contains(1, 2, 3, 4); actualValue != false {
		t.Errorf("Got %v expected %v", actualValue, false)
	}

	set.Remove()
	set.Remove(1)

	if actualValue, expectedValues := fmt.Sprintf("%d%d", set.Values()...), [2]string{"23", "32"}; actualValue != expectedValues[0] && actualValue != expectedValues[1] {
		t.Errorf("Got %v expected %v", actualValue, expectedValues)
	}

	if actualValue := set.Contains(1); actualValue != false {
		t.Errorf("Got %v expected %v", actualValue, false)
	}

	set.Remove(1, 2, 3)

	if actualValue := set.Contains(3); actualValue != false {
		t.Errorf("Got %v expected %v", actualValue, false)
	}

	if actualValue := set.Empty(); actualValue != true {
		t.Errorf("Got %v expected %v", actualValue, true)
	}

}

func BenchmarkHashSet(b *testing.B) {
	for i := 0; i < b.N; i++ {
		set := New()
		for n := 0; n < 1000; n++ {
			set.Add(i)
		}
		for n := 0; n < 1000; n++ {
			set.Remove(n)
		}
	}
}


text:
using JetBrains.Annotations;

namespace XRoadLib.Tests.Contract;

public enum Gender
{
    [UsedImplicitly] Unknown,
    Female,
    [UsedImplicitly] Male
}


text:
package ru.stqa.prt.addressbook.tests;

import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.stqa.prt.addressbook.model.GroupData;
import ru.stqa.prt.addressbook.model.Groups;

import java.util.Comparator;
import java.util.List;
import java.util.Set;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.testng.Assert.assertEquals;

/**
 * Created by natkin on 21.07.2016.
 */
public class GroupModificationTests extends TestBase{

  @BeforeMethod
  public void ansurePreonditios(){

    if (app.db().groups().size() == 0){
      app.goTo().groupPage();
      app.group().create(new GroupData().withName("test1"));
    }
  }

  @Test//(enabled = false)
  public void testGroupModification(){
    Groups before = app.db().groups();
    GroupData modifiedGroup = before.iterator().next(); // Возвращает первый попавшийся элемент множетсва
    GroupData group = new GroupData()
                          .withId(modifiedGroup.getId())
                          .withName("test1")
                          .withHeader("test2")
                          .withFooter("test3");
    app.goTo().groupPage();
    app.group().modify(group);
    assertThat(app.group().count(), equalTo(before.size()));
    Groups after = app.db().groups();
    assertThat(after, equalTo(before.without(modifiedGroup).withAdded(group)));
    verifyGroupListInUI();
  }

}


text:
/* global __dirname module require */

const cloneDeep = require('lodash.clonedeep');
const {copySync, ensureDirSync} = require('fs-extra');
const glob = require('glob');
const {dirname, join, relative} = require('path');

// @babel/cli v7's --copy-files option does not work well together with
// config-specified ignore paths, and that's a problem for embark-collective
// actions since the @babel/cli invocation must be the same across all packages
// in the collective; so any package in the collective that excludes src/ files
// from transpilation via its package-local .babelrc.js should copy those files
// into dist/, but only if they are expected to be in dist/; .babelrc.js should
// also copy any non .js,.ts files into /dist

// in this case we want the un-transpiled webpack config and babel-loader
// overrides script from the basic-pipeline to be copied into the respective
// subdir in dist/; we also want to copy .ejs and .json files

function copyFiles (ignored) {
  const others = glob.sync(
    join(__dirname, 'src/**/*.*'),
    {ignore: [
      join(__dirname, 'src/**/*.js'),
      join(__dirname, 'src/**/*.ts'),
      join(__dirname, 'src/**/*.disabled')
    ]}
  ).map(path => relative(__dirname, path));

  ignored = ignored.concat(others);
  ignored
    .map(path => path.replace('src', 'dist'))
    .forEach((dest, index) => {
      ensureDirSync(dirname(join(__dirname, dest)));
      const source = ignored[index];
      copySync(join(__dirname, source), join(__dirname, dest));
  });
}

module.exports = (api) => {
  const env = api.env();

  const base = {};

  const node = cloneDeep(base);

  if (env === 'node') {
    copyFiles(node.ignore || []);
    return node;
  }

  const test = cloneDeep(node);

  if (env === 'test') {
    copyFiles(test.ignore || []);
    return test;
  }

  return base;
};


text:
#ifndef _IXGBEVF_H_
#define _IXGBEVF_H_

#include <linux/types.h>
#include <linux/bitops.h>
#include <linux/timer.h>
#include <linux/io.h>
#include <linux/netdevice.h>
#include <linux/if_vlan.h>
#include <linux/u64_stats_sync.h>

#include "vf.h"

/* wrapper around a pointer to a socket buffer,
 * so a DMA handle can be stored along with the buffer */
struct ixgbevf_tx_buffer {
	struct sk_buff *skb;
	dma_addr_t dma;
	unsigned long time_stamp;
	u16 length;
	u16 next_to_watch;
	u16 mapped_as_page;
};

struct ixgbevf_rx_buffer {
	struct sk_buff *skb;
	dma_addr_t dma;
	struct page *page;
	dma_addr_t page_dma;
	unsigned int page_offset;
};

struct ixgbevf_ring {
	struct ixgbevf_adapter *adapter;  /* backlink */
	void *desc;			/* descriptor ring memory */
	dma_addr_t dma;			/* phys. address of descriptor ring */
	unsigned int size;		/* length in bytes */
	unsigned int count;		/* amount of descriptors */
	unsigned int next_to_use;
	unsigned int next_to_clean;

	int queue_index; /* needed for multiqueue queue management */
	union {
		struct ixgbevf_tx_buffer *tx_buffer_info;
		struct ixgbevf_rx_buffer *rx_buffer_info;
	};

	u64			total_bytes;
	u64			total_packets;
	struct u64_stats_sync	syncp;

	u16 head;
	u16 tail;

	u16 reg_idx; /* holds the special value that gets the hardware register
		      * offset associated with this ring, which is different
		      * for DCB and RSS modes */

#if defined(CONFIG_DCA) || defined(CONFIG_DCA_MODULE)
	/* cpu for tx queue */
	int cpu;
#endif

	u64 v_idx; /* maps directly to the index for this ring in the hardware
		    * vector array, can also be used for finding the bit in EICR
		    * and friends that represents the vector for this ring */

	u16 work_limit;                /* max work per interrupt */
	u16 rx_buf_len;
};

enum ixgbevf_ring_f_enum {
	RING_F_NONE = 0,
	RING_F_ARRAY_SIZE      /* must be last in enum set */
};

struct ixgbevf_ring_feature {
	int indices;
	int mask;
};

/* How many Rx Buffers do we bundle into one write to the hardware ? */
#define IXGBEVF_RX_BUFFER_WRITE	16	/* Must be power of 2 */

#define MAX_RX_QUEUES 1
#define MAX_TX_QUEUES 1

#define IXGBEVF_DEFAULT_TXD   1024
#define IXGBEVF_DEFAULT_RXD   512
#define IXGBEVF_MAX_TXD       4096
#define IXGBEVF_MIN_TXD       64
#define IXGBEVF_MAX_RXD       4096
#define IXGBEVF_MIN_RXD       64

/* Supported Rx Buffer Sizes */
#define IXGBEVF_RXBUFFER_64    64     /* Used for packet split */
#define IXGBEVF_RXBUFFER_128   128    /* Used for packet split */
#define IXGBEVF_RXBUFFER_256   256    /* Used for packet split */
#define IXGBEVF_RXBUFFER_2048  2048
#define IXGBEVF_MAX_RXBUFFER   16384  /* largest size for single descriptor */

#define IXGBEVF_RX_HDR_SIZE IXGBEVF_RXBUFFER_256

#define MAXIMUM_ETHERNET_VLAN_SIZE (VLAN_ETH_FRAME_LEN + ETH_FCS_LEN)

#define IXGBE_TX_FLAGS_CSUM		(u32)(1)
#define IXGBE_TX_FLAGS_VLAN		(u32)(1 << 1)
#define IXGBE_TX_FLAGS_TSO		(u32)(1 << 2)
#define IXGBE_TX_FLAGS_IPV4		(u32)(1 << 3)
#define IXGBE_TX_FLAGS_FCOE		(u32)(1 << 4)
#define IXGBE_TX_FLAGS_FSO		(u32)(1 << 5)
#define IXGBE_TX_FLAGS_VLAN_MASK	0xffff0000
#define IXGBE_TX_FLAGS_VLAN_PRIO_MASK	0x0000e000
#define IXGBE_TX_FLAGS_VLAN_SHIFT	16

/* MAX_MSIX_Q_VECTORS of these are allocated,
 * but we only use one per queue-specific vector.
 */
struct ixgbevf_q_vector {
	struct ixgbevf_adapter *adapter;
	struct napi_struct napi;
	DECLARE_BITMAP(rxr_idx, MAX_RX_QUEUES); /* Rx ring indices */
	DECLARE_BITMAP(txr_idx, MAX_TX_QUEUES); /* Tx ring indices */
	u8 rxr_count;     /* Rx ring count assigned to this vector */
	u8 txr_count;     /* Tx ring count assigned to this vector */
	u8 tx_itr;
	u8 rx_itr;
	u32 eitr;
	int v_idx;	  /* vector index in list */
};

/* Helper macros to switch between ints/sec and what the register uses.
 * And yes, it's the same math going both ways.  The lowest value
 * supported by all of the ixgbe hardware is 8.
 */
#define EITR_INTS_PER_SEC_TO_REG(_eitr) \
	((_eitr) ? (1000000000 / ((_eitr) * 256)) : 8)
#define EITR_REG_TO_INTS_PER_SEC EITR_INTS_PER_SEC_TO_REG

#define IXGBE_DESC_UNUSED(R) \
	((((R)->next_to_clean > (R)->next_to_use) ? 0 : (R)->count) + \
	(R)->next_to_clean - (R)->next_to_use - 1)

#define IXGBE_RX_DESC_ADV(R, i)	    \
	(&(((union ixgbe_adv_rx_desc *)((R).desc))[i]))
#define IXGBE_TX_DESC_ADV(R, i)	    \
	(&(((union ixgbe_adv_tx_desc *)((R).desc))[i]))
#define IXGBE_TX_CTXTDESC_ADV(R, i)	    \
	(&(((struct ixgbe_adv_tx_context_desc *)((R).desc))[i]))

#define IXGBE_MAX_JUMBO_FRAME_SIZE        16128

#define OTHER_VECTOR 1
#define NON_Q_VECTORS (OTHER_VECTOR)

#define MAX_MSIX_Q_VECTORS 2
#define MAX_MSIX_COUNT 2

#define MIN_MSIX_Q_VECTORS 2
#define MIN_MSIX_COUNT (MIN_MSIX_Q_VECTORS + NON_Q_VECTORS)

/* board specific private data structure */
struct ixgbevf_adapter {
	struct timer_list watchdog_timer;
	unsigned long active_vlans[BITS_TO_LONGS(VLAN_N_VID)];
	u16 bd_number;
	struct work_struct reset_task;
	struct ixgbevf_q_vector *q_vector[MAX_MSIX_Q_VECTORS];
	char name[MAX_MSIX_COUNT][IFNAMSIZ + 9];

	/* Interrupt Throttle Rate */
	u32 itr_setting;
	u16 eitr_low;
	u16 eitr_high;

	/* TX */
	struct ixgbevf_ring *tx_ring;	/* One per active queue */
	int num_tx_queues;
	u64 restart_queue;
	u64 hw_csum_tx_good;
	u64 lsc_int;
	u64 hw_tso_ctxt;
	u64 hw_tso6_ctxt;
	u32 tx_timeout_count;

	/* RX */
	struct ixgbevf_ring *rx_ring;	/* One per active queue */
	int num_rx_queues;
	int num_rx_pools;               /* == num_rx_queues in 82598 */
	int num_rx_queues_per_pool;	/* 1 if 82598, can be many if 82599 */
	u64 hw_csum_rx_error;
	u64 hw_rx_no_dma_resources;
	u64 hw_csum_rx_good;
	u64 non_eop_descs;
	int num_msix_vectors;
	int max_msix_q_vectors;         /* true count of q_vectors for device */
	struct ixgbevf_ring_feature ring_feature[RING_F_ARRAY_SIZE];
	struct msix_entry *msix_entries;

	u64 rx_hdr_split;
	u32 alloc_rx_page_failed;
	u32 alloc_rx_buff_failed;

	/* Some features need tri-state capability,
	 * thus the additional *_CAPABLE flags.
	 */
	u32 flags;
#define IXGBE_FLAG_RX_CSUM_ENABLED              (u32)(1)
#define IXGBE_FLAG_RX_1BUF_CAPABLE              (u32)(1 << 1)
#define IXGBE_FLAG_RX_PS_CAPABLE                (u32)(1 << 2)
#define IXGBE_FLAG_RX_PS_ENABLED                (u32)(1 << 3)
#define IXGBE_FLAG_IN_NETPOLL                   (u32)(1 << 4)
#define IXGBE_FLAG_IMIR_ENABLED                 (u32)(1 << 5)
#define IXGBE_FLAG_MQ_CAPABLE                   (u32)(1 << 6)
#define IXGBE_FLAG_NEED_LINK_UPDATE             (u32)(1 << 7)
#define IXGBE_FLAG_IN_WATCHDOG_TASK             (u32)(1 << 8)
	/* OS defined structs */
	struct net_device *netdev;
	struct pci_dev *pdev;

	/* structs defined in ixgbe_vf.h */
	struct ixgbe_hw hw;
	u16 msg_enable;
	struct ixgbevf_hw_stats stats;
	u64 zero_base;
	/* Interrupt Throttle Rate */
	u32 eitr_param;

	unsigned long state;
	u32 *config_space;
	u64 tx_busy;
	unsigned int tx_ring_count;
	unsigned int rx_ring_count;

	u32 link_speed;
	bool link_up;
	unsigned long link_check_timeout;

	struct work_struct watchdog_task;
	bool netdev_registered;
	bool dev_closed;
};

enum ixbgevf_state_t {
	__IXGBEVF_TESTING,
	__IXGBEVF_RESETTING,
	__IXGBEVF_DOWN
};

enum ixgbevf_boards {
	board_82599_vf,
	board_X540_vf,
};

extern const struct ixgbevf_info ixgbevf_82599_vf_info;
extern const struct ixgbevf_info ixgbevf_X540_vf_info;
extern const struct ixgbe_mbx_operations ixgbevf_mbx_ops;

/* needed by ethtool.c */
extern const char ixgbevf_driver_name[];
extern const char ixgbevf_driver_version[];

extern void ixgbevf_up(struct ixgbevf_adapter *adapter);
extern void ixgbevf_down(struct ixgbevf_adapter *adapter);
extern void ixgbevf_reinit_locked(struct ixgbevf_adapter *adapter);
extern void ixgbevf_reset(struct ixgbevf_adapter *adapter);
extern void ixgbevf_set_ethtool_ops(struct net_device *netdev);
extern int ixgbevf_setup_rx_resources(struct ixgbevf_adapter *,
				      struct ixgbevf_ring *);
extern int ixgbevf_setup_tx_resources(struct ixgbevf_adapter *,
				      struct ixgbevf_ring *);
extern void ixgbevf_free_rx_resources(struct ixgbevf_adapter *,
				      struct ixgbevf_ring *);
extern void ixgbevf_free_tx_resources(struct ixgbevf_adapter *,
				      struct ixgbevf_ring *);
extern void ixgbevf_update_stats(struct ixgbevf_adapter *adapter);

#ifdef ETHTOOL_OPS_COMPAT
extern int ethtool_ioctl(struct ifreq *ifr);

#endif
extern void ixgbe_napi_add_all(struct ixgbevf_adapter *adapter);
extern void ixgbe_napi_del_all(struct ixgbevf_adapter *adapter);

#ifdef DEBUG
extern char *ixgbevf_get_hw_dev_name(struct ixgbe_hw *hw);
#define hw_dbg(hw, format, arg...) \
	printk(KERN_DEBUG "%s: " format, ixgbevf_get_hw_dev_name(hw), ##arg)
#else
#define hw_dbg(hw, format, arg...) do {} while (0)
#endif

#endif /* _IXGBEVF_H_ */


text:
package uk.ac.ebi.eva.pipeline.parameters.validation.step;

import org.junit.Before;
import org.junit.Test;
import org.springframework.batch.core.JobParameter;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersInvalidException;

import uk.ac.ebi.eva.pipeline.parameters.JobParametersNames;

import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

/**
 * Tests that the arguments necessary to run a {@link uk.ac.ebi.eva.pipeline.jobs.steps.AnnotationLoaderStep} are
 * correctly validated
 */
public class IndexesGeneratorStepParametersValidatorTest {
    private IndexesGeneratorStepParametersValidator validator;

    private Map<String, JobParameter> requiredParameters;

    private Map<String, JobParameter> optionalParameters;

    @Before
    public void setUp() throws Exception {
        validator = new IndexesGeneratorStepParametersValidator();

        requiredParameters = new TreeMap<>();
        requiredParameters.put(JobParametersNames.DB_NAME, new JobParameter("dbName"));
        requiredParameters.put(JobParametersNames.DB_COLLECTIONS_FEATURES_NAME,
                               new JobParameter("dbCollectionsFeaturesName"));

        optionalParameters = new TreeMap<>();
        optionalParameters.put(JobParametersNames.CONFIG_RESTARTABILITY_ALLOW, new JobParameter("true"));
    }

    @Test
    public void allJobParametersAreValid() throws JobParametersInvalidException, IOException {
        validator.validate(new JobParameters(requiredParameters));
    }

    @Test
    public void allJobParametersIncludingOptionalAreValid() throws JobParametersInvalidException, IOException {
        Map<String, JobParameter> parameters = new TreeMap<>();
        parameters.putAll(requiredParameters);
        parameters.putAll(optionalParameters);
        validator.validate(new JobParameters(parameters));
    }

    @Test(expected = JobParametersInvalidException.class)
    public void dbCollectionsFeaturesNameIsRequired() throws JobParametersInvalidException, IOException {
        requiredParameters.remove(JobParametersNames.DB_COLLECTIONS_FEATURES_NAME);
        validator.validate(new JobParameters(requiredParameters));
    }

    @Test(expected = JobParametersInvalidException.class)
    public void dbNameIsRequired() throws JobParametersInvalidException, IOException {
        requiredParameters.remove(JobParametersNames.DB_NAME);
        validator.validate(new JobParameters(requiredParameters));
    }

}


text:
// Copyright 2014 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 "chrome/browser/sync/sync_error_notifier_ash.h"

#include "ash/test/ash_test_base.h"
#include "base/memory/scoped_ptr.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/notifications/notification.h"
#include "chrome/browser/notifications/notification_ui_manager.h"
#include "chrome/browser/sync/profile_sync_service_mock.h"
#include "chrome/browser/sync/sync_error_controller.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/webui/signin/login_ui_service.h"
#include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/message_center/notification.h"

#if defined(OS_WIN)
#include "chrome/browser/ui/ash/ash_util.h"
#include "ui/aura/test/test_screen.h"
#include "ui/gfx/screen.h"
#include "ui/gfx/screen_type_delegate.h"
#endif

using ::testing::NiceMock;
using ::testing::Return;
using ::testing::ReturnRef;
using ::testing::_;

namespace ash {
namespace test {

namespace {

static const char kTestAccountId[] = "testuser@test.com";

// Notification ID corresponding to kProfileSyncNotificationId + kTestAccountId.
static const std::string kNotificationId =
    "chrome://settings/sync/testuser@test.com";

#if defined(OS_WIN)
class ScreenTypeDelegateDesktop : public gfx::ScreenTypeDelegate {
 public:
  ScreenTypeDelegateDesktop() {}
  virtual ~ScreenTypeDelegateDesktop() {}
  virtual gfx::ScreenType GetScreenTypeForNativeView(
      gfx::NativeView view) OVERRIDE {
    return chrome::IsNativeViewInAsh(view) ?
        gfx::SCREEN_TYPE_ALTERNATE :
        gfx::SCREEN_TYPE_NATIVE;
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(ScreenTypeDelegateDesktop);
};
#endif

class FakeLoginUIService: public LoginUIService {
 public:
  FakeLoginUIService() : LoginUIService(NULL) {}
  virtual ~FakeLoginUIService() {}
};

class FakeLoginUI : public LoginUIService::LoginUI {
 public:
  FakeLoginUI() : focus_ui_call_count_(0) {}

  virtual ~FakeLoginUI() {}

  int focus_ui_call_count() const { return focus_ui_call_count_; }

 private:
  // LoginUIService::LoginUI:
  virtual void FocusUI() OVERRIDE {
    ++focus_ui_call_count_;
  }
  virtual void CloseUI() OVERRIDE {}

  int focus_ui_call_count_;
};

KeyedService* BuildMockLoginUIService(
    content::BrowserContext* profile) {
  return new FakeLoginUIService();
}

class SyncErrorNotifierTest : public AshTestBase  {
 public:
  SyncErrorNotifierTest() {}
  virtual ~SyncErrorNotifierTest() {}

  virtual void SetUp() OVERRIDE {
    profile_manager_.reset(
        new TestingProfileManager(TestingBrowserProcess::GetGlobal()));
    ASSERT_TRUE(profile_manager_->SetUp());

    profile_ = profile_manager_->CreateTestingProfile(kTestAccountId);

    TestingBrowserProcess::GetGlobal();
    AshTestBase::SetUp();

    // Set up a desktop screen for Windows to hold native widgets, used when
    // adding desktop widgets (i.e., message center notifications).
#if defined(OS_WIN)
    test_screen_.reset(aura::TestScreen::Create(gfx::Size()));
    gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, test_screen_.get());
    gfx::Screen::SetScreenTypeDelegate(new ScreenTypeDelegateDesktop);
#endif

    service_.reset(new NiceMock<ProfileSyncServiceMock>(profile_));

    FakeLoginUIService* login_ui_service = static_cast<FakeLoginUIService*>(
        LoginUIServiceFactory::GetInstance()->SetTestingFactoryAndUse(
            profile_, BuildMockLoginUIService));
    login_ui_service->SetLoginUI(&login_ui_);

    error_controller_.reset(new SyncErrorController(service_.get()));
    error_notifier_.reset(new SyncErrorNotifier(error_controller_.get(),
                                                profile_));

    notification_ui_manager_ = g_browser_process->notification_ui_manager();
  }

  virtual void TearDown() OVERRIDE {
    error_notifier_->Shutdown();
    service_.reset();
#if defined(OS_WIN)
    test_screen_.reset();
#endif
    profile_manager_.reset();

    AshTestBase::TearDown();
  }

 protected:
  // Utility function to test that SyncErrorNotifier behaves correctly for the
  // given error condition.
  void VerifySyncErrorNotifierResult(GoogleServiceAuthError::State error_state,
                                     bool is_signed_in,
                                     bool is_error) {
    EXPECT_CALL(*service_, HasSyncSetupCompleted())
                .WillRepeatedly(Return(is_signed_in));

    GoogleServiceAuthError auth_error(error_state);
    EXPECT_CALL(*service_, GetAuthError()).WillRepeatedly(
        ReturnRef(auth_error));

    error_controller_->OnStateChanged();
    EXPECT_EQ(is_error, error_controller_->HasError());

    // If there is an error we should see a notification.
    const Notification* notification = notification_ui_manager_->
        FindById(kNotificationId);
    if (is_error) {
      ASSERT_TRUE(notification);
      ASSERT_FALSE(notification->title().empty());
      ASSERT_FALSE(notification->title().empty());
      ASSERT_EQ((size_t)1, notification->buttons().size());
    } else {
      ASSERT_FALSE(notification);
    }
  }

#if defined(OS_WIN)
  scoped_ptr<gfx::Screen> test_screen_;
#endif
  scoped_ptr<TestingProfileManager> profile_manager_;
  scoped_ptr<SyncErrorController> error_controller_;
  scoped_ptr<SyncErrorNotifier> error_notifier_;
  scoped_ptr<NiceMock<ProfileSyncServiceMock> > service_;
  TestingProfile* profile_;
  FakeLoginUI login_ui_;
  NotificationUIManager* notification_ui_manager_;

  DISALLOW_COPY_AND_ASSIGN(SyncErrorNotifierTest);
};

} // namespace

// Test that SyncErrorNotifier shows an notification if a passphrase is
// required.
// Disabled on Windows: http://crbug.com/373238
#if defined(OS_WIN)
#define MAYBE_PassphraseNotification DISABLED_PassphraseNotification
#else
#define MAYBE_PassphraseNotification PassphraseNotification
#endif
TEST_F(SyncErrorNotifierTest, MAYBE_PassphraseNotification) {
  ASSERT_FALSE(notification_ui_manager_->FindById(kNotificationId));

  browser_sync::SyncBackendHost::Status status;
  EXPECT_CALL(*service_, QueryDetailedSyncStatus(_))
              .WillRepeatedly(Return(false));

  EXPECT_CALL(*service_, IsPassphraseRequired())
              .WillRepeatedly(Return(true));
  EXPECT_CALL(*service_, IsPassphraseRequiredForDecryption())
              .WillRepeatedly(Return(true));
  {
    SCOPED_TRACE("Expected a notification for passphrase error");
    VerifySyncErrorNotifierResult(GoogleServiceAuthError::NONE,
                                  true /* signed in */,
                                  true /* error */);
  }

  // Check that no notification is shown if there is no error.
  EXPECT_CALL(*service_, IsPassphraseRequired())
              .WillRepeatedly(Return(false));
  EXPECT_CALL(*service_, IsPassphraseRequiredForDecryption())
              .WillRepeatedly(Return(false));
  {
    SCOPED_TRACE("Not expecting notification since no error exists");
    VerifySyncErrorNotifierResult(GoogleServiceAuthError::NONE,
                                  true /* signed in */,
                                  false /* no error */);
  }

  // Check that no notification is shown if sync setup is not completed.
  EXPECT_CALL(*service_, IsPassphraseRequired())
              .WillRepeatedly(Return(true));
  EXPECT_CALL(*service_, IsPassphraseRequiredForDecryption())
              .WillRepeatedly(Return(true));
  {
    SCOPED_TRACE("Not expecting notification since sync setup is incomplete");
    VerifySyncErrorNotifierResult(
        GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS,
        false /* not signed in */,
        false /* no error */);
  }
}

}  // namespace test
}  // namespace ash


text:
@interface PUMUPI : NSObject

@property (strong, nonatomic) NSString *vpa;

@end


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function parse(html) {
    var frag = document.createDocumentFragment();
    var body = document.createElement('body');
    frag.appendChild(body);
    body.innerHTML = html;
    return body.firstElementChild;
}
exports.parse = parse;
function css(e, styles) {
    for (var prop in styles) {
        e.style[prop] = styles[prop];
    }
    return e;
}
exports.css = css;
function fit(e, target) {
    return css(e, {
        width: target.clientWidth + 'px',
        height: target.clientHeight + 'px',
    });
}
exports.fit = fit;
function hide(e) {
    return css(e, { display: 'none' });
}
exports.hide = hide;
function show(e) {
    return css(e, { display: 'block' });
}
exports.show = show;
function toggle(e, visible) {
    return visible ? show(e) : hide(e);
}
exports.toggle = toggle;
function singleTransition(e, prop, millis, ease) {
    if (ease === void 0) { ease = 'linear'; }
    e.style.transition = prop + " " + millis + "ms " + ease;
    console.log(e.style.transition);
    setTimeout(function () { return e.style.transition = ''; }, millis);
}
exports.singleTransition = singleTransition;
//# sourceMappingURL=Dom.js.map


text:
<?php
namespace LolAPIExamples\Champion;

use LolAPI\Service\Champion\Ver1_2\Champion\DTO\ChampionDTO;
use LolAPI\Service\Champion\Ver1_2\Champion\DTOBuilder;
use LolAPI\Service\Champion\Ver1_2\Champion\Request;
use LolAPI\Service\Champion\Ver1_2\Champion\Service;
use LolAPIExamples\ExampleTest;

class ChampionTest extends ExampleTest
{
    public function testExample() {
        $service = new Service($this->getLolAPIHandler());
        $request = new Request($this->getApiKey(), $this->getRegionalEndpoint(), 1);

        $query = $service->createQuery($request);
        $response = $query->execute();

        $dtoBuilder = new DTOBuilder();
        $dto = $dtoBuilder->buildDTO($response);

        if($this->isOutputEnabled()) {
            $this->processResult($dto);
        }
    }

    private function processResult(ChampionDTO $championDTO) {
        println(sprintf("Champion #%d", $championDTO->getId()));
        println(sprintf("Active: %s", ($championDTO->isActive() ? 'true' : 'false')), 1);
        println(sprintf("BotEnabled: %s", ($championDTO->isBotEnabled() ? 'true' : 'false')), 1);
        println(sprintf("BotMmEnabled: %s", ($championDTO->isBotMmEnabled() ? 'true' : 'false')), 1);
        println(sprintf("FreeToPlay: %s", ($championDTO->isFreeToPlay() ? 'true' : 'false')), 1);
        println(sprintf("RankedPlayEnabled: %s", ($championDTO->isRankedPlayEnabled() ? 'true' : 'false')), 1);
    }
}


text:
package system

import (
	"syscall"
)

func Lstat(path string) (*Stat_t, error) {
	s := &syscall.Stat_t{}
	err := syscall.Lstat(path, s)
	if err != nil {
		return nil, err
	}
	return fromStatT(s)
}


text:
import unittest

import trytond.tests.test_tryton

from test_shipment import TestShipment

def suite():
    """
    Define suite
    """
    test_suite = trytond.tests.test_tryton.suite()
    test_suite.addTests([
        unittest.TestLoader().loadTestsFromTestCase(TestShipment),
    ])
    return test_suite

if __name__ == '__main__':
    unittest.TextTestRunner(verbosity=2).run(suite())


text:
package com.dmdirc.addons.ui_swing.events;

import com.dmdirc.addons.ui_swing.components.frames.TextFrame;

import java.util.Optional;

/**
 * Event triggered when a swing window is added.
 */
public class SwingWindowAddedEvent extends SwingEvent {

    private final Optional<TextFrame> parentWindow;
    private final TextFrame childWindow;

    public SwingWindowAddedEvent(final Optional<TextFrame> parentWindow,
            final TextFrame childWindow) {
        this.parentWindow = parentWindow;
        this.childWindow = childWindow;
    }

    public Optional<TextFrame> getParentWindow() {
        return parentWindow;
    }

    public TextFrame getChildWindow() {
        return childWindow;
    }
}


text:
package com.mytwitter.Network;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import org.apache.http.HttpStatus;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * Class working with network connectivity
 */
public class NetworkHelper {

    public static final String WEBADDRESS_GOOGLE_COM_URL = "http://www.google.com";
    // always verify the host - don't check for certificate
    final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    private static final int NETWORK_CONNECTION_POOL_TIMEOUT = 1000;
    private static final int NETWORK_CONNECTION_CONNECT_TIMEOUT = 10000;
    private static final int NETWORK_CONNECTION_READ_TIMEOUT = 10000;
    private static final int NETWORK_SOCKET_CONNECT_TIMEOUT = 10000;
    private static final String WEBADDRESS_GOOGLE_DNS_ADDRESS1 = "8.8.8.8";
    private static final String WEBADDRESS_ANDROID_COM_URL = "http://www.android.com/";
    private static final String WEBADDRESS_ANDROID_COM_IP = "74.125.24.102";
    private SSLSocketFactory defaultSSLSocketFactory = null;
    private HostnameVerifier defaultHostnameVerifier = null;

    private NetworkHelper() {
    }

    public static boolean connectedToWiFiNetwork(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return connectedToWiFiNetwork(connectivityManager);
    }

    public static boolean connectedToWiFiNetwork(ConnectivityManager connectivityManager) {
        NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

        if (!isConnected)
            return false;

        return (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI);
    }

    public static boolean connectedToMobileNetwork(ConnectivityManager connectivityManager) {
        NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

        if (!isConnected)
            return false;

        return (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE);
    }

    public static boolean connectedToWiFiOrMobileNetwork(Context context) {
        final ConnectivityManager cm = getConnectivityManager(context);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

        if (!isConnected)
            return false;

        return (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) ||
                (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE);
    }

    /**
     * Checks whether some network is connected and fully usable.
     */
    public static boolean connectedToNetwork(ConnectivityManager connectivityManager) {
        NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
        return (activeNetwork != null && activeNetwork.isConnectedOrConnecting());
    }

    public static boolean connectedToNetwork(Context context) {
        ConnectivityManager connectivityManager = getConnectivityManager(context);
        NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
        return (activeNetwork != null && activeNetwork.isConnectedOrConnecting());
    }

    /**
     * Verifies that the handset is connected to the Internet.
     *
     * @return
     */
    public static boolean connectedToInternet(Context context) throws IOException {

        if (!connectedToNetwork(getConnectivityManager(context)))
            return false;

        URL googleUrl = new URL(WEBADDRESS_GOOGLE_COM_URL);
        HttpURLConnection connection = (HttpURLConnection) googleUrl.openConnection();
        connection.setConnectTimeout(NETWORK_CONNECTION_CONNECT_TIMEOUT);
        connection.connect();

        if (connection.getResponseCode() == HttpStatus.SC_OK)
            return true;

        return false;

        /**
         *  Alternative way (NOT TESTED):
         *
         boolean result = false;

         URL url;
         HttpURLConnection connection = null;

         try {
         url = new URL(WEBADDRESS_ANDROID_COM_URL);

         connection = (HttpURLConnection) url.openConnection();
         connection.setConnectTimeout(NETWORK_CONNECTION_CONNECT_TIMEOUT);
         connection.setReadTimeout(NETWORK_CONNECTION_READ_TIMEOUT);

         InetAddress address = InetAddress.getByName(WEBADDRESS_ANDROID_COM_IP);

         result = address.isReachable(NETWORK_CONNECTION_CONNECT_TIMEOUT);

         // Redirect check is valid only after the response headers have been received
         // InputStream in = new BufferedInputStream(connection.getInputStream());

         //            if (url.getHost().equals(connection.getURL().getHost()))
         //                result = true;

         } catch (Exception e) {
         e.printStackTrace();
         } finally {
         connection.disconnect();
         }

         return result;
         */
    }

    /**
     * Checks that a route to the remote host exists.
     */
    public static boolean isHostRoutable(Context context, String hostname) {

        boolean result = false;
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivity.getActiveNetworkInfo();

        if (connectivity != null && networkInfo != null && networkInfo.isConnected()) {
            int networkType = networkInfo.getType();
            int ipAddress = lookupHost(hostname);
            result = connectivity.requestRouteToHost(networkType, ipAddress);
        }

        return result;
    }

    /**
     * Converts an IP address to an integer.
     */
    public static int lookupHost(String hostname) {
        InetAddress address;

        try {
            address = InetAddress.getByName(hostname);
        } catch (UnknownHostException e) {
            return -1;
        }

        byte[] addrBytes = address.getAddress();

        return ((addrBytes[3] & 0xff) << 24) | ((addrBytes[2] & 0xff) << 16) | ((addrBytes[1] & 0xff) << 8) | (addrBytes[0] & 0xff);
    }

    private static ConnectivityManager getConnectivityManager(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm;
    }

    /**
     * Create a trust manager that does not validate SSL certificate chains.
     */
    public void trustAllHosts() {

        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[]{};
            }

            public void checkClientTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }
        }};

        // Install the all-trusting trust manager
        try {
            // Backup the current SSL socket factory
            defaultSSLSocketFactory = HttpsURLConnection
                    .getDefaultSSLSocketFactory();
            // Install our all trusting manager
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection
                    .setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


text:
//
//  XZMessageView.m
//  Pods
//
//  Created by Xi Zhang on 7/14/16.
//
//

#import "XZMessageView.h"

#define kDefaultAutoHideDelay 3.0
#define kDefaultAnimationDuration 0.4
#define kDefaultRedColor [UIColor colorWithRed:180.0/255.0 green:62.0/255.0 blue:64.0/255.0 alpha:1.0]

@interface XZMessageView()
{
    UILabel *_errorMsgLabel;
}

@end

@implementation XZMessageView

/* init methods */
-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupComponets];
    }
    return self;
}

-(id)initWithSize:(CGSize)size
{
    CGRect screenBounds = [UIScreen mainScreen].bounds;
    CGRect frame = CGRectMake(CGRectGetMidX(screenBounds) - size.width/2.0, -size.height, size.width, size.height);
    self = [self initWithFrame:frame];
    if (self) {
        [self setupComponets];
    }
    return self;
}

-(void)awakeFromNib
{
    [super awakeFromNib];
    [self setupComponets];
}

/* UI setup methods  */
-(void)setupComponets
{
    _animationDuration = kDefaultAnimationDuration;
    _autoHideDelay = kDefaultAutoHideDelay;

    [self setBackgroundColor:kDefaultRedColor];
    [self setupErrorLabel];
    [self setupGestures];
}

-(void)setupGestures
{
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hide:)];
    UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(hide:)];
    swipeGesture.direction = UISwipeGestureRecognizerDirectionUp;
    [self addGestureRecognizer:tapGesture];
    [self addGestureRecognizer:swipeGesture];
}

-(void)setupErrorLabel
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectInset(self.bounds, 5.0, 5.0)];
    [label setTextAlignment:NSTextAlignmentCenter];
    [label setBackgroundColor:[UIColor clearColor]];
    [label setTextColor:[UIColor whiteColor]];
    [label setNumberOfLines:1];
    [label setLineBreakMode:NSLineBreakByTruncatingTail];
    [label setFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:17.0]];
    [self addSubview:label];
    [label setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin];
    _errorMsgLabel = label;
}

/* public UI control methods */
-(void)displayErrorMsgViewWithText:(NSString *)str
{
    if(![str length])
        return;
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideErrorMsgView) object:nil];

    UIWindow *frontWindow = [UIApplication sharedApplication].delegate.window;
    [frontWindow.rootViewController.view addSubview:self];
    [frontWindow.rootViewController.view bringSubviewToFront:self];

    [self resetErrorMsg:str];
    [self show:nil callBack:^{
        [self performSelector:@selector(hideErrorMsgView) withObject:nil afterDelay:_autoHideDelay];
    }];
}

-(void)hideErrorMsgView
{
    [self hide:nil callBack:^{

    }];
}

/* private UI control methods */
-(void)hide:(UIGestureRecognizer *)gesture
{
    [self.superview bringSubviewToFront:self];
    CGRect rect = self.frame;
    rect.origin.y = -rect.size.height;
    [UIView animateWithDuration:_animationDuration animations:^{
        [self setFrame:rect];
    } completion:^(BOOL finished) {
    }];
}

-(void)hide:(UIGestureRecognizer *)gesture callBack:(void(^)(void))callback
{
    [self.superview bringSubviewToFront:self];
    CGRect rect = self.frame;
    rect.origin.y = -rect.size.height;
    [UIView animateWithDuration:_animationDuration animations:^{
        [self setFrame:rect];
    } completion:^(BOOL finished) {
        if (callback) {
            callback();
        }
    }];
}

-(void)show:(UIGestureRecognizer*)gesture callBack:(void(^)(void))callback
{
    [self.superview bringSubviewToFront:self];
    CGRect rect = self.frame;
    rect.origin.y = [[UIApplication sharedApplication] statusBarFrame].size.height;
    [UIView animateWithDuration:_animationDuration animations:^{
        [self setFrame:rect];
    } completion:^(BOOL finished) {
        if (callback) {
            callback();
        }
    }];
}

-(void)resetErrorMsg:(NSString *)errorMsg
{
    [_errorMsgLabel setText:errorMsg];
}

/*setters*/
-(void)setBgColor:(UIColor *)bgColor
{
    _bgColor = bgColor;
    [self setBackgroundColor:_bgColor];
}

-(void)setFont:(UIFont *)font
{
    _font = font;
    [_errorMsgLabel setFont:_font];
}

-(void)setFontColor:(UIColor *)fontColor
{
    _fontColor = fontColor;
    [_errorMsgLabel setTextColor:_fontColor];
}

@end


text:
Pattern: Use of HTTP for AWS Elasticsearch

Issue: -

## Description

Plain HTTP is unencrypted and human-readable. This means that if a malicious actor was to eavesdrop on your connection, they would be able to see all of your data flowing back and forth.

You should use HTTPS, which is HTTP over an encrypted (TLS) connection, meaning eavesdroppers cannot read your traffic.

**Resolution**: Enforce the use of HTTPS for Elasticsearch.

## Examples

Example of **incorrect** code:

```terraform
resource "aws_elasticsearch_domain" "bad_example" {
  domain_name = "domain-foo"

  domain_endpoint_options {
    enforce_https = false
  }
}
```

Example of **correct** code:

```terraform
resource "aws_elasticsearch_domain" "good_example" {
  domain_name = "domain-foo"

  domain_endpoint_options {
    enforce_https = true
  }
}
```


text:
<?php

namespace Admingenerator\PropelDemoBundle\Controller;

use Admingenerated\AdmingeneratorPropelDemoBundle\BaseController\NewController as BaseNewController;

class NewController extends BaseNewController
{
}


text:
//
//  ZXSendCommentViewController.m
//  Weibo_1
//
//  Created by zhengxiang on 15/12/21.
//  Copyright © 2015年 Zheng Xiang. All rights reserved.
//

#import "ZXSendCommentViewController.h"
#import "ZXCommentTableViewController.h"
#import "AFNetworking.h"
#import "AppDelegate.h"

@interface ZXSendCommentViewController ()

@property (nonatomic, strong) UITextView *textEditor;

@end

@implementation ZXSendCommentViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UIBarButtonItem *bbi = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(toReturn)];

    self.navigationItem.leftBarButtonItem = bbi;

    UIBarButtonItem *bbi1 = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(sendComment)];

    self.navigationItem.rightBarButtonItem = bbi1;

    //输入框显示区域
    _textEditor = [[UITextView alloc] initWithFrame:CGRectMake(0, 10, self.view.frame.size.width, 200)];

    //设置它的代理
//    _textEditor.delegate = self;
    _textEditor.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    _textEditor.keyboardType = UIKeyboardTypeDefault;
    _textEditor.font = [UIFont systemFontOfSize:20];

    //默认软键盘是在触摸区域后才会打开
    //这里表示进入当前ViewController直接打开软键盘
    [_textEditor becomeFirstResponder];

    //把输入框加在视图中
    [self.view addSubview:_textEditor];

    //下方的图片按钮 点击后呼出菜单 打开摄像机 查找本地相册
//    UIImage *image = [UIImage imageNamed:@"camera"];

//    NSLog(@"image: %@", image);

//    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//
//    button.frame = CGRectMake(0, 300, image.size.width, image.size.height);
//
//    [button setImage:image forState:UIControlStateNormal];
//
//    [button addTarget:self action:@selector(openMenu) forControlEvents:UIControlEventTouchUpInside];

    //把它也加在视图当中
//    [self.view addSubview:button];
}

- (void)toReturn {
//    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)sendComment {
    NSString *urlString = [NSString stringWithFormat:@"http://127.0.0.1:8000/report/sendComment/%@/", [AppDelegate APP].currentWeiboId ];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"user_id": [AppDelegate APP].user.userID, @"comment_text":_textEditor.text};

    [manager POST:urlString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSLog(@"JSON: %@", responseObject);
        if ([responseObject isKindOfClass:[NSDictionary class]]) {

            NSLog(@"NSDictionary!");
            NSDictionary *dict = [[NSDictionary alloc] initWithDictionary:responseObject];
            NSLog(@"%@", dict);
            //发送成功
            if ([dict[@"result"] compare:@"y"] == 0) {
                _textEditor.text = nil;
//                NSLog(@"%@", self.navigationController.viewControllers);
//                ZXCommentTableViewController *vc = [self.navigationController.viewControllers objectAtIndex:0];
//                [vc loadComment];
//                [vc.tableView reloadData];

                [AppDelegate APP].commentChange = YES;
                NSNotification *notification = [NSNotification notificationWithName:@"RefreshComment" object:nil];
                [[NSNotificationCenter defaultCenter] postNotification: notification];

            }
            else {
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"发送失败!" message:nil preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
                [alertController addAction:alertAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }

        } else if ([responseObject isKindOfClass:[NSArray class]]) {

            NSLog(@"NSArray");
            NSArray *array = [[NSArray alloc] initWithArray:responseObject];

            //            _isChange = YES;

            NSLog(@"reload ok!");

        } else {
            NSLog(@"unknown class of jsonObject");
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }
     ];
    [self.navigationController popViewControllerAnimated:YES];

}

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

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
#include <stdio.h>
#define MAXLINE 1000 /* maximum input line length */

int readline(char line[], int max);
int strindex(char source[], char searchfor[]);

char pattern[] ="thing"; //"ould"; /* pattern to search for */

/* find all lines matching pattern */
int main() {
	char line[MAXLINE];
	int found = 0;

    while (readline(line, MAXLINE) > 0){
        int idx = strindex(line, pattern);
		if (strindex(line, pattern) >= 0) {
			printf("%s, %d", line,idx);
			found++;
		}
    }
	return found;
}


text:
namespace net {

// The maximum number of sessions to open to a single domain.
static const size_t kMaxSessionsPerDomain = 1;

FlipSessionPool::FlipSessionPool() {}
FlipSessionPool::~FlipSessionPool() {
  CloseAllSessions();
}

scoped_refptr<FlipSession> FlipSessionPool::Get(
    const HostResolver::RequestInfo& info, HttpNetworkSession* session) {
  const std::string& domain = info.hostname();
  scoped_refptr<FlipSession> flip_session;
  FlipSessionList* list = GetSessionList(domain);
  if (list) {
    if (list->size() >= kMaxSessionsPerDomain) {
      flip_session = list->front();
      list->pop_front();
    }
  } else {
    list = AddSessionList(domain);
  }

  DCHECK(list);
  if (!flip_session)
    flip_session = new FlipSession(domain, session);

  DCHECK(flip_session);
  list->push_back(flip_session);
  DCHECK(list->size() <= kMaxSessionsPerDomain);
  return flip_session;
}

scoped_refptr<FlipSession> FlipSessionPool::GetFlipSessionFromSocket(
    const HostResolver::RequestInfo& info,
    HttpNetworkSession* session,
    ClientSocketHandle* connection) {
  const std::string& domain = info.hostname();
  FlipSessionList* list = GetSessionList(domain);
  if (!list)
    list = AddSessionList(domain);
  DCHECK(list->empty());
  scoped_refptr<FlipSession> flip_session(new FlipSession(domain, session));
  flip_session->InitializeWithSocket(connection);
  list->push_back(flip_session);
  return flip_session;
}

bool FlipSessionPool::HasSession(const HostResolver::RequestInfo& info) const {
  const std::string& domain = info.hostname();
  if (GetSessionList(domain))
    return true;
  return false;
}

void FlipSessionPool::Remove(const scoped_refptr<FlipSession>& session) {
  std::string domain = session->domain();
  FlipSessionList* list = GetSessionList(domain);
  CHECK(list);
  list->remove(session);
  if (list->empty())
    RemoveSessionList(domain);
}

FlipSessionPool::FlipSessionList*
    FlipSessionPool::AddSessionList(const std::string& domain) {
  DCHECK(sessions_.find(domain) == sessions_.end());
  return sessions_[domain] = new FlipSessionList();
}

FlipSessionPool::FlipSessionList*
    FlipSessionPool::GetSessionList(const std::string& domain) {
  FlipSessionsMap::iterator it = sessions_.find(domain);
  if (it == sessions_.end())
    return NULL;
  return it->second;
}

const FlipSessionPool::FlipSessionList*
    FlipSessionPool::GetSessionList(const std::string& domain) const {
  FlipSessionsMap::const_iterator it = sessions_.find(domain);
  if (it == sessions_.end())
    return NULL;
  return it->second;
}

void FlipSessionPool::RemoveSessionList(const std::string& domain) {
  FlipSessionList* list = GetSessionList(domain);
  if (list) {
    delete list;
    sessions_.erase(domain);
  } else {
    DCHECK(false) << "removing orphaned session list";
  }
}

void FlipSessionPool::CloseAllSessions() {
  while (sessions_.size()) {
    FlipSessionList* list = sessions_.begin()->second;
    DCHECK(list);
    sessions_.erase(sessions_.begin()->first);
    while (list->size()) {
      scoped_refptr<FlipSession> session = list->front();
      list->pop_front();
      session->CloseAllStreams(net::ERR_ABORTED);
    }
    delete list;
  }
}

}  // namespace net