void deserializeDictionaryModel(const nlohmann::json& input,
                                DictionaryModel& dictionaryModel) {
  nlohmann::json::const_iterator it = input.find("entities");
  if (it != input.end() && (*it).is_object()) {
    deserializeDictionary(*it, dictionaryModel);
  }
}
Example #2
0
/**
* Click and drag absolute: move to a relative coordinate within the window
* windowname, clamped.
*/
bool clickAndDragAbsolute(std::string window_name, nlohmann::json action){
   //populate the window variables. 
  int x_start, x_end, y_start, y_end, mouse_button;
  bool no_clamp = false; 
  bool success = populateClickAndDragValues(action, window_name, x_start,
                       x_end, y_start, y_end, mouse_button, no_clamp);
  
  //if we couldn't populate the values, do nothing (window doesn't exist)
  if(!success){ 
    std::cout << "Click and drag unsuccessful due to failure to populate click and drag values." << std::endl;
    return false;
  }


  int start_x_position = action.value("start_x", -1);
  int start_y_position = action.value("start_y", -1);

  int end_x_position = action.value("end_x", -1);
  int end_y_position = action.value("end_y", -1);

  if (start_x_position == end_x_position && start_y_position == end_y_position){
    std::cout << "Error, the click and drag action did not specify movement." << std::endl;
    return false;
  }

  if(end_x_position == -1 || end_y_position == -1){
    std::cout << "ERROR: the click and drag action must include an ending position" << std::endl;
    return false;
  }
  


  //get the mouse into starting position if they are specified.
  if(start_x_position != -1 && start_y_position != -1){ 
    start_x_position = start_x_position + x_start;
    start_y_position = start_y_position + y_start;

    //don't move out of the window.
    clamp(start_x_position, x_start, x_end); 
    clamp(start_y_position, y_start, y_end);
    mouse_move(window_name, start_x_position, start_y_position,x_start, x_end, 
                                                        y_start, y_end, false); 
  }
  
  end_x_position = end_x_position + x_start;
  end_y_position = end_y_position + y_start;
  
  //clamp the end position so we don't exit the window. 
  clamp(end_x_position, x_start, x_end); 
  clamp(end_y_position, y_start, y_end);

  //These functions won't do anything if the window doesn't exist. 
  mouseDown(window_name,mouse_button); 
  mouse_move(window_name, end_x_position, end_y_position,x_start, x_end, 
                                                  y_start, y_end, false);
  mouseUp(window_name,mouse_button);  

  return true;
}
Example #3
0
void ExprFunction<T>::set(const nlohmann::json &j, const Tvarvec &vars) {
    Tconstvec consts;
    auto it = j.find("constants");
    if (it != j.end())
        for (auto i = it->begin(); i != it->end(); ++i)
            consts.push_back({i.key(), i.value()});
    set(j.at("function"), vars, consts);
}
void deserializeIntentModel(const nlohmann::json& input,
                            const DictionaryModel& dictionaryModel,
                            IntentModel& intentModel) {
  nlohmann::json::const_iterator it = input.find("intents");
  if (it != input.end() && (*it).is_array()) {
    const nlohmann::json::array_t& intents = *it;
    deserializeIntents(intents, dictionaryModel, intentModel);
  }
}
void deserializeIntentStoryModel(const nlohmann::json& input,
                                 IntentStoryModel& intentStoryModel) {
  nlohmann::json::const_iterator it;

  it = input.find("intent_story");
  if (it != input.end() && (*it).is_object()) {
    deserializeIntentStory(*it, intentStoryModel);
  }
}
void deserializeChatbotActionModel(const nlohmann::json& input,
                                   ChatbotActionModel& chatbotActionModel) {
  nlohmann::json::const_iterator it;

  it = input.find("chatbot");
  if (it != input.end() && (*it).is_object()) {
    deserializeChatbotActions(*it, chatbotActionModel);
  }
}
Example #7
0
	Unit(const nlohmann::json &obj) : Point(obj)
	{
		if (obj.count("M"))
			mass = obj["M"].get<double>();
		if (obj.count("SX"))
			speed.x = obj["SX"].get<double>();
		if (obj.count("SY"))
			speed.y = obj["SY"].get<double>();
	}
