Exemplo n.º 1
0
void from_json(const json& j, ToolConfig& a) {
    std::vector<std::string>& files = a.getSourceFiles();
    try {
        files = j.at("source_files").get<std::vector<std::string>>();
    } catch (...) {
        files = {};
    }

    try {
        a.setExecutable(j.at("executable"));
    } catch (...) {
        a.setExecutable("");
    }

    try {
        a.setToolID(j.at("tool_id"));
    } catch (...) {
        a.setToolID("None");
    }

    try {
        a.setVersion(j.at("version"));
    } catch (...) {
        a.setVersion(newVersion);
    }

    std::vector<ToolAction>& actions = a.getActions();
    try {
        actions = j.at("actions").get<std::vector<ToolAction>>();
    } catch (...) {
        actions = {};
    }
}
Exemplo n.º 2
0
fostlib::headers_base::content::content(
    const json &values, const string &root
) {
    try {
        if ( values.isobject() ) {
            for ( json::const_iterator item(values.begin()); item != values.end(); ++item ) {
                const auto key = coerce<string>(item.key());
                const auto itemstr = coerce<string>(*item);
                if ( key == root ) {
                    value(itemstr);
                } else {
                    m_subvalues[key] = itemstr;
                }
            }
        } else if ( values.isatom() ) {
            value(coerce<string>(values));
        } else {
            throw exceptions::not_implemented(__func__,
                "Can't set header values from this JSON", values);
        }
    } catch ( exceptions::exception &e ) {
        insert(e.data(), "headers_base", "content", "values", values);
        insert(e.data(), "headers_base", "content", "root", root);
        throw;
    }
}
Exemplo n.º 3
0
void read_message(int clientID, string message){
    
    // Deserialize message from the string
    json msg = json::parse(message);
    
    if (msg["MESSAGE_TYPE"] == "CLIENT_UPDATE") {
        
        // Send a time stamp reply for client-side latency estimation
        json tStamps;
		tStamps["MESSAGE_TYPE"] = "TIME_STAMP_REPLY";
        tStamps["T2"] = chrono::system_clock::now().time_since_epoch() / chrono::milliseconds(1); // Time received
        tStamps["T1"] = msg["TIME_STAMP"]; // Origination time
        send_message(clientID, tStamps);
        
        // Now, process the client update:
        // Scenario A: We don't have a game ready yet. This is a pre-game message.
        if (game_p == NULL) {
            
            // Step 1: Put the message in the correct bin.
            pregame_player_msgs[clientID] = msg;
            
            // Step 2: If both bins are filled (2 players ready),
            // then start a new game.
            if (pregame_player_msgs.size() == 2) {
                game_p = new SnakeGame(pregame_player_msgs[0], pregame_player_msgs[1]);
                pregame_player_msgs.clear();
            }
        }
        
        // Scenario B: A game already exists. Just forward the message to it.
        else {
            game_p->handleClientInput(msg);
        }
    }
}
Exemplo n.º 4
0
 json merge(const json &a, const json &b) {
     json result = a.flatten();
     json tmp = b.flatten();
     for ( auto it = tmp.begin(); it != tmp.end(); ++it )
         result[it.key()] = it.value();
     return result.unflatten();
 }
