<commit_before>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * 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.
 */
#include "zorbatypes/xqpstring.h"
#include "zorbatypes/URI.h"
#include "zorbaerrors/error_manager.h"

struct URITestEntry
{
  zorba::xqpString base;
  zorba::xqpString uri;
  zorba::xqpString text;
  zorba::xqpString scheme;
  int              port;
  zorba::xqpString fragment;
  zorba::xqpString host;
  zorba::xqpString regbased_authority;
  zorba::xqpString path;
  zorba::xqpString userinfo;
  zorba::xqpString query;
};

int uri(int argc, char* argv[])
{
  zorba::xqpString foo("/b");
  if (foo.endsWith("/.."))
    std::cout << foo << " ends with " << "/.." << std::endl;
  if (foo.endsWith("/\\.\\."))
    std::cout << foo << " ends with " << "/\\.\\." << std::endl;

  URITestEntry tests[] =
  {
    {
      "",
      "http://www.zorba-xquery.com/",
      "http://www.zorba-xquery.com/",
      "http",
      0,
      "",
      "www.zorba-xquery.com",
      "",
      "/",
      "",
      ""
    },
    {
      "",
      "http://www.zorba-xquery.com/?abc=true",
      "http://www.zorba-xquery.com/?abc=true",
      "http",
      0,
      "",
      "www.zorba-xquery.com",
      "",
      "/",
      "",
      "abc=true"
    },
    {
      "",
      "http://www.zorba-xquery.com:8080/?abc=true",
      "http://www.zorba-xquery.com:8080/?abc=true",
      "http",
      8080,
      "",
      "www.zorba-xquery.com",
      "",
      "/",
      "",
      "abc=true"
    },
    {
      "",
      "http://user@www.zorba-xquery.com:8080/?abc=true",
      "http://user@www.zorba-xquery.com:8080/?abc=true",
      "http",
      8080,
      "",
      "www.zorba-xquery.com",
      "",
      "/",
      "user",
      "abc=true"
    },
    {
      "",
      "http://user@www.zorba-xquery.com:8080/path1/path2?abc=true",
      "http://user@www.zorba-xquery.com:8080/path1/path2?abc=true",
      "http",
      8080,
      "",
      "www.zorba-xquery.com",
      "",
      "/path1/path2",
      "user",
      "abc=true"
    },
    {
      "",
      "http://user@www.zorba-xquery.com:8080/path1/path2?abc=true&bcd=false#fragment",
      "http://user@www.zorba-xquery.com:8080/path1/path2?abc=true&bcd=false#fragment",
      "http",
      8080,
      "fragment",
      "www.zorba-xquery.com",
      "",
      "/path1/path2",
      "user",
      "abc=true&bcd=false"
    },
    {
      "",
      "ftp://ftp.is.co.za/rfc/rfc1808.txt",
      "ftp://ftp.is.co.za/rfc/rfc1808.txt",
      "ftp",
      0,
      "",
      "ftp.is.co.za",
      "",
      "/rfc/rfc1808.txt",
      "",
      ""
    },
    {
      "",
      "http://thomas@[2001:6f8:9000:876:cccc:bbbb::]:123/test",
      "http://thomas@[2001:6f8:9000:876:cccc:bbbb::]:123/test",
      "http",
      123,
      "",
      "[2001:6f8:9000:876:cccc:bbbb::]",
      "",
      "/test",
      "thomas",
      ""
    },
    // uri resolver tests
    {
      "http://a/b/c/d;p?q",
      "g",
      "http://a/b/c/g",
      "http",
      0,
      "",
      "a",
      "",
      "/b/c/g",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "./g",
      "http://a/b/c/g",
      "http",
      0,
      "",
      "a",
      "",
      "/b/c/g",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "g/",
      "http://a/b/c/g/",
      "http",
      0,
      "",
      "a",
      "",
      "/b/c/g/",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "/g",
      "http://a/g",
      "http",
      0,
      "",
      "a",
      "",
      "/g",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "?y",
      "http://a/b/c/?y",
      "http",
      0,
      "",
      "a",
      "",
      "/b/c/",
      "",
      "y"
    },
    {
      "http://a/b/c/d;p?q",
      "g?y",
      "http://a/b/c/g?y",
      "http",
      0,
      "",
      "a",
      "",
      "/b/c/g",
      "",
      "y"
    } //,
  //{
  //  "http://a/b/c/d;p?q",
  //  "#s",
  //  "http://a/b/c/d;p?q#s",
  //  "http",
  //  0,
  //  "s",
  //  "a",
  //  "",
  //  "/b/c/g",
  //  "",
  //  ""
  //}
    ,
    {
      "http://a/b/c/d;p?q",
      "g#s",
      "http://a/b/c/g#s",
      "http",
      0,
      "s",
      "a",
      "",
      "/b/c/g",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "g?y#s",
      "http://a/b/c/g?y#s",
      "http",
      0,
      "s",
      "a",
      "",
      "/b/c/g",
      "",
      "y"
    },
    {
      "http://a/b/c/d;p?q",
      ";x",
      "http://a/b/c/;x",
      "http",
      0,
      "",
      "a",
      "",
      "/b/c/;x",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "g;x",
      "http://a/b/c/g;x",
      "http",
      0,
      "",
      "a",
      "",
      "/b/c/g;x",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "g;x?y#s",
      "http://a/b/c/g;x?y#s",
      "http",
      0,
      "s",
      "a",
      "",
      "/b/c/g;x",
      "",
      "y"
    },
    {
      "http://a/b/c/d;p?q",
      ".",
      "http://a/b/c/",
      "http",
      0,
      "",
      "a",
      "",
      "/b/c/",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "./",
      "http://a/b/c/",
      "http",
      0,
      "",
      "a",
      "",
      "/b/c/",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "..",
      "http://a/b/",
      "http",
      0,
      "",
      "a",
      "",
      "/b/",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "../",
      "http://a/b/",
      "http",
      0,
      "",
      "a",
      "",
      "/b/",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "../g",
      "http://a/b/g",
      "http",
      0,
      "",
      "a",
      "",
      "/b/g",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "../..",
      "http://a/",
      "http",
      0,
      "",
      "a",
      "",
      "/",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "../../",
      "http://a/",
      "http",
      0,
      "",
      "a",
      "",
      "/",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "../../g",
      "http://a/g",
      "http",
      0,
      "",
      "a",
      "",
      "/g",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "g;x=1/./y",
      "http://a/b/c/g;x=1/y",
      "http",
      0,
      "",
      "a",
      "",
      "/b/c/g;x=1/y",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "g;x=1/../y",
      "http://a/b/c/y",
      "http",
      0,
      "",
      "a",
      "",
      "/b/c/y",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "g#s/../x",
      "http://a/b/c/g#s/../x",
      "http",
      0,
      "s/../x",
      "a",
      "",
      "/b/c/g",
      "",
      ""
    },
    {
      "",
      "file://d:/a/b/c",
      "file://d:/a/b/c",
      "file",
      0,
      "",
      "",
      "d:",
      "/a/b/c",
      "",
      ""
    },
    {
      "file://",
      "/a/b/c",
      "file:///a/b/c",
      "file",
      0,
      "",
      "",
      "",
      "/a/b/c",
      "",
      ""
    },
    {
      "",
      "http://www.msb.de",
      "http://www.msb.de",
      "http",
      0,
      "",
      "www.msb.de",
      "",
      "",
      "",
      ""
    },
    {
      "http://www.msb.de/",
      "lib/helpers",
      "http://www.msb.de/lib/helpers",
      "http",
      0,
      "",
      "www.msb.de",
      "",
      "/lib/helpers",
      "",
      ""
    }

  }; // URITestEntry tests[]

  const unsigned int test_count = sizeof(tests) / sizeof(tests[0]);
  try {
    for (unsigned int i = 0; i < test_count; ++i) {
      std::cout << "executing test number " << i << " with uri " << tests[i].uri << std::endl;

      zorba::URI uri;
      if (tests[i].base.empty()) {
        uri = zorba::URI(tests[i].uri);
      } else  {
        zorba::URI base(tests[i].base);
        uri = zorba::URI(base, tests[i].uri);
      }
      if (uri.toString() != tests[i].text)  {
        std::cerr << "uri text " << uri.toString() << " is not equal to " << tests[i].text << std::endl;
        return 2;
      }
      if (uri.get_scheme() != tests[i].scheme)
        return 3;
      if (uri.get_port() != tests[i].port) {
        std::cerr << "port " << uri.get_port() << " is not equal to " << tests[i].port << std::endl;
        return 4;
      }
      if (uri.get_fragment() != tests[i].fragment) {
        std::cerr << "fragment " << uri.get_fragment() << " is not equal to " << tests[i].fragment << std::endl;
        return 5;
      }
      if (uri.get_host() != tests[i].host) {
        std::cerr << "host " << uri.get_host() << " is not equal to " << tests[i].host << std::endl;
        return 6;
      }
      if (uri.get_reg_based_authority() != tests[i].regbased_authority) {
        std::cerr << "regbased_authority " << uri.get_reg_based_authority() << " is not equal to "
                  << tests[i].regbased_authority << std::endl;
        return 7;
      }
      if (uri.get_user_info() != tests[i].userinfo) {
        std::cerr << "userinfo " << uri.get_user_info() << " is not equal to " << tests[i].userinfo << std::endl;
        return 8;
      }
      if (uri.get_path() != tests[i].path) {
        std::cerr << "path " << uri.get_path() << " is not equal to " << tests[i].path << std::endl;
        return 9;
      }
      if (uri.get_query() != tests[i].query) {
        std::cerr << "query " << uri.get_query() << " is not equal to " << tests[i].query << std::endl;
        return 10;
      }
      std::cout << "result: " << uri.toString() << std::endl;
    }
  } catch (zorba::error::ZorbaError & e) {
    std::cerr << e.theDescription << std::endl;
    return 11;
  }

  zorba::xqpString lToEncode("/a /b/c");
  zorba::xqpString lEncoded = lToEncode.encodeForUri("/",1);
  std::cout << "encoded " << lEncoded << std::endl;

  std::cout << "decoded " << lEncoded.decodeFromUri() << std::endl;

  return 0;

}
<commit_msg>Fixed uri unitest.<commit_after>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * 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.
 */
#include "zorbatypes/xqpstring.h"
#include "zorbatypes/URI.h"
#include "zorbaerrors/error_manager.h"

struct URITestEntry
{
  zorba::xqpString base;
  zorba::xqpString uri;
  zorba::xqpString text;
  zorba::xqpString scheme;
  int              port;
  zorba::xqpString fragment;
  zorba::xqpString host;
  zorba::xqpString regbased_authority;
  zorba::xqpString path;
  zorba::xqpString userinfo;
  zorba::xqpString query;
};