void RaytracingConfig::loadFromJSON(const nlohmann::json & config) {

    enabled = config.get<bool>("enabled");
    title = config.get<std::string>("title");
    controlsCamera = config.get<bool>("controlsCamera");

    renderOutputWidth = config.get<int>("outputWidth");
    renderOutputHeight = config.get<int>("outputHeight");
    
    computationDevice = (ComputationDevice) config.get<int>("computationDevice");
    brdfType = (SupportedBRDF) config.get<int>("brdfType");
    supportedPhotonMap = (SupportedPhotonMap) config.get<int>("supportedPhotonMap");
    
    numberOfPhotonsToGather = config.get<int>("numberOfPhotonsToGather");
    raysPerLight = config.get<int>("raysPerLight");
    float maxPhotonGatherDistance = config.get<double>("maxPhotonGatherDistance", -1.0);
    if (maxPhotonGatherDistance != -1.0f) {
        this->maxPhotonGatherDistance = maxPhotonGatherDistance;
    }
    else {
        this->maxPhotonGatherDistance = std::numeric_limits<float>::infinity();
    }
    
    lumensPerLight = config.get<int>("lumensPerLight");
    
    photonBounceProbability = config.get<double>("photonBounceProbability");
    photonBounceEnergyMultipler = config.get<double>("photonBounceEnergyMultipler");
    
    usePhotonMappingForDirectIllumination = config.get<bool>("usePhotonMappingForDirectIllumination");
    
    directIlluminationEnabled = config.get<bool>("directIlluminationEnabled");
    indirectIlluminationEnabled = config.get<bool>("indirectIlluminationEnabled");
    shadowsEnabled = config.get<bool>("shadowsEnabled");
    
    if (config.has("Hashmap_properties")) {
        hashmapCellsize = config["Hashmap_properties"].get<double>("cellsize");
        hashmapSpacing = config["Hashmap_properties"].get<int>("spacing");
        hashmapGridStart = vec3FromData(config["Hashmap_properties"].get<std::vector<double>>("gridStart", make_vector<double>(0,0,0)));
        hashmapGridEnd = vec3FromData(config["Hashmap_properties"].get<std::vector<double>>("gridEnd", make_vector<double>(0,0,0)));
    }
    
    if (config.has("Tile_properties")) {
        tile_width = config["Tile_properties"].get<int>("tileHeight");
        tile_height = config["Tile_properties"].get<int>("tileWidth");
        
        tile_photonEffectRadius = config["Tile_properties"].get<double>("photonEffectRadius");
        tile_photonSampleRate = config["Tile_properties"].get<double>("photonSampleRate");
    }
    
    if (config.has("photonEffectRadius")) {
        this->maxPhotonGatherDistance = config.get<double>("photonEffectRadius", 1.0);
        tile_photonEffectRadius = this->maxPhotonGatherDistance;
    }
}
void deserializeChatbotActions(const nlohmann::json& chatbot,
                               ChatbotActionModel& chatbotActionModel) {
  nlohmann::json::const_iterator it;

  it = chatbot.find("replies");
  if (it != chatbot.end() && (*it).is_object()) {
    deserializeReplies(*it, chatbotActionModel);
  }

  it = chatbot.find("replies_by_state_action");
  if (it != chatbot.end() && (*it).is_object()) {
    deserializeReplyIdsByStateAndActionId(*it, chatbotActionModel);
  }
}
localization::ssd::config::config(nlohmann::json js)
{
    if (js.is_null())
    {
        throw std::runtime_error("missing ssd config in json config");
    }

    for (auto& info : config_list)
    {
        info->parse(js);
    }
    verify_config("localization_ssd", config_list, js);

    add_shape_type({2, 1}, "int32_t");
    add_shape_type({max_gt_boxes, 4}, "float");
    add_shape_type({1, 1}, "int32_t");
    add_shape_type({max_gt_boxes, 1}, "int32_t");

    // 'difficult' tag for gt_boxes
    add_shape_type({max_gt_boxes, 1}, "int32_t");

    class_name_map.clear();
    for (int i = 0; i < class_names.size(); i++)
    {
        class_name_map.insert({class_names[i], i});
    }

    validate();
}
Example #11
0
inline void
from_json (const nlohmann::json& j, tileset& ts)
{
    ts.firstgid = j["firstgid"].get<uint32>();

    if (j.count("source"))
    {
        ts.type = tileset::tiled_tileset_type_external;
        ts.source = j["source"].get<std::string>();
    }
    else
    {
        ts.type = tileset::tiled_tileset_type_embedded;
        ts.name = j["name"].get<std::string>();
        ts.tilewidth = j["tilewidth"].get<uint32>();
        ts.tileheight = j["tileheight"].get<uint32>();
        ts.spacing = j["spacing"].get<uint32>();
        ts.margin = j["margin"].get<uint32>();
        ts.tilecount = j["tilecount"].get<uint32>();
        ts.columns = j["columns"].get<uint32>();
        ts.image = j["image"].get<std::string>();
        ts.imagewidth = j["imagewidth"].get<uint32>();
        ts.imageheight = j["imageheight"].get<uint32>();
    }
}
Example #12
0
/**
* This function sets the window variables (using populateWindowData), and 
* mouse_button (pressed) destination (an x,y tuple we are dragging to), and 
* no_clamp (which is currently disabled/false). returns false on failure. 
* It is on the programmer to check.
*/
bool populateClickAndDragValues(nlohmann::json action, std::string window_name, 
      int& window_left, int& window_right, int& window_top, int& window_bottom, int& mouse_button, 
                                bool& no_clamp){
  int height, width;
  //Get the window dimensions.
  populateWindowData(window_name,height,width,window_left,window_right,window_top,window_bottom);


  // if(command.find("no clamp") != std::string::npos){
  //   std::cout << "Multiple windows are not yet supported. (No 'no clamp' option available)" << std::endl;
  //   no_clamp = false;
  // }

  std::string mouse_button_string = action.value("mouse_button", "left");

  if(mouse_button_string == "left"){
    mouse_button = 1;
  }
  else if (mouse_button_string == "middle"){
    mouse_button = 2;
  }
  else if (mouse_button_string == "right"){
    mouse_button = 3;
  }
  else{ //default.
    mouse_button = 1; 
  }
  return true;
}
std::vector<Vector<dim>> deserializeVectors(const nlohmann::json &data) {
    std::vector<Vector<dim>> vectors;
    if (data.empty())
        return vectors;

    if (data["Dimension"].get<unsigned int>() != dim) {
        Logging::error("Data has wrong dimension", "JsonSerializer");
        return vectors;
    }

    std::vector<std::vector<double>> stdVectors = data["data"].get<std::vector<std::vector<double>>>();
    size_t size = data["NumberConfigurations"].get<size_t>();
    if (stdVectors.size() != size) {
        Logging::error("Wrong vector size of file", "JsonSerializer");
        return vectors;
    }

    for (const auto &vec : stdVectors) {
        Vector<dim> eigenVec;
        for (unsigned int j = 0; j < dim; ++j)
            eigenVec[j] = vec[j];
        vectors.push_back(eigenVec);
    }
    return vectors;
}
Example #14
0
 /**
  * Import parameters from given json object.
  * Throw std::runtime_error if given json is malformated.
  */
 inline void loadJSON(const nlohmann::json& j)
 {
     //Empty case
     if (j.is_null()) {
         return;
     }
     //Check json type
     if (!j.is_object()) {
         throw std::runtime_error(
             "ParametersContainer load parameters json not object");
     }
     //Iterate on json entries
     for (nlohmann::json::const_iterator it=j.begin();it!=j.end();it++) {
         if (it.value().is_boolean()) {
             //Boolean
             if (_paramsBool.count(it.key()) == 0) {
                 throw std::runtime_error(
                     "ParametersContainer load parameters json bool does not exist: " 
                     + it.key());
             } else {
                 paramBool(it.key()).value = it.value();
             }
         } else if (it.value().is_number()) {
             //Number
             if (_paramsNumber.count(it.key()) == 0) {
                 throw std::runtime_error(
                     "ParametersContainer load parameters json number does not exist: " 
                     + it.key());
             } else {
                 paramNumber(it.key()).value = it.value();
             }
         } else if (it.value().is_string()) {
             //String
             if (_paramsStr.count(it.key()) == 0) {
                 throw std::runtime_error(
                     "ParametersContainer load parameters json str does not exist: " 
                     + it.key());
             } else {
                 paramStr(it.key()).value = it.value();
             }
         } else {
             throw std::runtime_error(
                 "ParametersContainer load parameters json malformated");
         }
     }
 }