Exemplo n.º 5
0
int upload_file(const char * from, const char * id, const char * to, char * new_id, size_t id_sz, CheckSum & md5) {
  fprintf(rlog, "uploading %s%s -> %s\n", id ? "id: " : "", id ? id : from, to);

  auto src = fopen(from, "r");

  if (!src) {
    fprintf(rlog, "ERROR: could not open \"%s\" for reading\n", from);
    return -1;
  }

  char url[1024];
  snprintf(url, 1024, "upload/drive/v3/files%s%s?uploadType=resumable&fields=name,id,size,md5Checksum",
	   id ? "/" : "", id ? id : "");

  DriveApi upload{id ? PATCH : POST, url};
  upload.headers.push_back("X-Upload-Content-Type: application/octet-stream");

  struct stat st = {};
  stat(from, &st);

  if (!id)
    upload.params.AddMember("parents", Value().SetArray().PushBack(StringRef(root_id), upload.params.doc.GetAllocator()));
  if (to)
    upload.params.AddMember("name", StringRef(to));
  char date[32];
  strftime(date, 32, "%Y-%m-%dT%TZ", gmtime(&st.st_mtime));
  upload.params.AddMember("modifiedTime", StringRef(date));

  upload.include_headers = true;

  auto resp = upload.perform();
  if (report_error("upload step 1", resp) != 0) {
    fclose(src);
    return -1;
  }

  //printf("Success\n");
  //printf("%s\n", resp.str.c_str());

  auto location = get_http_header("Location", resp.str.c_str());

  DriveApi put{PUT, location.c_str()};
  put.headers.push_back("Content-Type: application/octet-stream");
  put.body_fh = src;
  resp = put.perform();
  fclose(src);
  HANDLE_ERROR("upload step 2", resp);

  md5 = resp.data["md5Checksum"].GetString();
  
  //printf("Upload Success\n");
  //printf("%s\n", resp.str.c_str());
  
  ///return {resp.data["id"].asString(), atoi(resp.data["size"].asCString()), resp.data["md5Checksum"].asString()};

  if (new_id)
    strncpy(new_id, resp.data["id"].GetString(), id_sz);
 
  return 0;
}
Exemplo n.º 6
0
 void from_json(const json &j, AtomData &a) {
     if (j.is_object()==false || j.size()!=1)
         throw std::runtime_error("Invalid JSON data for AtomData");
     for (auto it : j.items()) {
         a.name = it.key();
         auto& val = it.value();
         a.activity = val.value("activity", a.activity) * 1.0_molar;
         a.alphax   = val.value("alphax", a.alphax);
         a.charge   = val.value("q", a.charge);
         a.dp       = val.value("dp", a.dp) * 1.0_angstrom;
         a.dprot    = val.value("dprot", a.dprot) * 1.0_rad;
         a.eps      = val.value("eps", a.eps) * 1.0_kJmol;
         a.id()     = val.value("id", a.id());
         a.mu       = val.value("mu", a.mu);
         a.mulen    = val.value("mulen", a.mulen);
         a.scdir    = val.value("scdir", a.scdir);
         a.sclen    = val.value("sclen", a.sclen);
         a.mw       = val.value("mw", a.mw);
         a.sigma    = val.value("sigma", 0.0) * 1.0_angstrom;
         if (fabs(a.sigma)<1e-20)
             a.sigma = 2.0*val.value("r", 0.0) * 1.0_angstrom;
         a.tension  = val.value("tension", a.tension) * 1.0_kJmol / (1.0_angstrom*1.0_angstrom);
         a.tfe      = val.value("tfe", a.tfe) * 1.0_kJmol / (1.0_angstrom*1.0_angstrom*1.0_molar);
         a.hydrophobic = val.value("hydrophobic", false);
     }
 }