int uri(int argc, char* argv[])
{
  zorba::xqpString foo("/b");
  if (foo.endsWith("/.."))
    std::cout << foo << " ends with " << "/.." << std::endl;
  if (foo.endsWith("/\\.\\."))
    std::cout << foo << " ends with " << "/\\.\\." << std::endl;

  URITestEntry tests[] =
  {
    {
      "",
      "http://www.zorba-xquery.com/",
      "http://www.zorba-xquery.com/",
      "http",
      0,
      "",
      "www.zorba-xquery.com",
      "",
      "/",
      "",
      ""
    },
    {
      "",
      "http://www.zorba-xquery.com/?abc=true",
      "http://www.zorba-xquery.com/?abc=true",
      "http",
      0,
      "",
      "www.zorba-xquery.com",
      "",
      "/",
      "",
      "abc=true"
    },
    {
      "",
      "http://www.zorba-xquery.com:8080/?abc=true",
      "http://www.zorba-xquery.com:8080/?abc=true",
      "http",
      8080,
      "",
      "www.zorba-xquery.com",
      "",
      "/",
      "",
      "abc=true"
    },
    {
      "",
      "http://user@www.zorba-xquery.com:8080/?abc=true",
      "http://user@www.zorba-xquery.com:8080/?abc=true",
      "http",
      8080,
      "",
      "www.zorba-xquery.com",
      "",
      "/",
      "user",
      "abc=true"
    },
    {
      "",
      "http://user@www.zorba-xquery.com:8080/path1/path2?abc=true",
      "http://user@www.zorba-xquery.com:8080/path1/path2?abc=true",
      "http",
      8080,
      "",
      "www.zorba-xquery.com",
      "",
      "/path1/path2",
      "user",
      "abc=true"
    },
    {
      "",
      "http://user@www.zorba-xquery.com:8080/path1/path2?abc=true&bcd=false#fragment",
      "http://user@www.zorba-xquery.com:8080/path1/path2?abc=true&bcd=false#fragment",
      "http",
      8080,
      "fragment",
      "www.zorba-xquery.com",
      "",
      "/path1/path2",
      "user",
      "abc=true&bcd=false"
    },
    {
      "",
      "ftp://ftp.is.co.za/rfc/rfc1808.txt",
      "ftp://ftp.is.co.za/rfc/rfc1808.txt",
      "ftp",
      0,
      "",
      "ftp.is.co.za",
      "",
      "/rfc/rfc1808.txt",
      "",
      ""
    },
    {
      "",
      "http://thomas@[2001:6f8:9000:876:cccc:bbbb::]:123/test",
      "http://thomas@[2001:6f8:9000:876:cccc:bbbb::]:123/test",
      "http",
      123,
      "",
      "[2001:6f8:9000:876:cccc:bbbb::]",
      "",
      "/test",
      "thomas",
      ""
    },
    // uri resolver tests
    {
      "http://a/b/c/d;p?q",
      "g",
      "http://a/b/c/g",
      "http",
      0,
      "",
      "a",
      "",
      "/b/c/g",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "./g",
      "http://a/b/c/g",
      "http",
      0,
      "",
      "a",
      "",
      "/b/c/g",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "g/",
      "http://a/b/c/g/",
      "http",
      0,
      "",
      "a",
      "",
      "/b/c/g/",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "/g",
      "http://a/g",
      "http",
      0,
      "",
      "a",
      "",
      "/g",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "?y",
      "http://a/b/c/?y",
      "http",
      0,
      "",
      "a",
      "",
      "/b/c/",
      "",
      "y"
    },
    {
      "http://a/b/c/d;p?q",
      "g?y",
      "http://a/b/c/g?y",
      "http",
      0,
      "",
      "a",
      "",
      "/b/c/g",
      "",
      "y"
    } //,
  //{
  //  "http://a/b/c/d;p?q",
  //  "#s",
  //  "http://a/b/c/d;p?q#s",
  //  "http",
  //  0,
  //  "s",
  //  "a",
  //  "",
  //  "/b/c/g",
  //  "",
  //  ""
  //}
    ,
    {
      "http://a/b/c/d;p?q",
      "g#s",
      "http://a/b/c/g#s",
      "http",
      0,
      "s",
      "a",
      "",
      "/b/c/g",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "g?y#s",
      "http://a/b/c/g?y#s",
      "http",
      0,
      "s",
      "a",
      "",
      "/b/c/g",
      "",
      "y"
    },
    {
      "http://a/b/c/d;p?q",
      ";x",
      "http://a/b/c/;x",
      "http",
      0,
      "",
      "a",
      "",
      "/b/c/;x",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "g;x",
      "http://a/b/c/g;x",
      "http",
      0,
      "",
      "a",
      "",
      "/b/c/g;x",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "g;x?y#s",
      "http://a/b/c/g;x?y#s",
      "http",
      0,
      "s",
      "a",
      "",
      "/b/c/g;x",
      "",
      "y"
    },
    {
      "http://a/b/c/d;p?q",
      ".",
      "http://a/b/c/",
      "http",
      0,
      "",
      "a",
      "",
      "/b/c/",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "./",
      "http://a/b/c/",
      "http",
      0,
      "",
      "a",
      "",
      "/b/c/",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "..",
      "http://a/b/",
      "http",
      0,
      "",
      "a",
      "",
      "/b/",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "../",
      "http://a/b/",
      "http",
      0,
      "",
      "a",
      "",
      "/b/",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "../g",
      "http://a/b/g",
      "http",
      0,
      "",
      "a",
      "",
      "/b/g",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "../..",
      "http://a/",
      "http",
      0,
      "",
      "a",
      "",
      "/",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "../../",
      "http://a/",
      "http",
      0,
      "",
      "a",
      "",
      "/",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "../../g",
      "http://a/g",
      "http",
      0,
      "",
      "a",
      "",
      "/g",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "g;x=1/./y",
      "http://a/b/c/g;x=1/y",
      "http",
      0,
      "",
      "a",
      "",
      "/b/c/g;x=1/y",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "g;x=1/../y",
      "http://a/b/c/y",
      "http",
      0,
      "",
      "a",
      "",
      "/b/c/y",
      "",
      ""
    },
    {
      "http://a/b/c/d;p?q",
      "g#s/../x",
      "http://a/b/c/g#s/../x",
      "http",
      0,
      "s/../x",
      "a",
      "",
      "/b/c/g",
      "",
      ""
    },
    {
      "",
      "file://d:/a/b/c",
      "file://d:/a/b/c",
      "file",
      0,
      "",
      "",
      "d:",
      "/a/b/c",
      "",
      ""
    },
    {
      "file://a",
      "/a/b/c",
      "file://a/a/b/c",
      "file",
      0,
      "",
      "a",
      "",
      "/a/b/c",
      "",
      ""
    },
    {
      "",
      "http://www.msb.de",
      "http://www.msb.de",
      "http",
      0,
      "",
      "www.msb.de",
      "",
      "",
      "",
      ""
    },
    {
      "http://www.msb.de/",
      "lib/helpers",
      "http://www.msb.de/lib/helpers",
      "http",
      0,
      "",
      "www.msb.de",
      "",
      "/lib/helpers",
      "",
      ""
    }
  }; // URITestEntry tests[]

  const unsigned int test_count = sizeof(tests) / sizeof(tests[0]);
  try {
    for (unsigned int i = 0; i < test_count; ++i) {
      std::cout << "executing test number " << i << " with uri " << tests[i].uri << std::endl;

      zorba::URI uri;
      if (tests[i].base.empty()) {
        uri = zorba::URI(tests[i].uri);
      } else  {
        zorba::URI base(tests[i].base);
        uri = zorba::URI(base, tests[i].uri);
      }
      if (uri.toString() != tests[i].text)  {
        std::cerr << "uri text " << uri.toString() << " is not equal to " << tests[i].text << std::endl;
        return 2;
      }
      if (uri.get_scheme() != tests[i].scheme)
        return 3;
      if (uri.get_port() != tests[i].port) {
        std::cerr << "port " << uri.get_port() << " is not equal to " << tests[i].port << std::endl;
        return 4;
      }
      if (uri.get_fragment() != tests[i].fragment) {
        std::cerr << "fragment " << uri.get_fragment() << " is not equal to " << tests[i].fragment << std::endl;
        return 5;
      }
      if (uri.get_host() != tests[i].host) {
        std::cerr << "host " << uri.get_host() << " is not equal to " << tests[i].host << std::endl;
        return 6;
      }
      if (uri.get_reg_based_authority() != tests[i].regbased_authority) {
        std::cerr << "regbased_authority " << uri.get_reg_based_authority() << " is not equal to "
                  << tests[i].regbased_authority << std::endl;
        return 7;
      }
      if (uri.get_user_info() != tests[i].userinfo) {
        std::cerr << "userinfo " << uri.get_user_info() << " is not equal to " << tests[i].userinfo << std::endl;
        return 8;
      }
      if (uri.get_path() != tests[i].path) {
        std::cerr << "path " << uri.get_path() << " is not equal to " << tests[i].path << std::endl;
        return 9;
      }
      if (uri.get_query() != tests[i].query) {
        std::cerr << "query " << uri.get_query() << " is not equal to " << tests[i].query << std::endl;
        return 10;
      }
      std::cout << "result: " << uri.toString() << std::endl;
    }
  } catch (zorba::error::ZorbaError & e) {
    std::cerr << e.theDescription << std::endl;
    return 11;
  }

  zorba::xqpString lToEncode("/a /b/c");
  zorba::xqpString lEncoded = lToEncode.encodeForUri("/",1);
  std::cout << "encoded " << lEncoded << std::endl;

  std::cout << "decoded " << lEncoded.decodeFromUri() << std::endl;

  return 0;

}
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: http://www.qt-project.org/
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**************************************************************************/

#include "toolchainmanager.h"

#include "abi.h"
#include "kitinformation.h"
#include "toolchain.h"

#include <coreplugin/icore.h>

#include <extensionsystem/pluginmanager.h>

#include <utils/persistentsettings.h>
#include <utils/qtcassert.h>

#include <QCoreApplication>
#include <QDir>
#include <QSettings>

static const char TOOLCHAIN_DATA_KEY[] = "ToolChain.";
static const char TOOLCHAIN_COUNT_KEY[] = "ToolChain.Count";
static const char TOOLCHAIN_FILE_VERSION_KEY[] = "Version";
static const char DEFAULT_DEBUGGER_COUNT_KEY[] = "DefaultDebugger.Count";
static const char DEFAULT_DEBUGGER_ABI_KEY[] = "DefaultDebugger.Abi.";
static const char DEFAULT_DEBUGGER_PATH_KEY[] = "DefaultDebugger.Path.";
static const char TOOLCHAIN_FILENAME[] = "/qtcreator/toolchains.xml";
static const char LEGACY_TOOLCHAIN_FILENAME[] = "/toolChains.xml";

using Utils::PersistentSettingsWriter;
using Utils::PersistentSettingsReader;

static Utils::FileName settingsFileName(const QString &path)
{
    QFileInfo settingsLocation(ExtensionSystem::PluginManager::settings()->fileName());
    return Utils::FileName::fromString(settingsLocation.absolutePath() + path);
}

namespace ProjectExplorer {

ToolChainManager *ToolChainManager::m_instance = 0;

namespace Internal {

// --------------------------------------------------------------------------
// ToolChainManagerPrivate
// --------------------------------------------------------------------------

class ToolChainManagerPrivate
{
public:
    ToolChainManagerPrivate(ToolChainManager *parent);
    ~ToolChainManagerPrivate();

    QList<ToolChain *> &toolChains();

    ToolChainManager *q;
    QMap<QString, Utils::FileName> m_abiToDebugger;
    Utils::PersistentSettingsWriter *m_writer;

private:
    QList<ToolChain *> m_toolChains;
};

ToolChainManagerPrivate::ToolChainManagerPrivate(ToolChainManager *parent)
    : q(parent), m_writer(0)
{ }

ToolChainManagerPrivate::~ToolChainManagerPrivate()
{ delete m_writer; }

QList<ToolChain *> &ToolChainManagerPrivate::toolChains()
{
    if (!m_writer)
        q->restoreToolChains();
    return m_toolChains;
}

} // namespace Internal

// --------------------------------------------------------------------------
// ToolChainManager
// --------------------------------------------------------------------------

ToolChainManager *ToolChainManager::instance()
{
    return m_instance;
}

ToolChainManager::ToolChainManager(QObject *parent) :
    QObject(parent),
    d(new Internal::ToolChainManagerPrivate(this))
{
    Q_ASSERT(!m_instance);
    m_instance = this;

    connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()),
            this, SLOT(saveToolChains()));
    connect(this, SIGNAL(toolChainAdded(ProjectExplorer::ToolChain*)),
            this, SIGNAL(toolChainsChanged()));
    connect(this, SIGNAL(toolChainRemoved(ProjectExplorer::ToolChain*)),
            this, SIGNAL(toolChainsChanged()));
    connect(this, SIGNAL(toolChainUpdated(ProjectExplorer::ToolChain*)),
            this, SIGNAL(toolChainsChanged()));
}

void ToolChainManager::restoreToolChains()
{
    QTC_ASSERT(!d->m_writer, return);
    d->m_writer =
            new Utils::PersistentSettingsWriter(settingsFileName(QLatin1String(TOOLCHAIN_FILENAME)), QLatin1String("QtCreatorToolChains"));

    QList<ToolChain *> tcsToRegister;
    QList<ToolChain *> tcsToCheck;

    // read all tool chains from SDK
    QFileInfo systemSettingsFile(Core::ICore::settings(QSettings::SystemScope)->fileName());
    QList<ToolChain *> readTcs =
            restoreToolChains(Utils::FileName::fromString(systemSettingsFile.absolutePath() + QLatin1String(TOOLCHAIN_FILENAME)));
    // make sure we mark these as autodetected!
    foreach (ToolChain *tc, readTcs)
        tc->setAutoDetected(true);

    tcsToRegister = readTcs; // SDK TCs are always considered to be up-to-date, so no need to
                             // recheck them.

    // read all tool chains from user file.
    // Read legacy settings once and keep them around...
    Utils::FileName fileName = settingsFileName(QLatin1String(TOOLCHAIN_FILENAME));
    if (!fileName.toFileInfo().exists())
        fileName = settingsFileName(QLatin1String(LEGACY_TOOLCHAIN_FILENAME));
    readTcs = restoreToolChains(fileName);

    foreach (ToolChain *tc, readTcs) {
        if (tc->isAutoDetected())
            tcsToCheck.append(tc);
        else
            tcsToRegister.append(tc);
    }
    readTcs.clear();

    // Then auto detect
    QList<ToolChain *> detectedTcs;
    QList<ToolChainFactory *> factories = ExtensionSystem::PluginManager::getObjects<ToolChainFactory>();
    foreach (ToolChainFactory *f, factories)
        detectedTcs.append(f->autoDetect());

    // Find/update autodetected tool chains:
    ToolChain *toStore = 0;
    foreach (ToolChain *currentDetected, detectedTcs) {
        toStore = currentDetected;

        // Check whether we had this TC stored and prefer the old one with the old id:
        for (int i = 0; i < tcsToCheck.count(); ++i) {
            if (*(tcsToCheck.at(i)) == *currentDetected) {
                toStore = tcsToCheck.at(i);
                tcsToCheck.removeAt(i);
                delete currentDetected;
                break;
            }
        }
        registerToolChain(toStore);
    }

    // Delete all loaded autodetected tool chains that were not rediscovered:
    qDeleteAll(tcsToCheck);

    // Store manual tool chains
    foreach (ToolChain *tc, tcsToRegister)
        registerToolChain(tc);
}