Example #15
0
inline std::optional<nlohmann::json::const_iterator> find_json(const nlohmann::json& json,
                                                               const std::string& key) {
  auto it = json.find(key);
  if (it != std::end(json)) {
    return it;
  }
  return std::nullopt;
}
/*
 * The check_equal function determines if the labels of the datanode and the querynode are equal.
 * The function iterates through all the labels of the query node and compares its value to that of the datanode.
 * It returns true only if all the labels match; returns false otherwises.
 */
    bool check_equal(nlohmann::json datanode, nlohmann::json querynode) {
        for (nlohmann::json::iterator it = querynode.begin(); it != querynode.end(); ++it) {
            if ((it.key() != "id") && (it.key() != "out_degree")) {
                if (datanode.find(it.key()) != datanode.end()) {
                    if(datanode[it.key()].is_string())
                    {
                        std::string d = datanode[it.key()], q= it.value();
                        if(d.find(q)== std::string::npos)
                            return false;
                    }
                    else if (datanode[it.key()] != it.value())
                        return false;
                } else
                    return false;
            }
        }
        return true;
    }
Example #17
0
inline nlohmann::json find_copy(const nlohmann::json& json,
                                const std::string& key,
                                const nlohmann::json& fallback_value) {
  auto it = json.find(key);
  if (it != std::end(json)) {
    return it.value();
  }
  return fallback_value;
}
void deserializeIntentStory(const nlohmann::json& story,
                            IntentStoryModel& intentStoryModel) {
  nlohmann::json::const_iterator it;

  it = story.find("root");
  if (it != story.end() && (*it).is_string()) {
    IntentStoryModel::VertexInfo vInfo;
    vInfo.stateId = *it;
    IntentStoryModel::StoryGraph::Vertex v =
        intentStoryModel.graph.addVertex(vInfo);
    intentStoryModel.vertexByStateId[vInfo.stateId] = v;
    intentStoryModel.rootStateId = vInfo.stateId;
  }

  it = story.find("graph");
  if (it != story.end() && (*it).is_object()) {
    deserializeGraph(*it, intentStoryModel);
  }
}
  to_if_held_down(const nlohmann::json& json) : dispatcher_client(),
                                                current_held_down_id_(0) {
    try {
      if (json.is_object()) {
        to_ = std::vector<to_event_definition>{
            json.get<to_event_definition>(),
        };

      } else if (json.is_array()) {
        to_ = json.get<std::vector<to_event_definition>>();

      } else {
        throw pqrs::json::unmarshal_error(fmt::format("json must be object or array, but is `{0}`", json.dump()));
      }

    } catch (...) {
      detach_from_dispatcher();
      throw;
    }
  }