Exemplo n.º 7
0
void Colour::fromJSON(json& jvalue)
{
  //Will accept integer colour or [r,g,b,a] array or 
  // string containing x11 name or hex #rrggbb or html rgba(r,g,b,a) 
  if (jvalue.is_number())
  {
    value = jvalue;
  }
  else if (jvalue.is_array())
  {
    float R = jvalue[0];
    float G = jvalue[1];
    float B = jvalue[2];
    float A = 1.0;
    if (jvalue.size() > 3) A = jvalue[3];
    if (R <= 1.0 && G <= 1.0 && B <= 1.0 && A <= 1.0)
    {
      r = R*255.0;
      g = G*255.0;
      b = B*255.0;
      a = A*255.0;
    }
    else
    {
      r = R;
      g = G;
      b = B;
    }
  }
  else if (jvalue.is_string())
  {
    fromString(jvalue);
  }
  //std::cout << "COLOUR: " << std::setw(2) << jvalue << " ==> " << *this << std::endl;
}
Exemplo n.º 8
0
void LogEntryRootFilter::parseJson(const json &j) {
    auto filterType_json = j.find("filterType");
    if (filterType_json != j.end()) {
        filterType = (FilterType) filterType_json->get<int>();
    } else {
        filterType = filterIn;
    }
}
Exemplo n.º 9
0
	void JsonUtil::ensureType(const string& aFieldName, const json& aNew, const json& aExisting) {
		if (aExisting.is_number()) {
			if (!aNew.is_number()) {
				throwError(aFieldName, ERROR_INVALID, "The new value must be a number");
			}
		} else if (aNew.type() != aExisting.type()) {
			throwError(aFieldName, ERROR_INVALID, "Type of the new value doesn't match with the existing type");
		}
	}
Exemplo n.º 10
0
QM_NAMESPACE

boost::python::dict to_dict(json const& self)  {
	boost::python::dict d;
	for(json::const_iterator it=self.begin();it!=self.end();++it)  {
		d[it->first] = it->second;
	}
	return d;
}
Exemplo n.º 11
0
std::shared_ptr<dariadb::MeasArray>
read_meas_array(const dariadb::scheme::IScheme_Ptr &scheme, const json &js) {
  auto result = std::make_shared<dariadb::MeasArray>();
  auto js_iter = js.find("append_values");
  if (js_iter == js.end()) {
    dariadb::logger_fatal("append_values not found");
    return nullptr;
  }

  auto values = *js_iter;
  for (auto it = values.begin(); it != values.end(); ++it) {
    dariadb::MeasArray sub_result;
    auto id_str = it.key();
    auto val4id = it.value();

    dariadb::Id id = scheme->addParam(id_str);

    auto flag_js = val4id["F"];
    auto val_js = val4id["V"];
    auto time_js = val4id["T"];

    if (flag_js.size() != val_js.size() || time_js.size() != val_js.size()) {
      THROW_EXCEPTION("bad query format, flags:", flag_js.size(),
                      " values:", val_js.size(), " times:", time_js.size(),
                      " query: ", js.dump(1));
    }

    sub_result.resize(flag_js.size());
    size_t pos = 0;
    for (auto f_it = flag_js.begin(); f_it != flag_js.end(); ++f_it) {
      dariadb::Flag f = *f_it;
      sub_result[pos++].flag = f;
    }

    pos = 0;
    for (auto v_it = val_js.begin(); v_it != val_js.end(); ++v_it) {
      dariadb::Value v = *v_it;
      sub_result[pos++].value = v;
    }

    pos = 0;
    for (auto t_it = time_js.begin(); t_it != time_js.end(); ++t_it) {
      dariadb::Time t = *t_it;
      sub_result[pos++].time = t;
    }

    dariadb::logger("in query ", sub_result.size(), " values for id:", id);
    for (auto v : sub_result) {
      v.id = id;
      result->push_back(v);
    }
  }
  return result;
}
Exemplo n.º 12
0
RenderableSpriteBlueprint::RenderableSpriteBlueprint(json& j) {
    if (j.count("diffuse")) {
        _diffuse = j["diffuse"].get<std::string>();
    }
    if (j.count("normal")) {
        _normal = j["normal"].get<std::string>();
    }
    if (j.count("lit")) {
        _lit = j["lit"].get<bool>();
    }
}
Exemplo n.º 13
0
	json JsonUtil::filterExactValues(const json& aNew, const json& aCompareTo) noexcept {
		json ret = aNew;
		for (const auto& v: json::iterator_wrapper(aCompareTo)) {
			auto key = v.key();
			auto i = aNew.find(key);
			if (i != aNew.end() && aNew.at(key) == aCompareTo.at(key)) {
				ret.erase(key);
			}
		}

		return ret;
	}