ToolChainManager::~ToolChainManager()
{
    // Deregister tool chains
    QList<ToolChain *> copy = d->toolChains();
    foreach (ToolChain *tc, copy)
        deregisterToolChain(tc);

    delete d;
    m_instance = 0;
}

void ToolChainManager::saveToolChains()
{
    QVariantMap data;
    data.insert(QLatin1String(TOOLCHAIN_FILE_VERSION_KEY), 1);

    int count = 0;
    foreach (ToolChain *tc, d->toolChains()) {
        if (tc->isValid()) {
            QVariantMap tmp = tc->toMap();
            if (tmp.isEmpty())
                continue;
            data.insert(QString::fromLatin1(TOOLCHAIN_DATA_KEY) + QString::number(count), tmp);
            ++count;
        }
    }
    data.insert(QLatin1String(TOOLCHAIN_COUNT_KEY), count);
    d->m_writer->save(data, Core::ICore::mainWindow());

    // Do not save default debuggers! Those are set by the SDK!
}

QList<ToolChain *> ToolChainManager::restoreToolChains(const Utils::FileName &fileName)
{
    QList<ToolChain *> result;

    PersistentSettingsReader reader;
    if (!reader.load(fileName))
        return result;
    QVariantMap data = reader.restoreValues();

    // Check version:
    int version = data.value(QLatin1String(TOOLCHAIN_FILE_VERSION_KEY), 0).toInt();
    if (version < 1)
        return result;

    // Read default debugger settings (if any)
    int count = data.value(QLatin1String(DEFAULT_DEBUGGER_COUNT_KEY)).toInt();
    for (int i = 0; i < count; ++i) {
        const QString abiKey = QString::fromLatin1(DEFAULT_DEBUGGER_ABI_KEY) + QString::number(i);
        if (!data.contains(abiKey))
            continue;
        const QString pathKey = QString::fromLatin1(DEFAULT_DEBUGGER_PATH_KEY) + QString::number(i);
        if (!data.contains(pathKey))
            continue;
        d->m_abiToDebugger.insert(data.value(abiKey).toString(),
                                  Utils::FileName::fromString(data.value(pathKey).toString()));
    }

    QList<ToolChainFactory *> factories = ExtensionSystem::PluginManager::getObjects<ToolChainFactory>();

    count = data.value(QLatin1String(TOOLCHAIN_COUNT_KEY), 0).toInt();
    for (int i = 0; i < count; ++i) {
        const QString key = QString::fromLatin1(TOOLCHAIN_DATA_KEY) + QString::number(i);
        if (!data.contains(key))
            break;

        const QVariantMap tcMap = data.value(key).toMap();

        bool restored = false;
        foreach (ToolChainFactory *f, factories) {
            if (f->canRestore(tcMap)) {
                if (ToolChain *tc = f->restore(tcMap)) {
                    result.append(tc);
                    restored = true;
                    break;
                }
            }
        }
        if (!restored)
            qWarning("Warning: Unable to restore compiler '%s' stored in %s.",
                     qPrintable(ToolChainFactory::idFromMap(tcMap)),
                     qPrintable(fileName.toUserOutput()));
    }
    return result;
}

QList<ToolChain *> ToolChainManager::toolChains() const
{
    return d->toolChains();
}

QList<ToolChain *> ToolChainManager::findToolChains(const Abi &abi) const
{
    QList<ToolChain *> result;
    foreach (ToolChain *tc, toolChains()) {
        Abi targetAbi = tc->targetAbi();
        if (targetAbi.isCompatibleWith(abi))
            result.append(tc);
    }
    return result;
}

ToolChain *ToolChainManager::findToolChain(const QString &id) const
{
    if (id.isEmpty())
        return 0;

    foreach (ToolChain *tc, d->toolChains()) {
        if (tc->id() == id)
            return tc;
    }
    return 0;
}

Utils::FileName ToolChainManager::defaultDebugger(const Abi &abi) const
{
    return d->m_abiToDebugger.value(abi.toString());
}

void ToolChainManager::notifyAboutUpdate(ProjectExplorer::ToolChain *tc)
{
    if (!tc || !toolChains().contains(tc))
        return;
    emit toolChainUpdated(tc);
}

bool ToolChainManager::registerToolChain(ToolChain *tc)
{
    if (!tc || d->toolChains().contains(tc))
        return true;
    foreach (ToolChain *current, d->toolChains()) {
        if (*tc == *current && !tc->isAutoDetected())
            return false;
    }

    d->toolChains().append(tc);
    emit toolChainAdded(tc);
    return true;
}

void ToolChainManager::deregisterToolChain(ToolChain *tc)
{
    if (!tc || !d->toolChains().contains(tc))
        return;
    d->toolChains().removeOne(tc);
    emit toolChainRemoved(tc);
    delete tc;
}

} // namespace ProjectExplorer
<commit_msg>Warn when failing to restore auto-detected tool chains<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: http://www.qt-project.org/
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**************************************************************************/

#include "toolchainmanager.h"

#include "abi.h"
#include "kitinformation.h"
#include "toolchain.h"

#include <coreplugin/icore.h>

#include <extensionsystem/pluginmanager.h>

#include <utils/persistentsettings.h>
#include <utils/qtcassert.h>

#include <QCoreApplication>
#include <QDir>
#include <QSettings>

static const char TOOLCHAIN_DATA_KEY[] = "ToolChain.";
static const char TOOLCHAIN_COUNT_KEY[] = "ToolChain.Count";
static const char TOOLCHAIN_FILE_VERSION_KEY[] = "Version";
static const char DEFAULT_DEBUGGER_COUNT_KEY[] = "DefaultDebugger.Count";
static const char DEFAULT_DEBUGGER_ABI_KEY[] = "DefaultDebugger.Abi.";
static const char DEFAULT_DEBUGGER_PATH_KEY[] = "DefaultDebugger.Path.";
static const char TOOLCHAIN_FILENAME[] = "/qtcreator/toolchains.xml";
static const char LEGACY_TOOLCHAIN_FILENAME[] = "/toolChains.xml";

using Utils::PersistentSettingsWriter;
using Utils::PersistentSettingsReader;

static Utils::FileName settingsFileName(const QString &path)
{
    QFileInfo settingsLocation(ExtensionSystem::PluginManager::settings()->fileName());
    return Utils::FileName::fromString(settingsLocation.absolutePath() + path);
}

namespace ProjectExplorer {

ToolChainManager *ToolChainManager::m_instance = 0;

namespace Internal {

// --------------------------------------------------------------------------
// ToolChainManagerPrivate
// --------------------------------------------------------------------------

class ToolChainManagerPrivate
{
public:
    ToolChainManagerPrivate(ToolChainManager *parent);
    ~ToolChainManagerPrivate();

    QList<ToolChain *> &toolChains();

    ToolChainManager *q;
    QMap<QString, Utils::FileName> m_abiToDebugger;
    Utils::PersistentSettingsWriter *m_writer;

private:
    QList<ToolChain *> m_toolChains;
};

ToolChainManagerPrivate::ToolChainManagerPrivate(ToolChainManager *parent)
    : q(parent), m_writer(0)
{ }

ToolChainManagerPrivate::~ToolChainManagerPrivate()
{ delete m_writer; }

QList<ToolChain *> &ToolChainManagerPrivate::toolChains()
{
    if (!m_writer)
        q->restoreToolChains();
    return m_toolChains;
}

} // namespace Internal

// --------------------------------------------------------------------------
// ToolChainManager
// --------------------------------------------------------------------------

ToolChainManager *ToolChainManager::instance()
{
    return m_instance;
}

ToolChainManager::ToolChainManager(QObject *parent) :
    QObject(parent),
    d(new Internal::ToolChainManagerPrivate(this))
{
    Q_ASSERT(!m_instance);
    m_instance = this;

    connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()),
            this, SLOT(saveToolChains()));
    connect(this, SIGNAL(toolChainAdded(ProjectExplorer::ToolChain*)),
            this, SIGNAL(toolChainsChanged()));
    connect(this, SIGNAL(toolChainRemoved(ProjectExplorer::ToolChain*)),
            this, SIGNAL(toolChainsChanged()));
    connect(this, SIGNAL(toolChainUpdated(ProjectExplorer::ToolChain*)),
            this, SIGNAL(toolChainsChanged()));
}

void ToolChainManager::restoreToolChains()
{
    QTC_ASSERT(!d->m_writer, return);
    d->m_writer =
            new Utils::PersistentSettingsWriter(settingsFileName(QLatin1String(TOOLCHAIN_FILENAME)), QLatin1String("QtCreatorToolChains"));

    QList<ToolChain *> tcsToRegister;
    QList<ToolChain *> tcsToCheck;

    // read all tool chains from SDK
    QFileInfo systemSettingsFile(Core::ICore::settings(QSettings::SystemScope)->fileName());
    QList<ToolChain *> readTcs =
            restoreToolChains(Utils::FileName::fromString(systemSettingsFile.absolutePath() + QLatin1String(TOOLCHAIN_FILENAME)));
    // make sure we mark these as autodetected!
    foreach (ToolChain *tc, readTcs)
        tc->setAutoDetected(true);

    tcsToRegister = readTcs; // SDK TCs are always considered to be up-to-date, so no need to
                             // recheck them.

    // read all tool chains from user file.
    // Read legacy settings once and keep them around...
    Utils::FileName fileName = settingsFileName(QLatin1String(TOOLCHAIN_FILENAME));
    if (!fileName.toFileInfo().exists())
        fileName = settingsFileName(QLatin1String(LEGACY_TOOLCHAIN_FILENAME));
    readTcs = restoreToolChains(fileName);

    foreach (ToolChain *tc, readTcs) {
        if (tc->isAutoDetected())
            tcsToCheck.append(tc);
        else
            tcsToRegister.append(tc);
    }
    readTcs.clear();

    // Then auto detect
    QList<ToolChain *> detectedTcs;
    QList<ToolChainFactory *> factories = ExtensionSystem::PluginManager::getObjects<ToolChainFactory>();
    foreach (ToolChainFactory *f, factories)
        detectedTcs.append(f->autoDetect());

    // Find/update autodetected tool chains:
    ToolChain *toStore = 0;
    foreach (ToolChain *currentDetected, detectedTcs) {
        toStore = currentDetected;

        // Check whether we had this TC stored and prefer the old one with the old id:
        for (int i = 0; i < tcsToCheck.count(); ++i) {
            if (*(tcsToCheck.at(i)) == *currentDetected) {
                toStore = tcsToCheck.at(i);
                tcsToCheck.removeAt(i);
                delete currentDetected;
                break;
            }
        }
        registerToolChain(toStore);
    }

    // Delete all loaded autodetected tool chains that were not rediscovered:
    foreach (ToolChain *tc, tcsToCheck) {
        qWarning() << QString::fromLatin1("ToolChain \"%1\" (%2) dropped since it was not auto-detected again")
                      .arg(tc->displayName()).arg(tc->id());
        delete tc;
    }

    // Store manual tool chains
    foreach (ToolChain *tc, tcsToRegister)
        registerToolChain(tc);
}

ToolChainManager::~ToolChainManager()
{
    // Deregister tool chains
    QList<ToolChain *> copy = d->toolChains();
    foreach (ToolChain *tc, copy)
        deregisterToolChain(tc);

    delete d;
    m_instance = 0;
}

void ToolChainManager::saveToolChains()
{
    QVariantMap data;
    data.insert(QLatin1String(TOOLCHAIN_FILE_VERSION_KEY), 1);

    int count = 0;
    foreach (ToolChain *tc, d->toolChains()) {
        if (tc->isValid()) {
            QVariantMap tmp = tc->toMap();
            if (tmp.isEmpty())
                continue;
            data.insert(QString::fromLatin1(TOOLCHAIN_DATA_KEY) + QString::number(count), tmp);
            ++count;
        }
    }
    data.insert(QLatin1String(TOOLCHAIN_COUNT_KEY), count);
    d->m_writer->save(data, Core::ICore::mainWindow());

    // Do not save default debuggers! Those are set by the SDK!
}