Example #20
0
inline std::optional<T> find(const nlohmann::json& json,
                             const std::string& key) {
  auto it = json.find(key);
  if (it != std::end(json)) {
    try {
      return it.value().get<T>();
    } catch (std::exception&) {
    }
  }

  return std::nullopt;
}
files_and_template_pages_parameters::files_and_template_pages_parameters(const nlohmann::json &config)
{
	// Optional parameters
	try {
		const auto &default_behavior =
			config.at("default_behavior").get<std::string>();
		
		if (default_behavior == "files") {
			this->default_behavior =
				files_and_template_pages_parameters::behavior::files;
		} else if (default_behavior == "template_pages") {
			this->default_behavior =
				files_and_template_pages_parameters::behavior::template_pages;
		} else {
			throw std::logic_error("Incorrect config");
		}
	} catch (const std::out_of_range &) {}
	
	
	try {
		this->change_behavior_regex =
			config.at("change_behavior_regex").get<std::string>();
	} catch (const std::out_of_range &) {}
}
Example #22
0
	PlayerFragment(const nlohmann::json &obj) : CircularUnit(obj)
	{
		if (obj.count("TTF"))
			ttf = obj["TTF"].get<int>();

		auto id_str = obj["Id"].get<string>();
		auto dot_pos = id_str.find('.');
		if (dot_pos == string::npos)
		{
			playerId = stoi(id_str);
		}
		else
		{
			playerId = stoi(id_str.substr(0, dot_pos));
			fragmentId = stoi(id_str.substr(dot_pos + 1));
		}
	}