Exemplo n.º 14
0
	optional<int> FavoriteHubUtils::deserializeIntHubSetting(const string& aFieldName, const json& aJson) {
		auto p = aJson.find(aFieldName);
		if (p == aJson.end()) {
			return boost::none;
		}

		if ((*p).is_null()) {
			return HUB_SETTING_DEFAULT_INT;
		}

		return JsonUtil::parseValue<int>(aFieldName, *p);
	}
Exemplo n.º 15
0
bool RPCMethod::ValidateArguments(json j) {
  if (j.size() != this->paramTypes->size()) {
    return false;
  }

  for (unsigned int c = 0; c < this->paramTypes->size(); c++) {
    if (!this->checkType(this->paramTypes->at(c), j.at(c))) {
      return false;
    }
  }
  return true;
}
Exemplo n.º 16
0
RenderableBackgroundBlueprint::RenderableBackgroundBlueprint(json& j) {
    if (j.count("diffuse")) {
        _diffuse = j["diffuse"].get<std::string>();
    }
    if (j.count("normal")) {
        _normal = j["normal"].get<std::string>();
    }
    if (j.count("scale")) {
        _scale = j["scale"].get<float>();
    } else {
        _scale = 1;
    }
}
Exemplo n.º 17
0
LightBlueprint::LightBlueprint(json& j) {
    _type = j["type"];

    if (j.count("x")) _x = j["x"].get<float>();
    if (j.count("y")) _y = j["y"].get<float>();
    if (j.count("z")) _z = j["z"].get<float>();
    if (j.count("drop")) _drop = j["drop"].get<float>();
    if (j.count("end")) _end = j["end"].get<float>();
    if (j.count("depth")) _depth = j["depth"].get<float>();
    if (j.count("color")) {
        _color = Color(j["color"][0], j["color"][1], j["color"][2]);
    }
}
Exemplo n.º 18
0
 void Movebase::from_json(const json &j) {
     auto it = j.find("repeat");
     if (it!=j.end()) {
         if (it->is_number())
             repeat = it->get<double>();
         else
         if (it->is_string())
             if (it->get<std::string>()=="N")
                 repeat = -1;
     }
     _from_json(j);
     if (repeat<0)
         repeat=0;
 }
Exemplo n.º 19
0
bool RPCMethod::checkType(ParamType type, json j) {
  switch (type) {
  case ParamType::Bool:
    return j.is_boolean();
  case ParamType::Int:
    return j.is_number_integer();
  case ParamType::Float:
    return j.is_number();
  case ParamType::String:
    return j.is_string();
  case ParamType::JSON:
    return true;  
  }
}
Exemplo n.º 20
0
 double value_inf(const json &j, const std::string &key) {
     auto it = j.find(key);
     if (it==j.end())
         throw std::runtime_error("unknown json key '" + key + "'");
     else
         if (it->is_string()) {
             if (*it=="inf")
                 return std::numeric_limits<double>::infinity();
             if (*it=="-inf")
                 return -std::numeric_limits<double>::infinity();
             throw std::runtime_error("value must be number or 'inf'");
         }
     return double(*it);
 }