QList<ToolChain *> ToolChainManager::restoreToolChains(const Utils::FileName &fileName)
{
    QList<ToolChain *> result;

    PersistentSettingsReader reader;
    if (!reader.load(fileName))
        return result;
    QVariantMap data = reader.restoreValues();

    // Check version:
    int version = data.value(QLatin1String(TOOLCHAIN_FILE_VERSION_KEY), 0).toInt();
    if (version < 1)
        return result;

    // Read default debugger settings (if any)
    int count = data.value(QLatin1String(DEFAULT_DEBUGGER_COUNT_KEY)).toInt();
    for (int i = 0; i < count; ++i) {
        const QString abiKey = QString::fromLatin1(DEFAULT_DEBUGGER_ABI_KEY) + QString::number(i);
        if (!data.contains(abiKey))
            continue;
        const QString pathKey = QString::fromLatin1(DEFAULT_DEBUGGER_PATH_KEY) + QString::number(i);
        if (!data.contains(pathKey))
            continue;
        d->m_abiToDebugger.insert(data.value(abiKey).toString(),
                                  Utils::FileName::fromString(data.value(pathKey).toString()));
    }

    QList<ToolChainFactory *> factories = ExtensionSystem::PluginManager::getObjects<ToolChainFactory>();

    count = data.value(QLatin1String(TOOLCHAIN_COUNT_KEY), 0).toInt();
    for (int i = 0; i < count; ++i) {
        const QString key = QString::fromLatin1(TOOLCHAIN_DATA_KEY) + QString::number(i);
        if (!data.contains(key))
            break;

        const QVariantMap tcMap = data.value(key).toMap();

        bool restored = false;
        foreach (ToolChainFactory *f, factories) {
            if (f->canRestore(tcMap)) {
                if (ToolChain *tc = f->restore(tcMap)) {
                    result.append(tc);
                    restored = true;
                    break;
                }
            }
        }
        if (!restored)
            qWarning("Warning: Unable to restore compiler '%s' stored in %s.",
                     qPrintable(ToolChainFactory::idFromMap(tcMap)),
                     qPrintable(fileName.toUserOutput()));
    }
    return result;
}

QList<ToolChain *> ToolChainManager::toolChains() const
{
    return d->toolChains();
}

QList<ToolChain *> ToolChainManager::findToolChains(const Abi &abi) const
{
    QList<ToolChain *> result;
    foreach (ToolChain *tc, toolChains()) {
        Abi targetAbi = tc->targetAbi();
        if (targetAbi.isCompatibleWith(abi))
            result.append(tc);
    }
    return result;
}

ToolChain *ToolChainManager::findToolChain(const QString &id) const
{
    if (id.isEmpty())
        return 0;

    foreach (ToolChain *tc, d->toolChains()) {
        if (tc->id() == id)
            return tc;
    }
    return 0;
}

Utils::FileName ToolChainManager::defaultDebugger(const Abi &abi) const
{
    return d->m_abiToDebugger.value(abi.toString());
}

void ToolChainManager::notifyAboutUpdate(ProjectExplorer::ToolChain *tc)
{
    if (!tc || !toolChains().contains(tc))
        return;
    emit toolChainUpdated(tc);
}

bool ToolChainManager::registerToolChain(ToolChain *tc)
{
    if (!tc || d->toolChains().contains(tc))
        return true;
    foreach (ToolChain *current, d->toolChains()) {
        if (*tc == *current && !tc->isAutoDetected())
            return false;
    }

    d->toolChains().append(tc);
    emit toolChainAdded(tc);
    return true;
}

void ToolChainManager::deregisterToolChain(ToolChain *tc)
{
    if (!tc || !d->toolChains().contains(tc))
        return;
    d->toolChains().removeOne(tc);
    emit toolChainRemoved(tc);
    delete tc;
}

} // namespace ProjectExplorer
<|endoftext|>


<commit_before>#include "nuFATE.h"

double nuFACE::readDoubleAttribute(hid_t object, std::string name){
        double target;
        hid_t attribute_id = H5Aopen(object,name.c_str(),H5P_DEFAULT);
        herr_t status = H5Aread(attribute_id, H5T_NATIVE_DOUBLE, &target);
        if(status<0)
            throw std::runtime_error("Failed to read attribute '"+name+"'");
        H5Aclose(attribute_id);
        return target;
}

double* nuFACE::logspace(double Emin,double Emax,unsigned int div){
        if(div==0)
            throw std::length_error("number of samples requested from logspace must be nonzero");
        double logpoints[div];
        double Emin_log,Emax_log;
        Emin_log = log(Emin);
        Emax_log = log(Emax);

        double step_log = (Emax_log - Emin_log)/double(div-1);

        logpoints[0]=Emin;
        double EE = Emin_log+step_log;
        for(unsigned int i=1; i<div-1; i++, EE+=step_log)
            logpoints[i] = exp(EE);
        logpoints[div-1]=Emax;
        double* logpoints_ = &logpoints[0];
        return logpoints_;
}

double* nuFACE::get_glashow_total(double NumNodes, double* energy_nodes){
    double GF = 1.16e-5
    double hbarc = 1.97e-14
    double GW = 2.085
    double MW = 80.385e0
    double mmu = 0.106e0
    double me = 511.e-6
    double pi = 3.14159265358979323846
    glashow_total_ = (double *)malloc(NumNodes*sizeof(double));

    for(int i=0; i<=NumNodes; i++){
        double x = *(glashow_total_+i);
        *(glashow_total_ +i) = 2.*me*(*(energy_nodes+i));
        *(glashow_total_ +i) = 1. /3.*std::pow(GF,2)*x/pi*std::pow((1.-(std::pow(mmu,2)-std::pow(me,2))/x),2)/(std::pow((1.-x/std::pow(MW,2)),2)+std::pow(GW,2)/std::pow(MW,2))*0.676/0.1057*std::pow(hbarc,2);
    }
    return glashow_total_;
}

double* nuFACE::get_RHS_matrices(double NumNodes, double* energy_nodes, std::shared_ptr<double> sigma_array_, double* dxs_array_){

        DeltaE_ = (double *)malloc(NumNodes*sizeof(double));
        for(int i = 0; i <= NumNodes-1;i++){
            *(DeltaE_ + i) = log10(*(energy_nodes+i+1)) - log10(*(energy_nodes+i));
        }

        double RHSMatrix[NumNodes][NumNodes] = {};

        for(int i = 0; i <= NumNodes; i++)
        {
            for(int j= i+1; j <= NumNodes )
            {
                double e1 = 1./ *(energy_nodes+j);
                double e2 = *(energy_nodes+i) * *(energy_nodes+i);
                RHSMatrix[i][j] = *(DeltaE_ + j - 1) * *(dxs_array_+j * dxsdim[1]+i) * e1 * e2;
            }
        }

        double* RHSMatrix_ = &RHSMatrix[0][0];
        return RHSMatrix_;
}

nuFACE::get_eigs(int flavor, double gamma, string h5_filename) {

        newflavor = flavor;
        newgamma = gamma;
        newh5_filename = h5_filename;

        //open h5file containing cross sections

        hid_t file_id,group_id,root_id;

        file_id = H5Fopen(h5_filename.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);
        root_id = H5Gopen(file_id, "/", H5P_DEFAULT);

        std::string grptot = "/total_cross_sections";
        std::string grpdiff = "/differential_cross_sections";
        group_id = H5Gopen(root_id, grptot.c_str(), H5P_DEFAULT);

        //Get energy information
        double Emin = readDoubleAttribute(group_id, 'max_energy')
        double Emax = readDoubleAttribute(group_id, 'min_energy')
        double NumNodes = readDoubleAttribute(group_id, 'number_energy_nodes')
        energy_nodes = logspace(Emin, Emax, Numnodes)

        //Get sigma_array

        if (flavor == -1) {
            hsize_t sarraysize[1];
            H5LTget_dataset_info(group_id,"nuebarxs", sarraysize,NULL,NULL);
            sigma_array_ = std::make_shared<double>(sarraysize[0]);
            H5LTread_dataset_double(group_id, "nuebarxs", sigma_array_);
        }  else if (flavor == -2){
            hsize_t sarraysize[1];
            H5LTget_dataset_info(group_id,"numubarxs", sarraysize,NULL,NULL);
            sigma_array_ = std::make_shared<double>(sarraysize[0]);
            H5LTread_dataset_double(group_id, "numubarxs", sigma_array_);
        }  else if (flavor == -3){
            hsize_t sarraysize[1];
            H5LTget_dataset_info(group_id,"nutaubarxs", sarraysize,NULL,NULL);
            sigma_array_ = std::make_shared<double>(sarraysize[0]);
            H5LTread_dataset_double(group_id, "nutaubarxs", sigma_array_);
        }  else if (flavor == 1){
            hsize_t sarraysize[1];
            H5LTget_dataset_info(group_id,"nuexs", sarraysize,NULL,NULL);
            sigma_array_ = std::make_shared<double>(sarraysize[0]);
            H5LTread_dataset_double(group_id, "nuexs", sigma_array_);
        }  else if (flavor == 2){
            hsize_t sarraysize[1];
            H5LTget_dataset_info(group_id,"numuxs", sarraysize,NULL,NULL);
            sigma_array_ = std::make_shared<double>(sarraysize[0]);
            H5LTread_dataset_double(group_id, "numuxs", sigma_array_);
        }  else if (flavor == 3){
            hsize_t sarraysize[1];
            H5LTget_dataset_info(group_id,"nutauxs", sarraysize,NULL,NULL);
            sigma_array_ = std::make_shared<double>(sarraysize[0]);
            H5LTread_dataset_double(group_id, "nutauxs", sigma_array_);
        }

        //Get differential cross sections

        hsize_t dxarraysize[2];
        group_id = H5Gopen(root_id, grpdiff.c_str(), H5P_DEFAULT);

        if (flavor > 0){
            H5LTget_dataset_info(group_id,"dxsnu", dxarraysize,NULL,NULL);
            size_t dim1 = dxarraysize[0];
            size_t dim2 = dxarraysize[1];
            dxsdim[0] = dxarraysize[0];
            dxsdim[1] = dxarraysize[1];
            dxs_array_ = (double *)malloc(dim1*dim2*sizeof(double));
            H5LTread_dataset(group_id, "dxsnu", dxs_array_);
        } else {
            H5LTget_dataset_info(group_id,"dxsnubar", dxarraysize,NULL,NULL);
            size_t dim1 = dxarraysize[0];
            size_t dim2 = dxarraysize[1];
            dxsdim[0] = dxarraysize[0];
            dxsdim[1] = dxarraysize[1];
            dxs_array_ = (double *)malloc(dim1*dim2*sizeof(double));
            H5LTread_dataset(group_id, "dxsnu", dxs_array_);
        }

        //Find RHS matrix

        RHSMatrix_ = get_RHS_matrices(NumNodes, energy_nodes, sigma_array_, dxs_array_);

        //Account for tau regeneration/Glashow resonance

        if (flavor = -3){
            std:string grptau = "/tau_decay_spectrum";
            group_id = H5Gopen(root_id, grptau.c_str(), H5P_DEFAULT);
            hsize_t tauarraysize[2];
            H5LTget_dataset_info(group_id,"tbarfull", tauarraysize,NULL,NULL);
            size_t dim1 = tauarraysize[0];
            size_t dim2 = taurraysize[1];
            tau_array_ = (double *)malloc(dim1*dim2*sizeof(double));
            H5LTread_dataset(group_id, "tbarfull", tau_array_);
            RHregen_ = get_RHS_matrices(NumNodes, energy_nodes, sigma_array_, tau_array_);
            for (int i = 0; i<=NumNodes; i++){
                for(int j=0; j<=NumNodes;j++)
                *(RHSMatrix_+i*NumNodes+j) = *(RHSMatrix_+i*NumNodes+j) + *(RHregen_+i*NumNodes+j);
            }
        } else if(flavor = 3){
            std:string grptau = "/tau_decay_spectrum";
            group_id = H5Gopen(root_id, grptau.c_str(), H5P_DEFAULT);
            hsize_t tauarraysize[2];
            H5LTget_dataset_info(group_id,"tfull", tauarraysize,NULL,NULL);
            size_t dim1 = tauarraysize[0];
            size_t dim2 = taurraysize[1];
            tau_array_ = (double *)malloc(dim1*dim2*sizeof(double));
            H5LTread_dataset(group_id, "tbarfull", tau_array_);
            RHregen_ = get_RHS_matrices(NumNodes, energy_nodes, sigma_array_, tau_array_);
            for (int i = 0; i<=NumNodes; i++){
                for(int j=0; j<=NumNodes;j++)
                *(RHSMatrix_+i*NumNodes+j) = *(RHSMatrix_+i*NumNodes+j) + *(RHregen_+i*NumNodes+j);
            }
        } else if(flavor = -1){
            glashow_total_ = get_glashow_total(energy_nodes);
            for (int i = 0; i<=sarraysize[0]; i++){
                *(sigma_array_+i) = *(sigma_array_+i) +
            }
        }

}

int nuFACE::getFlavor() const {
    return newflavor;
}

double nuFACE::getGamma() const {
    return newgamma;
}

string nuFACE::getFilename() const {
    return newh5_filename;
}
<commit_msg>Update nuFACE.cpp<commit_after>#include "nuFATE.h"

double nuFACE::readDoubleAttribute(hid_t object, std::string name){
        double target;
        hid_t attribute_id = H5Aopen(object,name.c_str(),H5P_DEFAULT);
        herr_t status = H5Aread(attribute_id, H5T_NATIVE_DOUBLE, &target);
        if(status<0)
            throw std::runtime_error("Failed to read attribute '"+name+"'");
        H5Aclose(attribute_id);
        return target;
}

double* nuFACE::logspace(double Emin,double Emax,unsigned int div){
        if(div==0)
            throw std::length_error("number of samples requested from logspace must be nonzero");
        double logpoints[div];
        double Emin_log,Emax_log;
        Emin_log = log(Emin);
        Emax_log = log(Emax);

        double step_log = (Emax_log - Emin_log)/double(div-1);

        logpoints[0]=Emin;
        double EE = Emin_log+step_log;
        for(unsigned int i=1; i<div-1; i++, EE+=step_log)
            logpoints[i] = exp(EE);
        logpoints[div-1]=Emax;
        double* logpoints_ = &logpoints[0];
        return logpoints_;
}