Example #23
0
bool ReadTexturesFromJson(const nlohmann::json& json_textures, const filesystem::path& base_path, ID3D11Device* device, std::vector<TextureIdentifier>* textures) {
  const auto& json_textures_array = json_textures.value("textures", nlohmann::json::array({}));

  if (!json_textures_array.is_array()) {
    DXFW_TRACE(__FILE__, __LINE__, false, "Invalid textures JSON %S", json_textures_array.dump().c_str());
    return false;
  }

  for (const auto& json_texture : json_textures_array) {
    if (!json_texture.is_object()) {
      DXFW_TRACE(__FILE__, __LINE__, false, "Invalid textures entry %S", json_texture.dump().c_str());
      continue;
    }

    const auto& json_texture_name_it = json_texture.find("name");
    if (json_texture_name_it == json_texture.end() || !json_texture_name_it->is_string()) {
      DXFW_TRACE(__FILE__, __LINE__, false, "Invalid texture name %S", json_texture_name_it->dump().c_str());
      continue;
    }

    const auto& json_texture_path_it = json_texture.find("filename");
    if (json_texture_path_it == json_texture.end() || !(json_texture_path_it->is_string() || json_texture_path_it->is_array())) {
      DXFW_TRACE(__FILE__, __LINE__, false, "Invalid texture filename(s) %S", json_texture_path_it->dump().c_str());
      continue;
    }

    TextureIdentifier identifier;
    identifier.Hash = std::hash<std::string>()(*json_texture_name_it);

    if (json_texture_path_it->is_string()) {
      identifier.Texture = ReadSingleTexture(identifier.Hash, *json_texture_path_it, base_path, device);
    } else {  // Array
      identifier.Texture = ReadMipmapTexture(identifier.Hash, *json_texture_path_it, base_path, device);
    }

    if (!identifier.Texture.IsValid()) {
      DXFW_TRACE(__FILE__, __LINE__, false, "Error creating texture %S", json_texture_name_it->dump().c_str());
      continue;
    }

    textures->emplace_back(std::move(identifier));
  }

  return true;
}
Example #24
0
void interface::config::verify_config(
        const std::string& location,
        const vector<shared_ptr<interface::config_info_interface>>& config,
        nlohmann::json js) const
{
    json::parser_callback_t cb = [&](int depth, json::parse_event_t event, json& parsed) {
        if(event == json::parse_event_t::key) {
            string key = parsed;
            bool found = false;
            for(auto item : config) {
                if(item->name() == key) {
                    found = true;
                    break;
                }
            }
            if(!found) {
                int distance = numeric_limits<int>::max();
                string suggestion;
                for(auto item : config) {
                    int test = LevenshteinDistance(item->name(), key);
                    if(test < distance) {
                        distance = test;
                        suggestion = item->name();
                    }
                }
                stringstream ss;
                ss << "key '" << key << "'" << " not found, did you mean '" << suggestion << "'";
                throw invalid_argument(ss.str());
            }
        }
        return true;
    };

    string text;
    try {
        text = js.dump();
        json::parse(text, cb);
    } catch( exception err ) {
        // This is not an error, it just means the json is empty
//        stringstream ss;
//        ss << "parse error for json '" << text << "' in " << location;
//        throw runtime_error(ss.str());
    }
}
Example #25
0
		//--------------------------------------------------------------
		void Particles::deserialize(const nlohmann::json & json)
		{
			ofxPreset::Serializer::Deserialize(json, nm::Particle::parameters);

			// Restore Renderer settings.
			if (json.count("Renderers"))
			{
				auto & jsonRenderers = json["Renderers"];
				for (auto & it : this->renderers)
				{
					ofxPreset::Serializer::Deserialize(jsonRenderers, it.second.parameters);
				}
			}

			if (!this->parameters.stateFile->empty())
			{
				this->loadState(this->parameters.stateFile);
			}
		}