Exemplo n.º 21
0
static void GenStat(Stat& stat, const json& v) {
    switch (v.type()) {
    case value_types::array_t:
        for (json::const_array_iterator itr = v.begin_elements(); itr != v.end_elements(); ++itr)
            GenStat(stat, *itr);
        stat.arrayCount++;
        stat.elementCount += v.size();
        break;

    case value_types::empty_object_t:
    case value_types::object_t:
        for (json::const_object_iterator itr = v.begin_members(); itr != v.end_members(); ++itr) {
            GenStat(stat, itr->value());
            stat.stringLength += itr->name().size();
        }
        stat.objectCount++;
        stat.memberCount += v.size();
        stat.stringCount += v.size();
        break;

    case value_types::string_t: 
        stat.stringCount++;
        stat.stringLength += v.as_string().size();
        break;

    case value_types::small_string_t:
        stat.stringCount++;
        stat.stringLength += v.as_string().size();
        break;

    case value_types::double_t:
    case value_types::integer_t:
    case value_types::uinteger_t:
        stat.numberCount++;
        break;

    case value_types::bool_t:
        if (v.as_bool())
            stat.trueCount++;
        else
            stat.falseCount++;
        break;

    case value_types::null_t:
        stat.nullCount++;
        break;
    }
}
Exemplo n.º 22
0
linear_diffusion::linear_diffusion(json const& material_data) : material_property(material_data)
{
    if (material_data.find("conductivity") != material_data.end())
    {
        m_conductivity = material_data["conductivity"];
    }
    if (material_data.find("specific_heat") != material_data.end())
    {
        m_specific_heat = material_data["specific_heat"];
    }
    else
    {
        throw std::domain_error("\"specific_heat\" needs to be specified as a material "
                                "property");
    }
}
Exemplo n.º 23
0
static void iter_convert(const json& json, string& root_path, datum& ret_datum) {
  json_value* value = json.get();
  if (typeid(*value) == typeid(json_integer)) {
    json_integer* int_value = dynamic_cast<json_integer*>(value);
    convert_integer(*int_value, root_path, ret_datum);

  } else if (typeid(*value) == typeid(json_float)) {
    json_float* float_value = dynamic_cast<json_float*>(value);
    convert_float(*float_value, root_path, ret_datum);
    
  } else if (typeid(*value) == typeid(json_string)) {
    json_string* string_value = dynamic_cast<json_string*>(value);
    convert_string(*string_value, root_path, ret_datum);

  } else if (typeid(*value) == typeid(json_bool)) {
    json_bool* bool_value = dynamic_cast<json_bool*>(value);
    convert_bool(*bool_value, root_path, ret_datum);

  } else if (typeid(*value) == typeid(json_null)) {
    json_null* null_value = dynamic_cast<json_null*>(value);
    convert_null(*null_value, root_path, ret_datum);

  } else if (typeid(*value) == typeid(json_array)) {
    json_array* array_value = dynamic_cast<json_array*>(value);
    convert_array(*array_value, root_path, ret_datum);

  } else if (typeid(*value) == typeid(json_object)) {
    json_object* object_value = dynamic_cast<json_object*>(value);
    convert_object(*object_value, root_path, ret_datum);
  }
}
Exemplo n.º 24
0
json HTTPHandler::postAPIRequest(json data, const char *url)
{
    CURL *curl;
    CURLcode res;
    string response, send_data;
    ostringstream auth_header, content_header;
    struct curl_slist *chunk = NULL;
    curl = curl_easy_init();
    json j = {};
    send_data = data.dump();

    if (curl)
    {
        auth_header << "Authorization: Bearer " << Config::getAuthToken().c_str();
        content_header << "Content-Type: application/json";

        chunk = curl_slist_append(chunk, auth_header.str().c_str());
        chunk = curl_slist_append(chunk, content_header.str().c_str());

        res = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, send_data.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeToString);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);

        j = json::parse(response);
    }

    return j;
}
Exemplo n.º 25
0
	InputContext::InputContext( const json & j )
	{
		_name = j.get( "context", json::nullRef ).asString();
		_priority = j.get( "priority", json::nullRef ).asInt();

		auto inputList = j.get( "input_list", json::nullRef );
		if( inputList.isNull() )
		{
			TRACE_WARNING( "Input Context action list is not found." );
			return;
		}

		for( uint i = 0; i < inputList.size(); ++i )
		{
			addEventAction( EventAction::FromJson( inputList[ i ] ) );
		}
	}