double* nuFACE::get_glashow_total(double NumNodes, double* energy_nodes){
    double GF = 1.16e-5
    double hbarc = 1.97e-14
    double GW = 2.085
    double MW = 80.385e0
    double mmu = 0.106e0
    double me = 511.e-6
    double pi = 3.14159265358979323846
    glashow_total_ = (double *)malloc(NumNodes*sizeof(double));

    for(int i=0; i<NumNodes; i++){
        double x = *(glashow_total_+i);
        *(glashow_total_ +i) = 2.*me*(*(energy_nodes+i));
        *(glashow_total_ +i) = 1. /3.*std::pow(GF,2)*x/pi*std::pow((1.-(std::pow(mmu,2)-std::pow(me,2))/x),2)/(std::pow((1.-x/std::pow(MW,2)),2)+std::pow(GW,2)/std::pow(MW,2))*0.676/0.1057*std::pow(hbarc,2);
    }
    return glashow_total_;
}

double* nuFACE::get_RHS_matrices(double NumNodes, double* energy_nodes, std::shared_ptr<double> sigma_array_, double* dxs_array_){

        DeltaE_ = (double *)malloc(NumNodes*sizeof(double));
        for(int i = 0; i < NumNodes-1;i++){
            *(DeltaE_ + i) = log10(*(energy_nodes+i+1)) - log10(*(energy_nodes+i));
        }

        double RHSMatrix[NumNodes][NumNodes] = {};

        for(int i = 0; i < NumNodes; i++)
        {
            for(int j= i+1; j < NumNodes )
            {
                double e1 = 1./ *(energy_nodes+j);
                double e2 = *(energy_nodes+i) * *(energy_nodes+i);
                RHSMatrix[i][j] = *(DeltaE_ + j - 1) * *(dxs_array_+j * dxsdim[1]+i) * e1 * e2;
            }
        }

        double* RHSMatrix_ = &RHSMatrix[0][0];
        return RHSMatrix_;
}

nuFACE::get_eigs(int flavor, double gamma, string h5_filename) {

        newflavor = flavor;
        newgamma = gamma;
        newh5_filename = h5_filename;

        //open h5file containing cross sections

        hid_t file_id,group_id,root_id;

        file_id = H5Fopen(h5_filename.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);
        root_id = H5Gopen(file_id, "/", H5P_DEFAULT);

        std::string grptot = "/total_cross_sections";
        std::string grpdiff = "/differential_cross_sections";
        group_id = H5Gopen(root_id, grptot.c_str(), H5P_DEFAULT);

        //Get energy information
        double Emin = readDoubleAttribute(group_id, 'max_energy')
        double Emax = readDoubleAttribute(group_id, 'min_energy')
        double NumNodes = readDoubleAttribute(group_id, 'number_energy_nodes')
        energy_nodes = logspace(Emin, Emax, Numnodes)

        //Get sigma_array

        if (flavor == -1) {
            hsize_t sarraysize[1];
            H5LTget_dataset_info(group_id,"nuebarxs", sarraysize,NULL,NULL);
            sigma_array_ = std::make_shared<double>(sarraysize[0]);
            H5LTread_dataset_double(group_id, "nuebarxs", sigma_array_);
        }  else if (flavor == -2){
            hsize_t sarraysize[1];
            H5LTget_dataset_info(group_id,"numubarxs", sarraysize,NULL,NULL);
            sigma_array_ = std::make_shared<double>(sarraysize[0]);
            H5LTread_dataset_double(group_id, "numubarxs", sigma_array_);
        }  else if (flavor == -3){
            hsize_t sarraysize[1];
            H5LTget_dataset_info(group_id,"nutaubarxs", sarraysize,NULL,NULL);
            sigma_array_ = std::make_shared<double>(sarraysize[0]);
            H5LTread_dataset_double(group_id, "nutaubarxs", sigma_array_);
        }  else if (flavor == 1){
            hsize_t sarraysize[1];
            H5LTget_dataset_info(group_id,"nuexs", sarraysize,NULL,NULL);
            sigma_array_ = std::make_shared<double>(sarraysize[0]);
            H5LTread_dataset_double(group_id, "nuexs", sigma_array_);
        }  else if (flavor == 2){
            hsize_t sarraysize[1];
            H5LTget_dataset_info(group_id,"numuxs", sarraysize,NULL,NULL);
            sigma_array_ = std::make_shared<double>(sarraysize[0]);
            H5LTread_dataset_double(group_id, "numuxs", sigma_array_);
        }  else if (flavor == 3){
            hsize_t sarraysize[1];
            H5LTget_dataset_info(group_id,"nutauxs", sarraysize,NULL,NULL);
            sigma_array_ = std::make_shared<double>(sarraysize[0]);
            H5LTread_dataset_double(group_id, "nutauxs", sigma_array_);
        }

        //Get differential cross sections

        hsize_t dxarraysize[2];
        group_id = H5Gopen(root_id, grpdiff.c_str(), H5P_DEFAULT);

        if (flavor > 0){
            H5LTget_dataset_info(group_id,"dxsnu", dxarraysize,NULL,NULL);
            size_t dim1 = dxarraysize[0];
            size_t dim2 = dxarraysize[1];
            dxsdim[0] = dxarraysize[0];
            dxsdim[1] = dxarraysize[1];
            dxs_array_ = (double *)malloc(dim1*dim2*sizeof(double));
            H5LTread_dataset(group_id, "dxsnu", dxs_array_);
        } else {
            H5LTget_dataset_info(group_id,"dxsnubar", dxarraysize,NULL,NULL);
            size_t dim1 = dxarraysize[0];
            size_t dim2 = dxarraysize[1];
            dxsdim[0] = dxarraysize[0];
            dxsdim[1] = dxarraysize[1];
            dxs_array_ = (double *)malloc(dim1*dim2*sizeof(double));
            H5LTread_dataset(group_id, "dxsnu", dxs_array_);
        }

        //Find RHS matrix

        RHSMatrix_ = get_RHS_matrices(NumNodes, energy_nodes, sigma_array_, dxs_array_);

        //Account for tau regeneration/Glashow resonance

        if (flavor == -3){
            std:string grptau = "/tau_decay_spectrum";
            group_id = H5Gopen(root_id, grptau.c_str(), H5P_DEFAULT);
            hsize_t tauarraysize[2];
            H5LTget_dataset_info(group_id,"tbarfull", tauarraysize,NULL,NULL);
            size_t dim1 = tauarraysize[0];
            size_t dim2 = taurraysize[1];
            tau_array_ = (double *)malloc(dim1*dim2*sizeof(double));
            H5LTread_dataset(group_id, "tbarfull", tau_array_);
            RHregen_ = get_RHS_matrices(NumNodes, energy_nodes, sigma_array_, tau_array_);
            for (int i = 0; i<NumNodes; i++){
                for(int j=0; j<NumNodes;j++)
                *(RHSMatrix_+i*NumNodes+j) = *(RHSMatrix_+i*NumNodes+j) + *(RHregen_+i*NumNodes+j);
            }
        } else if(flavor == 3){
            std:string grptau = "/tau_decay_spectrum";
            group_id = H5Gopen(root_id, grptau.c_str(), H5P_DEFAULT);
            hsize_t tauarraysize[2];
            H5LTget_dataset_info(group_id,"tfull", tauarraysize,NULL,NULL);
            size_t dim1 = tauarraysize[0];
            size_t dim2 = taurraysize[1];
            tau_array_ = (double *)malloc(dim1*dim2*sizeof(double));
            H5LTread_dataset(group_id, "tbarfull", tau_array_);
            RHregen_ = get_RHS_matrices(NumNodes, energy_nodes, sigma_array_, tau_array_);
            for (int i = 0; i<NumNodes; i++){
                for(int j=0; j<NumNodes;j++)
                *(RHSMatrix_+i*NumNodes+j) = *(RHSMatrix_+i*NumNodes+j) + *(RHregen_+i*NumNodes+j);
            }
        } else if(flavor == -1){
            double* glashow_total_ = get_glashow_total(energy_nodes);
            for (int i = 0; i < sarraysize[0]; i++){
                *(sigma_array_+i) = *(sigma_array_+i) + *(glashow_total_ + i)/2.;
                *(RHSMatrix_ +i) = *(RHSMatrix_ +i) + *(glashow_partial_ + i)/2.;

            }
        }
        phi_0_ = (double *)malloc(NumNodes*sizeof(double));
        for (int i = 0; i < NumNodes; i++){
            *(phi_0_ + i) = std::pow(*(energy_nodes +i),(2-gamma));
        }
        for (int i = 0; i < sarraysize[0]; i++){
            *(RHSMatrix_+i*sarraysize[0]+i) = *(RHSMatrix_+i*sarraysize[0]+i) + *(sigma_array_+i);
        }

        //compute eigenvalues and eigenvectors

        gsl_matrix_view m = gsl_matrix_view_array(RHSMatrix_, NumNodes, NumNodes);
        gsl_vector *eval = gsl_vector_alloc (NumNodes);
        gsl_matrix *evec = gsl_matrix_alloc (NumNodes, NumNodes);
        gsl_eigen_nonsymmv_workspace * w = gsl_eigen_nonsymmv_alloc (NumNodes);

        gsl_eigen_nonsymmv (&m.matrix, eval, evec, w);

        int s;
        gsl_vector *ci = gsl_vector_alloc(NumNodes);
        gsl_permutation *p = gsl_permutation_alloc(NumNodes);

        gsl_linalg_LU_decomp (&m.matrix, p, &s);
        gsl_linalg_LU_solve (&m.matrix, p, phi_0_, ci);

        //free unneeded memory
        gsl_permutation_free (p);
        gsl_eigen_nonsymmv_free (w);

        return eval, evec, ci, energy_nodes, phi_0_;
}

int nuFACE::getFlavor() const {
    return newflavor;
}

double nuFACE::getGamma() const {
    return newgamma;
}

string nuFACE::getFilename() const {
    return newh5_filename;
}
<|endoftext|>


<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2011      Valery Kharitonov <kharvd@gmail.com>
//

// Self
#include "PostalCodeItem.h"

// Marble
#include "GeoPainter.h"
#include "ViewportParams.h"

// Qt
#include <QtGui/QFontMetrics>

using namespace Marble;

const QFont PostalCodeItem::s_font = QFont( "Sans Serif", 10, QFont::Bold );
const int PostalCodeItem::s_labelOutlineWidth = 5;

PostalCodeItem::PostalCodeItem( QObject *parent )
    : AbstractDataPluginItem( parent )
{
    setSize( QSize( 0, 0 ) );
}

PostalCodeItem::~PostalCodeItem()
{
}

QString PostalCodeItem::itemType() const
{
    return "postalCodeItem";
}

bool PostalCodeItem::initialized()
{
    return !m_text.isEmpty();
}

bool PostalCodeItem::operator<( const AbstractDataPluginItem *other ) const
{
    return this->id() < other->id();
}

QString PostalCodeItem::text() const
{
    return m_text;
}

void PostalCodeItem::setText( const QString& text )
{
    QFontMetrics metrics( s_font );
    setSize( metrics.size( 0, text ) + QSize( 10, 10 ) );
    m_text = text;
}

void PostalCodeItem::paint( GeoPainter *painter, ViewportParams *viewport,
                          const QString& renderPos, GeoSceneLayer * layer )
{
    Q_UNUSED( renderPos )
    Q_UNUSED( layer )
    Q_UNUSED( viewport )

    painter->save();

    const int fontAscent = QFontMetrics( s_font ).ascent();

    QPen outlinepen( Qt::white );
    outlinepen.setWidthF( s_labelOutlineWidth );
    QBrush  outlinebrush( Qt::black );

    const QPointF baseline( s_labelOutlineWidth / 2.0, fontAscent );

    QPainterPath outlinepath;
    outlinepath.addText( baseline, s_font, m_text );

    painter->setRenderHint( QPainter::Antialiasing, true );
    painter->setPen( outlinepen );
    painter->setBrush( outlinebrush );
    painter->drawPath( outlinepath );
    painter->setPen( Qt::NoPen );
    painter->drawPath( outlinepath );
    painter->setRenderHint( QPainter::Antialiasing, false );

    painter->restore();
}

#include "PostalCodeItem.moc"
<commit_msg>enable caching<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2011      Valery Kharitonov <kharvd@gmail.com>
//

// Self
#include "PostalCodeItem.h"

// Marble
#include "GeoPainter.h"
#include "ViewportParams.h"

// Qt
#include <QtGui/QFontMetrics>

using namespace Marble;

const QFont PostalCodeItem::s_font = QFont( "Sans Serif", 10, QFont::Bold );
const int PostalCodeItem::s_labelOutlineWidth = 5;

PostalCodeItem::PostalCodeItem( QObject *parent )
    : AbstractDataPluginItem( parent )
{
    setSize( QSize( 0, 0 ) );
    setCacheMode( ItemCoordinateCache );
}