Example #26
0
    config(nlohmann::json js)
        : frame(js["frame"])
    {
        if (js.is_null())
        {
            throw std::runtime_error("missing video config in json config");
        }

        for (auto& info : config_list)
        {
            info->parse(js);
        }
        verify_config("video", config_list, js);

        // channel major only
        add_shape_type({frame.channels, max_frame_count, frame.height, frame.width},
                       {"channels", "frames", "height", "width"},
                       frame.output_type);
    }
Example #27
0
/**
 * Call the lua script to plot the Stock
 * @param data json object of the Stock
 */
void Plot::plot(const nlohmann::json &data) const {
  /** Convert the json to a string */
  std::string data_str = data.dump();
  /** Create a table on the lua Stack to communicate with the script */
  lua_createtable(this->lua_state, 1, 0);
  /** Push the index 1 to the Stack */
  lua_pushnumber(this->lua_state, 1);
  /** Push the json data to the Stack */
  lua_pushstring(this->lua_state, data_str.c_str());
  /** Submit the Stack */
  lua_settable(this->lua_state, -3);
  /** Make the stack available for lua */
  lua_setglobal(this->lua_state, "arg");
  /** Run the lua script */
  int status = luaL_dofile(this->lua_state, this->path_to_script.c_str());
  /** Check if the script executed with errors */
  if (status != LUA_OK) {
    /** Throw a PlotScriptError with the error message of the lua script */
    throw(PlotScriptError(lua_tostring(lua_state, -1)));
  }
}
Example #28
0
void CGC6500::HandleMessage( const nlohmann::json &commandIn )
{
	try
	{		
		if( commandIn[ "cmd" ].get<std::string>() == "chCmd" )
		{
			size_t channelNum = commandIn.at( "ch" ).get<size_t>();
			
			// Pass message down to specified channel
			m_pChannels.at( channelNum )->HandleMessage( commandIn );
		}
		else
		{
			throw std::runtime_error( "Unknown command" );
		}
	}
	catch( const std::exception &e )
	{
		std::cerr << "Error handling message: " << e.what() << std::endl;
	}
}
Example #29
0
  static entry make_from_json(const nlohmann::json& json) {
    entry result(device_id(0),
                 event_time_stamp(absolute_time_point(0)),
                 event(),
                 event_type::key_down,
                 event());

    if (json.is_object()) {
      if (auto v = pqrs::json::find<uint32_t>(json, "device_id")) {
        result.device_id_ = device_id(*v);
      }

      if (auto v = pqrs::json::find_json(json, "event_time_stamp")) {
        result.event_time_stamp_ = event_time_stamp::make_from_json(v->value());
      }

      if (auto v = pqrs::json::find<bool>(json, "valid")) {
        result.valid_ = *v;
      }

      if (auto v = pqrs::json::find<bool>(json, "lazy")) {
        result.lazy_ = *v;
      }

      if (auto v = pqrs::json::find_json(json, "event")) {
        result.event_ = event::make_from_json(v->value());
      }

      if (auto v = pqrs::json::find_json(json, "event_type")) {
        result.event_type_ = v->value().get<event_type>();
      }

      if (auto v = pqrs::json::find_json(json, "original_event")) {
        result.original_event_ = event::make_from_json(v->value());
      }
    }

    return result;
  }
Example #30
-1
		//--------------------------------------------------------------
		void Interlude::deserialize(const nlohmann::json & json)
		{
			// Restore Stripes.
			if (json.count("Stripes Back"))
			{
				auto layout = render::Layout::Back;
				auto jsonStripes = json["Stripes Back"];
				for (int i = 0; i < jsonStripes.size(); ++i)
				{
					auto instance = this->addStripes(layout);
					if (instance)
					{
						ofxPreset::Serializer::Deserialize(jsonStripes, instance->parameters);
					}
				}
			}
			if (json.count("Stripes Front"))
			{
				auto layout = render::Layout::Front;
				auto jsonStripes = json["Stripes Front"];
				for (int i = 0; i < jsonStripes.size(); ++i)
				{
					auto instance = this->addStripes(layout);
					if (instance)
					{
						ofxPreset::Serializer::Deserialize(jsonStripes, instance->parameters);
					}
				}
			}
		}