bool SimpleScene::Deserialize(const json &node, std::string dir) {

	//No camera deserialization for now
	if (node.find("layers") == node.end()) {
		SIMPLE_LOG("Couldn't deserialize layers");
		return false;
	}

	for (auto l : node["layers"]) {
		SimpleLayer* layer = new SimpleLayer();
		if (!layer->Deserialize(l))
			return false;
		AddLayer(layer);
	}
	return true;
	
}
Exemplo n.º 27
0
Germline::Germline(string code, char shortcut, string path, json json_recom, int max_indexing)
{
    
  int delta_min = -10;
  
  if (json_recom.find("4") != json_recom.end()) {
      delta_min = 0;
  }
  
  init(code, shortcut, delta_min, max_indexing);

  bool regular = (code.find("+") == string::npos);
  
  rep_5 = Fasta(2, "|", regular ? CYS104_IN_GAPPED_V : 0) ;
  rep_4 = Fasta(2, "|") ;
  rep_3 = Fasta(2, "|", regular ? PHE118_TRP118_IN_GAPPED_J : 0) ;

  for (json::iterator it = json_recom["5"].begin();
       it != json_recom["5"].end(); ++it) 
  {
    string filename = *it;
    f_reps_5.push_back(path + filename);
    rep_5.add(path + filename);
  }
  
  if (json_recom.find("4") != json_recom.end()) {
    for (json::iterator it = json_recom["4"].begin();
        it != json_recom["4"].end(); ++it) 
    {
        string filename = *it;
        f_reps_4.push_back(path + filename);
        rep_4.add(path + filename);
    }
  }
  
  for (json::iterator it = json_recom["3"].begin();
       it != json_recom["3"].end(); ++it) 
  {
    string filename = *it;
    f_reps_3.push_back(path + filename);
    rep_3.add(path + filename);
  }

  if (rep_4.size())
    seg_method = SEG_METHOD_543 ;
}
Exemplo n.º 28
0
void resetGame() {
    delete game_p;
    game_p = NULL;
    pregame_player_msgs.clear();
    send_buffer.clear();
    receive_buffer.clear();
    lastUpdateTime = 0;
}
Exemplo n.º 29
0
    boost::any configuration_parser::convert_json(const json& _json)
    {
        switch (_json.type()) {
            case json::value_t::string:
                return _json.get<std::string>();

            case json::value_t::number_float:
                return _json.get<double>();

            case json::value_t::number_integer:
            case json::value_t::number_unsigned:
                return _json.get<int>();

            case json::value_t::boolean:
                return _json.get<bool>();

            case json::value_t::array: {
                std::vector<boost::any> array;

                for (auto&& jj : _json) {
                    array.push_back(convert_json(jj));
                }

                return array;
            }

            case json::value_t::object: {
                std::unordered_map<std::string, boost::any> object;

                //for (auto&& [k, v] : j.items()) { // Supported in later versions :(
                for (auto it = std::begin(_json); it != std::end(_json); ++it) {
                    object.insert({it.key(), convert_json(it.value())});
                }

                return object;
            }

            case json::value_t::null:
                return std::string{"NULL"};

            default:
                const auto type = static_cast<std::uint8_t>(_json.type());
                THROW(-1, (boost::format("unhandled type in json_typeof: %d") % type));
        }
    } // parse_json_object
Exemplo n.º 30
0
int rename_file(const char * id, const char * to, time_t mtime) {
  fprintf(rlog, "renaming id:%s -> %s\n", id, to);
  char url[1024];
  snprintf(url, 1024, "drive/v3/files/%s?fields=name,id,size,md5Checksum", id);
  DriveApi rename{PATCH, url};
  rename.params.AddMember("name", StringRef(to));
  char date[32];
  strftime(date, 32, "%Y-%m-%dT%TZ", gmtime(&mtime));
  rename.params.AddMember("modifiedTime", StringRef(date));
  
  auto resp = rename.perform();
  HANDLE_ERROR("rename", resp);

  //printf("Rename Success!\n");
  //printf("%s\n", resp.str.c_str());

  return 0;
}