PostalCodeItem::~PostalCodeItem()
{
}

QString PostalCodeItem::itemType() const
{
    return "postalCodeItem";
}

bool PostalCodeItem::initialized()
{
    return !m_text.isEmpty();
}

bool PostalCodeItem::operator<( const AbstractDataPluginItem *other ) const
{
    return this->id() < other->id();
}

QString PostalCodeItem::text() const
{
    return m_text;
}

void PostalCodeItem::setText( const QString& text )
{
    QFontMetrics metrics( s_font );
    setSize( metrics.size( 0, text ) + QSize( 10, 10 ) );
    m_text = text;
}

void PostalCodeItem::paint( GeoPainter *painter, ViewportParams *viewport,
                          const QString& renderPos, GeoSceneLayer * layer )
{
    Q_UNUSED( renderPos )
    Q_UNUSED( layer )
    Q_UNUSED( viewport )

    painter->save();

    const int fontAscent = QFontMetrics( s_font ).ascent();

    QPen outlinepen( Qt::white );
    outlinepen.setWidthF( s_labelOutlineWidth );
    QBrush  outlinebrush( Qt::black );

    const QPointF baseline( s_labelOutlineWidth / 2.0, fontAscent );

    QPainterPath outlinepath;
    outlinepath.addText( baseline, s_font, m_text );

    painter->setRenderHint( QPainter::Antialiasing, true );
    painter->setPen( outlinepen );
    painter->setBrush( outlinebrush );
    painter->drawPath( outlinepath );
    painter->setPen( Qt::NoPen );
    painter->drawPath( outlinepath );
    painter->setRenderHint( QPainter::Antialiasing, false );

    painter->restore();
}

#include "PostalCodeItem.moc"
<|endoftext|>


<commit_before>#include <errno.h>

#include <cstdint>

#include "caffe2/core/db.h"
#include "glog/logging.h"
#include "zmq.h"

namespace caffe2 {
namespace db {

typedef char ZmqCommand;
typedef int ZmqMessageSize;
const ZmqCommand kQueryMessageSize = 's';
const ZmqCommand kGet = 'g';

class ZmqDBCursor : public Cursor {
 public:
  explicit ZmqDBCursor(void* requester)
      : requester_(requester), buffer_(nullptr), received_size_(0),
        buffer_size_(0) {
    // Figure out the buffer size.
    CHECK_EQ(
        zmq_send(requester_, &kQueryMessageSize, sizeof(ZmqCommand), 0),
        sizeof(ZmqCommand))
        << "Incorrect zmq communication when querying message size.";
    CHECK_EQ(
        zmq_recv(requester_, &buffer_size_, sizeof(ZmqMessageSize), 0),
        sizeof(ZmqMessageSize))
        << "Incorrect zmq communication when fetching message size.";
    CHECK_GT(buffer_size_, 0) << "Incorrect buffer size obtained.";
    buffer_.reset(new char[buffer_size_]);
    // obtain the first value.
    Next();
  }

  ~ZmqDBCursor() {}
  void SeekToFirst() override { /* do nothing */ }
  void Next() override {
    CHECK_EQ(
        zmq_send(requester_, &kGet, sizeof(ZmqCommand), 0), sizeof(ZmqCommand))
        << "Incorrect zmq communication when sending request.";
    received_size_ = zmq_recv(requester_, buffer_.get(), buffer_size_, 0);
    CHECK_GT(received_size_, 0) << "Received no message.";
  }
  string key() override { return ""; }
  string value() override {
    return string(buffer_.get(), received_size_);
  }
  virtual bool Valid() { return true; }

 private:
  void* requester_;
  unique_ptr<char[]> buffer_;
  int received_size_;
  ZmqMessageSize buffer_size_;
};

class ZmqDB : public DB {
 public:
  ZmqDB(const string& source, Mode mode)
      : DB(source, mode), context_(zmq_ctx_new()),
        requester_(zmq_socket(context_, ZMQ_REQ)) {
    CHECK_EQ(mode, READ) << "ZeroMQ DB only supports read mode.";
    VLOG(1) << "Connecting to ZeroMQ server: " << source;
    int ret = zmq_connect(requester_, source.c_str());
    CHECK_EQ(ret, 0) << "Error in connecting to zmq server. "
                     << "Error is: " << errno;
    VLOG(1) << "Opened ZeroMQ server: " << source;
  }

  ~ZmqDB() { Close(); }

  void Close() override {
    if (!requester_) {
      zmq_close(requester_);
      requester_ = nullptr;
      zmq_ctx_destroy(context_);
      context_ = nullptr;
    }
  }

  Cursor* NewCursor() override {
    return new ZmqDBCursor(requester_);
  }
  Transaction* NewTransaction() override {
    // TODO(Yangqing): Do I really need to just do log fatal?
    LOG(FATAL) << "ZeroMQ DB does not support writing with a transaction.";
    return nullptr;  // dummy placeholder to suppress old compiler warnings.
  }

 private:
  void* context_;
  void* requester_;
};

REGISTER_CAFFE2_DB(ZmqDB, ZmqDB);
// For lazy-minded, one can also call with lower-case name.
REGISTER_CAFFE2_DB(zmqdb, ZmqDB);

}  // namespace db
}  // namespace caffe2
<commit_msg>zmqdb: make clear error message that zmq 3+ is required.<commit_after>#include <errno.h>

#include <cstdint>

#include "caffe2/core/db.h"
#include "glog/logging.h"
#include "zmq.h"

#if ZMQ_VERSION_MAJOR < 3
#error "ZmqDB requires ZMQ version 3 or above."
#endif

namespace caffe2 {
namespace db {

typedef char ZmqCommand;
typedef int ZmqMessageSize;
const ZmqCommand kQueryMessageSize = 's';
const ZmqCommand kGet = 'g';

class ZmqDBCursor : public Cursor {
 public:
  explicit ZmqDBCursor(void* requester)
      : requester_(requester), buffer_(nullptr), received_size_(0),
        buffer_size_(0) {
    // Figure out the buffer size.
    CHECK_EQ(
        zmq_send(requester_, &kQueryMessageSize, sizeof(ZmqCommand), 0),
        sizeof(ZmqCommand))
        << "Incorrect zmq communication when querying message size.";
    CHECK_EQ(
        zmq_recv(requester_, &buffer_size_, sizeof(ZmqMessageSize), 0),
        sizeof(ZmqMessageSize))
        << "Incorrect zmq communication when fetching message size.";
    CHECK_GT(buffer_size_, 0) << "Incorrect buffer size obtained.";
    buffer_.reset(new char[buffer_size_]);
    // obtain the first value.
    Next();
  }

  ~ZmqDBCursor() {}
  void SeekToFirst() override { /* do nothing */ }
  void Next() override {
    CHECK_EQ(
        zmq_send(requester_, &kGet, sizeof(ZmqCommand), 0), sizeof(ZmqCommand))
        << "Incorrect zmq communication when sending request.";
    received_size_ = zmq_recv(requester_, buffer_.get(), buffer_size_, 0);
    CHECK_GT(received_size_, 0) << "Received no message.";
  }
  string key() override { return ""; }
  string value() override {
    return string(buffer_.get(), received_size_);
  }
  virtual bool Valid() { return true; }

 private:
  void* requester_;
  unique_ptr<char[]> buffer_;
  int received_size_;
  ZmqMessageSize buffer_size_;
};

class ZmqDB : public DB {
 public:
  ZmqDB(const string& source, Mode mode)
      : DB(source, mode), context_(zmq_ctx_new()),
        requester_(zmq_socket(context_, ZMQ_REQ)) {
    CHECK_EQ(mode, READ) << "ZeroMQ DB only supports read mode.";
    VLOG(1) << "Connecting to ZeroMQ server: " << source;
    int ret = zmq_connect(requester_, source.c_str());
    CHECK_EQ(ret, 0) << "Error in connecting to zmq server. "
                     << "Error is: " << errno;
    VLOG(1) << "Opened ZeroMQ server: " << source;
  }

  ~ZmqDB() { Close(); }

  void Close() override {
    if (!requester_) {
      zmq_close(requester_);
      requester_ = nullptr;
      zmq_ctx_destroy(context_);
      context_ = nullptr;
    }
  }

  Cursor* NewCursor() override {
    return new ZmqDBCursor(requester_);
  }
  Transaction* NewTransaction() override {
    // TODO(Yangqing): Do I really need to just do log fatal?
    LOG(FATAL) << "ZeroMQ DB does not support writing with a transaction.";
    return nullptr;  // dummy placeholder to suppress old compiler warnings.
  }

 private:
  void* context_;
  void* requester_;
};

REGISTER_CAFFE2_DB(ZmqDB, ZmqDB);
// For lazy-minded, one can also call with lower-case name.
REGISTER_CAFFE2_DB(zmqdb, ZmqDB);

}  // namespace db
}  // namespace caffe2
<|endoftext|>


<commit_before>//===========================================
//  Lumina-DE source code
//  Copyright (c) 2014, Ken Moore
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
#ifdef __DragonFly__
#include "LuminaOS.h"
#include <unistd.h>

//can't read xbrightness settings - assume invalid until set
static int screenbrightness = -1;
static int audiovolume = -1;

QString LOS::OSName(){ return "DragonFly BSD"; }

//OS-specific prefix(s)
QString LOS::AppPrefix(){ return "/usr/local/"; } //Prefix for applications
QString LOS::SysPrefix(){ return "/usr/"; } //Prefix for system

//OS-specific application shortcuts (*.desktop files)
QString LOS::ControlPanelShortcut(){ return ""; } //system control panel
QString LOS::AppStoreShortcut(){ return ""; } //graphical app/pkg manager
QString LOS::QtConfigShortcut(){ return "/usr/local/bin/qtconfig-qt4"; } //qtconfig binary (NOT *.desktop file)

// ==== ExternalDevicePaths() ====
QStringList LOS::ExternalDevicePaths(){
    //Returns: QStringList[<type>::::<filesystem>::::<path>]
      //Note: <type> = [USB, HDRIVE, DVD, SDCARD, UNKNOWN]
  QStringList devs = LUtils::getCmdOutput("mount");
  //Now check the output
  for(int i=0; i<devs.length(); i++){
    if(devs[i].startsWith("/dev/")){
      QString type = devs[i].section(" on ",0,0);
	type.remove("/dev/");
      //Determine the type of hardware device based on the dev node
      if(type.startsWith("da")){ type = "USB"; }
      else if(type.startsWith("ada")){ type = "HDRIVE"; }
      else if(type.startsWith("mmsd")){ type = "SDCARD"; }
      else if(type.startsWith("cd")||type.startsWith("acd")){ type="DVD"; }
      else{ type = "UNKNOWN"; }
      //Now put the device in the proper output format
      devs[i] = type+"::::"+devs[i].section("(",1,1).section(",",0,0)+"::::"+devs[i].section(" on ",1,50).section("(",0,0).simplified();
    }else{
      //invalid device - remove it from the list
      devs.removeAt(i);
      i--;
    }
  }
  return devs;
}

//Read screen brightness information
int LOS::ScreenBrightness(){
  //Returns: Screen Brightness as a percentage (0-100, with -1 for errors)
  if(screenbrightness==-1){
    if(QFile::exists(QDir::homePath()+"/.lumina/.currentxbrightness")){
      int val = LUtils::readFile(QDir::homePath()+"/.lumina/.currentxbrightness").join("").simplified().toInt();
      screenbrightness = val;
    }
  }
  //If it gets to this point, then we have a valid (but new) installation
  if(screenbrightness<0){ screenbrightness = 100; } //default value for systems

  return screenbrightness;
}

//Set screen brightness
void LOS::setScreenBrightness(int percent){
  if(percent == -1){ return; } //This is usually an invalid value passed directly to the setter
  //ensure bounds
  if(percent<0){percent=0;}
  else if(percent>100){ percent=100; }
  //Run the command(s)
  bool success = false;
  float pf = percent/100.0; //convert to a decimel
  //Run the command
  QString cmd = "xbrightness  %1";
  cmd = cmd.arg( QString::number( int(65535*pf) ) );
  success = (0 == LUtils::runCmd(cmd) );
  //Save the result for later
  if(!success){ screenbrightness = -1; }
  else{ screenbrightness = percent; }
  LUtils::writeFile(QDir::homePath()+"/.lumina/.currentxbrightness", QStringList() << QString::number(screenbrightness), true);
}

//Read the current volume
int LOS::audioVolume(){ //Returns: audio volume as a percentage (0-100, with -1 for errors)
  int out = audiovolume;
  if(out < 0){
    //First time session check: Load the last setting for this user
    QString info = LUtils::readFile(QDir::homePath()+"/.lumina/.currentvolume").join("");
    if(!info.isEmpty()){
      out = info.simplified().toInt();
      audiovolume = out; //unset this internal flag
      return out;
    }
  }

  //probe the system for the current volume (other utils could be changing it)
  QString info = LUtils::getCmdOutput("mixer -S vol").join(":").simplified(); //ignores any other lines
  if(!info.isEmpty()){
    int L = info.section(":",1,1).toInt();
    int R = info.section(":",2,2).toInt();
    if(L>R){ out = L; }
    else{ out = R; }
    if(out != audiovolume){
      //Volume changed by other utility: adjust the saved value as well
      LUtils::writeFile(QDir::homePath()+"/.lumina/.currentvolume", QStringList() << QString::number(out), true);
    }
    audiovolume = out;
  }

  return out;
}

//Set the current volume
void LOS::setAudioVolume(int percent){
  if(percent<0){percent=0;}
  else if(percent>100){percent=100;}
  QString info = LUtils::getCmdOutput("mixer -S vol").join(":").simplified(); //ignores any other lines
  if(!info.isEmpty()){
    int L = info.section(":",1,1).toInt();
    int R = info.section(":",2,2).toInt();
    int diff = L-R;
    if((percent == L) && (L==R)){ return; } //already set to that volume
    if(diff<0){ R=percent; L=percent+diff; } //R Greater
    else{ L=percent; R=percent-diff; } //L Greater or equal
    //Check bounds
    if(L<0){L=0;}else if(L>100){L=100;}
    if(R<0){R=0;}else if(R>100){R=100;}
    //Run Command
    audiovolume = percent; //save for checking later
    LUtils::runCmd("mixer vol "+QString::number(L)+":"+QString::number(R));
    LUtils::writeFile(QDir::homePath()+"/.lumina/.currentvolume", QStringList() << QString::number(percent), true);
  }
}

//Change the current volume a set amount (+ or -)
void LOS::changeAudioVolume(int percentdiff){
  QString info = LUtils::getCmdOutput("mixer -S vol").join(":").simplified(); //ignores any other lines
  if(!info.isEmpty()){
    int L = info.section(":",1,1).toInt() + percentdiff;
    int R = info.section(":",2,2).toInt() + percentdiff;
    //Check bounds
    if(L<0){L=0;}else if(L>100){L=100;}
    if(R<0){R=0;}else if(R>100){R=100;}
    //Run Command
    LUtils::runCmd("mixer vol "+QString::number(L)+":"+QString::number(R));
  }
}

//Check if a graphical audio mixer is installed
bool LOS::hasMixerUtility(){
  return QFile::exists("/usr/local/bin/pc-mixer");
}

//Launch the graphical audio mixer utility
void LOS::startMixerUtility(){
  QProcess::startDetached("pc-mixer -notray");
}

//Check for user system permission (shutdown/restart)
bool LOS::userHasShutdownAccess(){
  return true; //not implemented yet
}

//System Shutdown
void LOS::systemShutdown(){ //start poweroff sequence
  QProcess::startDetached("shutdown -p now");
}

//System Restart
void LOS::systemRestart(){ //start reboot sequence
  QProcess::startDetached("shutdown -r now");
}

//Check for suspend support
bool LOS::systemCanSuspend(){
  return false;
}

//Put the system into the suspend state
void LOS::systemSuspend(){

}

//Battery Availability
bool LOS::hasBattery(){
  int val = LUtils::getCmdOutput("apm -l").join("").toInt();
  return (val >= 0 && val <= 100);
}

//Battery Charge Level
int LOS::batteryCharge(){ //Returns: percent charge (0-100), anything outside that range is counted as an error
  int charge = LUtils::getCmdOutput("apm -l").join("").toInt();
  if(charge > 100){ charge = -1; } //invalid charge
  return charge;
}

//Battery Charging State
bool LOS::batteryIsCharging(){
  return (LUtils::getCmdOutput("apm -a").join("").simplified() == "1");
}

//Battery Time Remaining
int LOS::batterySecondsLeft(){ //Returns: estimated number of seconds remaining
  return LUtils::getCmdOutput("apm -t").join("").toInt();
}

//File Checksums
QStringList LOS::Checksums(QStringList filepaths){ //Return: checksum of the input file
 return QStringList();
}

//file system capacity
QString LOS::FileSystemCapacity(QString dir) { //Return: percentage capacity as give by the df command
  QStringList mountInfo = LUtils::getCmdOutput("df \"" + dir+"\"");
  QString::SectionFlag skipEmpty = QString::SectionSkipEmpty;
  //we take the 5th word on the 2 line
  QString capacity = mountInfo[1].section(" ",4,4, skipEmpty);
  return capacity;
}

QStringList LOS::CPUTemperatures(){ //Returns: List containing the temperature of any CPU's ("50C" for example)
  return QStringList(); //not implemented yet
}

int LOS::CPUUsagePercent(){ //Returns: Overall percentage of the amount of CPU cycles in use (-1 for errors)
  return -1; //not implemented yet
}

int LOS::MemoryUsagePercent(){
  return -1; //not implemented yet
}

QStringList LOS::DiskUsage(){ //Returns: List of current read/write stats for each device
  return QStringList(); //not implemented yet
}
#endif
<commit_msg>DragonFly does not have graphical mixer<commit_after>//===========================================
//  Lumina-DE source code
//  Copyright (c) 2014, Ken Moore
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
#ifdef __DragonFly__
#include "LuminaOS.h"
#include <unistd.h>

//can't read xbrightness settings - assume invalid until set
static int screenbrightness = -1;
static int audiovolume = -1;

QString LOS::OSName(){ return "DragonFly BSD"; }

//OS-specific prefix(s)
QString LOS::AppPrefix(){ return "/usr/local/"; } //Prefix for applications
QString LOS::SysPrefix(){ return "/usr/"; } //Prefix for system

//OS-specific application shortcuts (*.desktop files)
QString LOS::ControlPanelShortcut(){ return ""; } //system control panel
QString LOS::AppStoreShortcut(){ return ""; } //graphical app/pkg manager
QString LOS::QtConfigShortcut(){ return "/usr/local/bin/qtconfig-qt4"; } //qtconfig binary (NOT *.desktop file)

// ==== ExternalDevicePaths() ====
QStringList LOS::ExternalDevicePaths(){
    //Returns: QStringList[<type>::::<filesystem>::::<path>]
      //Note: <type> = [USB, HDRIVE, DVD, SDCARD, UNKNOWN]
  QStringList devs = LUtils::getCmdOutput("mount");
  //Now check the output
  for(int i=0; i<devs.length(); i++){
    if(devs[i].startsWith("/dev/")){
      QString type = devs[i].section(" on ",0,0);
	type.remove("/dev/");
      //Determine the type of hardware device based on the dev node
      if(type.startsWith("da")){ type = "USB"; }
      else if(type.startsWith("ada")){ type = "HDRIVE"; }
      else if(type.startsWith("mmsd")){ type = "SDCARD"; }
      else if(type.startsWith("cd")||type.startsWith("acd")){ type="DVD"; }
      else{ type = "UNKNOWN"; }
      //Now put the device in the proper output format
      devs[i] = type+"::::"+devs[i].section("(",1,1).section(",",0,0)+"::::"+devs[i].section(" on ",1,50).section("(",0,0).simplified();
    }else{
      //invalid device - remove it from the list
      devs.removeAt(i);
      i--;
    }
  }
  return devs;
}

//Read screen brightness information
int LOS::ScreenBrightness(){
  //Returns: Screen Brightness as a percentage (0-100, with -1 for errors)
  if(screenbrightness==-1){
    if(QFile::exists(QDir::homePath()+"/.lumina/.currentxbrightness")){
      int val = LUtils::readFile(QDir::homePath()+"/.lumina/.currentxbrightness").join("").simplified().toInt();
      screenbrightness = val;
    }
  }
  //If it gets to this point, then we have a valid (but new) installation
  if(screenbrightness<0){ screenbrightness = 100; } //default value for systems

  return screenbrightness;
}

//Set screen brightness
void LOS::setScreenBrightness(int percent){
  if(percent == -1){ return; } //This is usually an invalid value passed directly to the setter
  //ensure bounds
  if(percent<0){percent=0;}
  else if(percent>100){ percent=100; }
  //Run the command(s)
  bool success = false;
  float pf = percent/100.0; //convert to a decimel
  //Run the command
  QString cmd = "xbrightness  %1";
  cmd = cmd.arg( QString::number( int(65535*pf) ) );
  success = (0 == LUtils::runCmd(cmd) );
  //Save the result for later
  if(!success){ screenbrightness = -1; }
  else{ screenbrightness = percent; }
  LUtils::writeFile(QDir::homePath()+"/.lumina/.currentxbrightness", QStringList() << QString::number(screenbrightness), true);
}

//Read the current volume
int LOS::audioVolume(){ //Returns: audio volume as a percentage (0-100, with -1 for errors)
  int out = audiovolume;
  if(out < 0){
    //First time session check: Load the last setting for this user
    QString info = LUtils::readFile(QDir::homePath()+"/.lumina/.currentvolume").join("");
    if(!info.isEmpty()){
      out = info.simplified().toInt();
      audiovolume = out; //unset this internal flag
      return out;
    }
  }

  //probe the system for the current volume (other utils could be changing it)
  QString info = LUtils::getCmdOutput("mixer -S vol").join(":").simplified(); //ignores any other lines
  if(!info.isEmpty()){
    int L = info.section(":",1,1).toInt();
    int R = info.section(":",2,2).toInt();
    if(L>R){ out = L; }
    else{ out = R; }
    if(out != audiovolume){
      //Volume changed by other utility: adjust the saved value as well
      LUtils::writeFile(QDir::homePath()+"/.lumina/.currentvolume", QStringList() << QString::number(out), true);
    }
    audiovolume = out;
  }

  return out;
}

//Set the current volume
void LOS::setAudioVolume(int percent){
  if(percent<0){percent=0;}
  else if(percent>100){percent=100;}
  QString info = LUtils::getCmdOutput("mixer -S vol").join(":").simplified(); //ignores any other lines
  if(!info.isEmpty()){
    int L = info.section(":",1,1).toInt();
    int R = info.section(":",2,2).toInt();
    int diff = L-R;
    if((percent == L) && (L==R)){ return; } //already set to that volume
    if(diff<0){ R=percent; L=percent+diff; } //R Greater
    else{ L=percent; R=percent-diff; } //L Greater or equal
    //Check bounds
    if(L<0){L=0;}else if(L>100){L=100;}
    if(R<0){R=0;}else if(R>100){R=100;}
    //Run Command
    audiovolume = percent; //save for checking later
    LUtils::runCmd("mixer vol "+QString::number(L)+":"+QString::number(R));
    LUtils::writeFile(QDir::homePath()+"/.lumina/.currentvolume", QStringList() << QString::number(percent), true);
  }
}

//Change the current volume a set amount (+ or -)
void LOS::changeAudioVolume(int percentdiff){
  QString info = LUtils::getCmdOutput("mixer -S vol").join(":").simplified(); //ignores any other lines
  if(!info.isEmpty()){
    int L = info.section(":",1,1).toInt() + percentdiff;
    int R = info.section(":",2,2).toInt() + percentdiff;
    //Check bounds
    if(L<0){L=0;}else if(L>100){L=100;}
    if(R<0){R=0;}else if(R>100){R=100;}
    //Run Command
    LUtils::runCmd("mixer vol "+QString::number(L)+":"+QString::number(R));
  }
}

//Check if a graphical audio mixer is installed
bool LOS::hasMixerUtility(){
  return false; //not implemented yet for DragonFly
}

//Launch the graphical audio mixer utility
void LOS::startMixerUtility(){
  //Not implemented yet for DragonFly
}

//Check for user system permission (shutdown/restart)
bool LOS::userHasShutdownAccess(){
  return true; //not implemented yet
}

//System Shutdown
void LOS::systemShutdown(){ //start poweroff sequence
  QProcess::startDetached("shutdown -p now");
}

//System Restart
void LOS::systemRestart(){ //start reboot sequence
  QProcess::startDetached("shutdown -r now");
}

//Check for suspend support
bool LOS::systemCanSuspend(){
  return false;
}

//Put the system into the suspend state
void LOS::systemSuspend(){

}

//Battery Availability
bool LOS::hasBattery(){
  int val = LUtils::getCmdOutput("apm -l").join("").toInt();
  return (val >= 0 && val <= 100);
}

//Battery Charge Level
int LOS::batteryCharge(){ //Returns: percent charge (0-100), anything outside that range is counted as an error
  int charge = LUtils::getCmdOutput("apm -l").join("").toInt();
  if(charge > 100){ charge = -1; } //invalid charge
  return charge;
}

//Battery Charging State
bool LOS::batteryIsCharging(){
  return (LUtils::getCmdOutput("apm -a").join("").simplified() == "1");
}

//Battery Time Remaining
int LOS::batterySecondsLeft(){ //Returns: estimated number of seconds remaining
  return LUtils::getCmdOutput("apm -t").join("").toInt();
}

//File Checksums
QStringList LOS::Checksums(QStringList filepaths){ //Return: checksum of the input file
 return QStringList();
}

//file system capacity
QString LOS::FileSystemCapacity(QString dir) { //Return: percentage capacity as give by the df command
  QStringList mountInfo = LUtils::getCmdOutput("df \"" + dir+"\"");
  QString::SectionFlag skipEmpty = QString::SectionSkipEmpty;
  //we take the 5th word on the 2 line
  QString capacity = mountInfo[1].section(" ",4,4, skipEmpty);
  return capacity;
}

QStringList LOS::CPUTemperatures(){ //Returns: List containing the temperature of any CPU's ("50C" for example)
  return QStringList(); //not implemented yet
}

int LOS::CPUUsagePercent(){ //Returns: Overall percentage of the amount of CPU cycles in use (-1 for errors)
  return -1; //not implemented yet
}

int LOS::MemoryUsagePercent(){
  return -1; //not implemented yet
}

QStringList LOS::DiskUsage(){ //Returns: List of current read/write stats for each device
  return QStringList(); //not implemented yet
}
#endif
<|endoftext|>


<commit_before>/*
 *
 */

// #include <fcntl.h>
// #include <linux/types.h>
// #include <linux/spi/spidev.h>
// #include <sys/ioctl.h>
// #include <unistd.h>

#include <thread>

#include "unix/log.hpp"
#include "mcu/constant.h"

#include "device.hpp"
#include "mcu-decode.hpp"
#include "mcu-encode.hpp"
#include "serial-id.hpp"

namespace led_d
{

  char_t device_t::write_buffer[buffer_size];
  char_t device_t::read_buffer[buffer_size];

  namespace {

    auto block_delay = std::chrono::milliseconds (1);
    //auto empty_delay = std::chrono::milliseconds (30);

    // fixme: !!!
    // auto device_delay = 5;
    // auto device_mode = 0;
    // auto device_bits = 8;
    // auto device_speed = 1000;

  } // namespace anonymous

  device_t::device_t (const std::string &/*path*/, mcu_queue_t &to_queue,
                      mcu_queue_t &from_queue, bool show_msg)
    : //m_path (path),
      //m_device (0),
      m_go (true),
      m_to_queue (to_queue),
      m_from_queue (from_queue),
      m_show_msg (show_msg)
  {
  }

  device_t::~device_t ()
  {
    m_bitbang.stop ();

    m_gpio.stop ();
  }

  void device_t::start ()
  {
    // gpio is first, we need to enable level shifter
    m_gpio.start ();

    // open unix device
    m_bitbang.start (m_gpio.get_chip ());

    m_to_queue.push
      (mcu::encode::join (serial::get (), MSG_ID_VERSION, PROTOCOL_VERSION));

    while (m_go == true) {
      if (((m_block.is_engaged () == true)
           && (m_gpio.is_irq_raised () == false))
          || (m_to_queue.empty () == true)) {
        std::this_thread::sleep_for (block_delay);
        continue;
      }
      if (m_gpio.is_irq_raised () == true) {
        // we are interested in gpio-irq only if 'to_queue' is empty
        write_msg (mcu::encode::join (SERIAL_ID_TO_IGNORE, MSG_ID_QUERY));
        continue;
      }
      auto msg = m_to_queue.pop ();
      if (msg)
        write_msg (*msg);
    }
  }

  void device_t::stop ()
  {
    m_go = false;

    m_bitbang.stop ();

    // fixme: smth else ???
  }

  void device_t::write_msg (const mcu_msg_t &msg_src)
  {
    char_t serial_id = mcu::decode::get_serial (msg_src);

    //
    // eye-catch | size | serial | msg-id | xxx
    //
    mcu_msg_t msg = msg_src;
    mcu::encode::wrap (msg);

    if (serial_id != SERIAL_ID_TO_IGNORE)
      m_block.engage (serial_id);

    mcu_msg_t in_msg;
    m_bitbang.transfer (msg, in_msg);

    if (m_show_msg == true) {
      log_t::buffer_t buf;
      if (serial_id != SERIAL_ID_TO_IGNORE) {
        buf << "serial out: " << (int) serial_id;
        log_t::info (buf);
      }
      log_t::clear (buf);
      buf << "out: ";
      for (auto &num : msg)
        buf << (int) num << " ";
      log_t::info (buf);
      log_t::clear (buf);
      buf << "in: ";
      for (auto &num : in_msg)
        buf << (int) num << " ";
      log_t::info (buf);
    }

    msg.clear ();
    for (auto &number : in_msg)
      if (m_parse.push (number, msg) == true) {
        char_t serial = 0;
        char_t msg_id = MSG_ID_EMPTY;
        if (mcu::decode::split (msg, serial, msg_id) == true) {
          m_block.relax (serial);
          if ((m_show_msg == true)
              && (serial != SERIAL_ID_TO_IGNORE)) {
            log_t::buffer_t buf;
            buf << "serial in: " << (int) serial;
            log_t::info (buf);
          }
          if (msg_id != MSG_ID_STATUS)
            // special handling is needed, otherwise just drop msg
            m_from_queue.push (msg);
        } else {
          log_t::buffer_t buf;
          buf << "spi: Failed to decode mcu message";
          log_t::error (buf);
        }
      }
  }

  // void device_t::device_write (uint32_t msg_size)
  // {
  //   spi_ioc_transfer buf;
  //   buf.tx_buf =  (unsigned long) write_buffer;
  //   buf.rx_buf =  (unsigned long) read_buffer;
  //   buf.len = msg_size;
  //   buf.delay_usecs = spi_delay;
  //   buf.speed_hz = 0;
  //   buf.bits_per_word = 0;
  //
  //   if (ioctl (m_device, SPI_IOC_MESSAGE (1), &buf) < 0) {
  //     log_t::buffer_t buf;
  //     buf << "spi: Failed to send spi message to mcu";
  //     log_t::error (buf);
  //   }
  // }
  //
  // void spi_t::device_stop ()
  // {
  //   if (m_device > 0) {
  //     close (m_device);
  //     m_device = 0;
  //   }
  // }
  //
  // void spi_t::device_start ()
  // {
  //   m_device = open (m_path.c_str (), O_RDWR);
  //   if (m_device < 0)
  //     throw std::runtime_error ("Failed to open spi device");
  //   if (ioctl (m_device, SPI_IOC_WR_MODE, &spi_mode) < 0)
  //     throw std::runtime_error ("Failed to set spi write mode");
  //   if (ioctl (m_device, SPI_IOC_RD_MODE, &spi_mode) < 0)
  //     throw std::runtime_error ("Failed to set spi read mode");
  //   if (ioctl (m_device, SPI_IOC_WR_BITS_PER_WORD, &spi_bits) < 0)
  //     throw std::runtime_error ("Failed to set spi write bits");
  //   if (ioctl (m_device, SPI_IOC_RD_BITS_PER_WORD, &spi_bits) < 0)
  //     throw std::runtime_error ("Failed to set spi read bits");
  //   if (ioctl (m_device, SPI_IOC_WR_MAX_SPEED_HZ, &spi_speed) < 0)
  //     throw std::runtime_error ("Failed to set spi write speed");
  //   if (ioctl (m_device, SPI_IOC_RD_MAX_SPEED_HZ, &spi_speed) < 0)
  //     throw std::runtime_error ("Failed to set spi read speed");
  // }

} // namespace led_d
<commit_msg>pi: Return prev code in device.cpp loop<commit_after>/*
 *
 */

// #include <fcntl.h>
// #include <linux/types.h>
// #include <linux/spi/spidev.h>
// #include <sys/ioctl.h>
// #include <unistd.h>

#include <thread>

#include "unix/log.hpp"
#include "mcu/constant.h"

#include "device.hpp"
#include "mcu-decode.hpp"
#include "mcu-encode.hpp"
#include "serial-id.hpp"

namespace led_d
{

  char_t device_t::write_buffer[buffer_size];
  char_t device_t::read_buffer[buffer_size];

  namespace {

    auto block_delay = std::chrono::milliseconds (1);
    //auto empty_delay = std::chrono::milliseconds (30);

    // fixme: !!!
    // auto device_delay = 5;
    // auto device_mode = 0;
    // auto device_bits = 8;
    // auto device_speed = 1000;

  } // namespace anonymous

  device_t::device_t (const std::string &/*path*/, mcu_queue_t &to_queue,
                      mcu_queue_t &from_queue, bool show_msg)
    : //m_path (path),
      //m_device (0),
      m_go (true),
      m_to_queue (to_queue),
      m_from_queue (from_queue),
      m_show_msg (show_msg)
  {
  }

  device_t::~device_t ()
  {
    m_bitbang.stop ();

    m_gpio.stop ();
  }

  void device_t::start ()
  {
    // gpio is first, we need to enable level shifter
    m_gpio.start ();

    // open unix device
    m_bitbang.start (m_gpio.get_chip ());

    m_to_queue.push
      (mcu::encode::join (serial::get (), MSG_ID_VERSION, PROTOCOL_VERSION));

    // fixme:
    // It is better to avoid using delay here,
    // but unclear how to do it
    while (m_go == true) {
      if ((m_block.is_engaged () == true)
          && (m_gpio.is_irq_raised () == false)) {
        std::this_thread::sleep_for (block_delay);
        continue;
      }
      if (m_gpio.is_irq_raised () == true) {
        // we are interested in gpio-irq only if 'to_queue' is empty
        write_msg (mcu::encode::join (SERIAL_ID_TO_IGNORE, MSG_ID_QUERY));
        continue;
      }
      auto msg = m_to_queue.pop ();
      if (msg)
        write_msg (*msg);
    }
  }

  void device_t::stop ()
  {
    m_go = false;

    m_bitbang.stop ();

    // fixme: smth else ???
  }

  void device_t::write_msg (const mcu_msg_t &msg_src)
  {
    char_t serial_id = mcu::decode::get_serial (msg_src);

    //
    // eye-catch | size | serial | msg-id | xxx
    //
    mcu_msg_t msg = msg_src;
    mcu::encode::wrap (msg);

    if (serial_id != SERIAL_ID_TO_IGNORE)
      m_block.engage (serial_id);

    mcu_msg_t in_msg;
    m_bitbang.transfer (msg, in_msg);

    if (m_show_msg == true) {
      log_t::buffer_t buf;
      if (serial_id != SERIAL_ID_TO_IGNORE) {
        buf << "serial out: " << (int) serial_id;
        log_t::info (buf);
      }
      log_t::clear (buf);
      buf << "out: ";
      for (auto &num : msg)
        buf << (int) num << " ";
      log_t::info (buf);
      log_t::clear (buf);
      buf << "in: ";
      for (auto &num : in_msg)
        buf << (int) num << " ";
      log_t::info (buf);
    }

    msg.clear ();
    for (auto &number : in_msg)
      if (m_parse.push (number, msg) == true) {
        char_t serial = 0;
        char_t msg_id = MSG_ID_EMPTY;
        if (mcu::decode::split (msg, serial, msg_id) == true) {
          m_block.relax (serial);
          if ((m_show_msg == true)
              && (serial != SERIAL_ID_TO_IGNORE)) {
            log_t::buffer_t buf;
            buf << "serial in: " << (int) serial;
            log_t::info (buf);
          }
          if (msg_id != MSG_ID_STATUS)
            // special handling is needed, otherwise just drop msg
            m_from_queue.push (msg);
        } else {
          log_t::buffer_t buf;
          buf << "spi: Failed to decode mcu message";
          log_t::error (buf);
        }
      }
  }

  // void device_t::device_write (uint32_t msg_size)
  // {
  //   spi_ioc_transfer buf;
  //   buf.tx_buf =  (unsigned long) write_buffer;
  //   buf.rx_buf =  (unsigned long) read_buffer;
  //   buf.len = msg_size;
  //   buf.delay_usecs = spi_delay;
  //   buf.speed_hz = 0;
  //   buf.bits_per_word = 0;
  //
  //   if (ioctl (m_device, SPI_IOC_MESSAGE (1), &buf) < 0) {
  //     log_t::buffer_t buf;
  //     buf << "spi: Failed to send spi message to mcu";
  //     log_t::error (buf);
  //   }
  // }
  //
  // void spi_t::device_stop ()
  // {
  //   if (m_device > 0) {
  //     close (m_device);
  //     m_device = 0;
  //   }
  // }
  //
  // void spi_t::device_start ()
  // {
  //   m_device = open (m_path.c_str (), O_RDWR);
  //   if (m_device < 0)
  //     throw std::runtime_error ("Failed to open spi device");
  //   if (ioctl (m_device, SPI_IOC_WR_MODE, &spi_mode) < 0)
  //     throw std::runtime_error ("Failed to set spi write mode");
  //   if (ioctl (m_device, SPI_IOC_RD_MODE, &spi_mode) < 0)
  //     throw std::runtime_error ("Failed to set spi read mode");
  //   if (ioctl (m_device, SPI_IOC_WR_BITS_PER_WORD, &spi_bits) < 0)
  //     throw std::runtime_error ("Failed to set spi write bits");
  //   if (ioctl (m_device, SPI_IOC_RD_BITS_PER_WORD, &spi_bits) < 0)
  //     throw std::runtime_error ("Failed to set spi read bits");
  //   if (ioctl (m_device, SPI_IOC_WR_MAX_SPEED_HZ, &spi_speed) < 0)
  //     throw std::runtime_error ("Failed to set spi write speed");
  //   if (ioctl (m_device, SPI_IOC_RD_MAX_SPEED_HZ, &spi_speed) < 0)
  //     throw std::runtime_error ("Failed to set spi read speed");
  // }

} // namespace led_d
<|endoftext|>