示例#1
0
  void refreshMenu()
  {
    place_wnames_.clear();
    picojson::object& obj = json_.value().get<picojson::object>();
    std::size_t num = (start_ + disp_num_) < place_names_.size() ? disp_num_ : place_names_.size() - start_;
    for (std::size_t i = 0; i < num; ++i)
    {
      std::string name = place_names_[start_ + i];

      picojson::object& params = obj[name].get<picojson::object>();
      char a = 'a' + i;
      std::stringstream sstr;
      sstr << a << ". " << localize_.get(params["name"].get<std::string>());
      place_wnames_.push_back(sstr.str());
    }
  }
示例#2
0
 void listup(const int mode, const int level)
 {
   place_names_.clear();
   picojson::object& obj = json_.value().get<picojson::object>();
   std::string& type = place_type_[mode];
   for (picojson::object::iterator it = obj.begin(); it != obj.end(); ++it)
   {
     picojson::object& data = (it->second).get<picojson::object>();
     std::string& t = data["type"].get<std::string>();
     int l = data["level"].get<double>();
     bool same_type = (mode == 0) || (t == type);
     bool same_level = (level == -1) || (l == level);
     if (same_type && same_level) place_names_.push_back(it->first);
   }
   // TIPS: mapはsort済み
 }
示例#3
0
SpaceStationType::SpaceStationType(const std::string &id_, const std::string &path_)
	: id(id_)
	, model(0)
	, modelName("")
	, angVel(0.f)
	, dockMethod(SURFACE)
	, numDockingPorts(0)
	, numDockingStages(0)
	, numUndockStages(0)
	, shipLaunchStage(3)
	, parkingDistance(0)
	, parkingGapSize(0)
{
	Json data = JsonUtils::LoadJsonDataFile(path_);
	if (data.is_null()) {
		Output("couldn't read station def '%s'\n", path_.c_str());
		throw StationTypeLoadError();
	}

	modelName = data.value("model", "");

	const std::string type = data.value("type", "");
	if (type == "surface")
		dockMethod = SURFACE;
	else if (type == "orbital")
		dockMethod = ORBITAL;
	else {
		Output("couldn't parse station def '%s': unknown type '%s'\n", path_.c_str(), type.c_str());
		throw StationTypeLoadError();
	}

	angVel = data.value("angular_velocity", 0.0f);

	parkingDistance = data.value("parking_distance", 0.0f);
	parkingGapSize = data.value("parking_gap_size", 0.0f);

	padOffset = data.value("pad_offset", 150.f);

	model = Pi::FindModel(modelName, /* allowPlaceholder = */ false);
	if (!model) {
		Output("couldn't initialize station type '%s' because the corresponding model ('%s') could not be found.\n", path_.c_str(), modelName.c_str());
		throw StationTypeLoadError();
	}
	OnSetupComplete();
}
示例#4
0
static void _json_to_lua(lua_State *l, const Json &data)
{
	LUA_DEBUG_START(l);

	switch (data.type()) {
		case Json::nullValue:
			lua_pushnil(l);
			break;

		case Json::intValue:
		case Json::uintValue:
		case Json::realValue:
			lua_pushnumber(l, data.asDouble());
			break;

		case Json::stringValue: {
			const std::string &str(data.asString());
			lua_pushlstring(l, str.c_str(), str.size());
			break;
		}

		case Json::booleanValue:
			lua_pushboolean(l, data.asBool());
			break;

		case Json::arrayValue: {
			lua_newtable(l);
			for (int i = 0; i < int(data.size()); i++) {
				lua_pushinteger(l, i+1);
				_json_to_lua(l, data[i]);
				lua_rawset(l, -3);
			}
			break;
		}

		case Json::objectValue: {
			lua_newtable(l);
			for (Json::const_iterator i = data.begin(); i != data.end(); ++i) {
				const std::string &key(i.key().asString());
				lua_pushlstring(l, key.c_str(), key.size());
				_json_to_lua(l, *i);
				lua_rawset(l, -3);
			}
			break;
		}
	}

	LUA_DEBUG_END(l, 1);
}
示例#5
0
文件: login.cpp 项目: slazav/eventdb
/* Convert login information from string to standard json {id, name, site}.
 * (original information can be different for different sites).
 */
Json
parse_login_data(const string & juser) {

    /* convert string to json */
    Json root = Json::load_string(juser);

    /* if loginza returned an error - throw it */
    if (!root.get("error_message").is_null())
        throw Exc() << juser;

    /* get identity field */
    std::string identity = root["identity"].as_string();
    if (identity == "") throw Err() << "login error";

    /* default name */
    std::string name = identity;

    /* extract site */
    std::string site = get_site(identity);

    /* parse the name if possible and make correct full name */
    Json nn = root["name"];
    if (nn.is_object()) {
        string n1 = nn["first_name"].as_string();
        string n2 = nn["last_name"].as_string();
        string n3 = nn["full_name"].as_string();
        if (n3!="") name=n3;
        else if (n1!="" && n2!="") name = n1+" "+n2;
        else if (n2!="") name=n2;
        else if (n1!="") name=n1;
    }

    /* lj has only identity */
    if (site == "lj") {
        size_t i1 = identity.find("http://");
        size_t i2 = identity.find(".livejournal.com");
        name = identity.substr(i1+7, i2-i1-7);
    }

    /* build the output json */
    Json ret = Json::object();
    ret.set("id", Json(identity));
    ret.set("site",  Json(site));
    ret.set("name",  Json(name));
    return ret;
}
示例#6
0
int main(int argc, char** argv) {
    if (argc != 2) {
        cout << "Usage: clison filename.json\n";
        return 1;
    }
    try {
#ifdef WITH_SCHEMA
        ifstream schfs("schema.json");
        if (!schfs)
            cout << "note: schema.json not found\n";
        else {
            //meta = Json(schfs);
            schfs >> meta;
            string schema_url = "http://json-schema.org/draft-04/schema#";
            if (meta.type() != Json::OBJECT || meta["$schema"] != schema_url) {
                cout << "schema.json is not a http://json-schema.org/draft-04/schema\n";
                meta = Json::null;
            }
            schfs.close();
            sprops = meta["properties"];
        }
#endif
        ifstream fs(argv[1]);
        Json js(fs);
        fs.close();
        Json::indent = 2;
        vector<string> path;
        cli(js, js, path);
    } catch (Json::use_error& ex) {
        cout << "use_error: " << ex.what() << '\n';
    } catch (Json::parse_error& ex) {
        cout << "parse_error: " << ex.what() << '\n';
        cout << "line: " << ex.line << ", col: " << ex.col << '\n';
    } catch (std::exception& ex) {
        cout << "exception: " << ex.what() << '\n';
    }
#ifdef TEST
    meta = Json::null;
    schema = Json::null;
    Json::test();
#endif
}
示例#7
0
Json RiotService::GetMatchFeedByIds::internalCall() {
    Json summoners = _service->_api.getSummonerByIds(_params["ids"]);
    Json::object diff;
    Json::array matches;
    std::string err;
    auto cmp = [](const Json & a, const Json & b) {
        return a["createDate"].number_value() > b["createDate"].number_value();
    };
    for (auto & kv : summoners.object_items()) {
        Json cache = _service->getSummonerInfoCache(kv.first);
        printf("cache : %s\nnew: %s", cache.dump().c_str(), kv.second.dump().c_str());
        if (cache.is_null() || cache["revisionDate"].number_value() < kv.second["revisionDate"].number_value()) {
            diff[kv.first] = kv.second;
        } else {
            matches.insert(matches.end(), cache["games"].array_items().begin(), cache["games"].array_items().end());
        }
    }
    std::sort(matches.begin(), matches.end(), cmp);
    if (!matches.empty()) {
        _onRead(matches);
    }
    for (auto & kv : diff) {
        auto future = std::async(std::launch::async, [this, kv, cmp, &matches]() {
            Json newInfo = _service->_api.getRecentGamesBySummonerId(kv.first);
            if (!newInfo.is_null()) {
                Json::array modifiedMatches;
                for (auto & match : newInfo["games"].array_items()) {
                    auto item = match.object_items();
                    item["summonerId"] = kv.first;
                    item["name"] = kv.second["name"].string_value();
                    modifiedMatches.push_back(item);
                }
                matches.insert(matches.end(), modifiedMatches.begin(), modifiedMatches.end());
                sort(matches.begin(), matches.end(), cmp);
                
                Json::object updateObject(kv.second.object_items());
                updateObject["games"] = modifiedMatches;
                _service->saveSummonerInfo(kv.first, Json(updateObject));
            }
            _onRead(matches);
        });
    }
    return Json(matches);
}
示例#8
0
文件: json.cpp 项目: a4a881d4/oai
int main(int argc, char *argv[])
{
  try
  {
    Json js;

    std::string str("Test\\ string\\ end\\\nAnders was here\n\"Quoted string inside string\"\n");
    std::cout << " --------------- original\n";
    std::cout << str << std::endl;

    js.encode(str);
    std::cout << " --------------- encoded\n";
    std::cout << str << std::endl;

    js.decode(str);
    std::cout << " --------------- decoded\n";
    std::cout << str << std::endl;

    js["String"] = str;
    str = js.ToString();
    std::cout << " --------------- from ToString()\n";
    std::cout << str << std::endl;

    Json js2 = Json::Parse(str);
    std::cout << js2.ToString() << std::endl;

    std::cout << (std::string)js2["String"] << std::endl;

    str = "{\"no-value\":null}";
    Json js3 = Json::Parse(str);
    std::cout << js3.ToString() << std::endl;

    std::cout << " --------------- request\n";
    Json req;
    req["method"] = "test";
    Json params;
    params["value1"] = 1L;
    params["value2"] = "2";
    req["params"] = params;
    std::cout << req.ToString() << std::endl;
  }
  catch (const Exception& e)
  {
    std::cerr << e.ToString() << std::endl;
  }
}
示例#9
0
文件: sqlite_store.cpp 项目: 02N/mx3
void
SqliteStore::set(const string& key, const Json& value) {
    auto serialized = value.dump();
    sqlite::WriteTransaction guard {m_stmts};

    bool did_update = false;
    {
    auto& stmt = m_update;
    stmt->reset();
    stmt->bind(1, key);
    stmt->bind(2, serialized);
    did_update = stmt->exec() > 0;
    }

    if (!did_update) {
        auto& stmt = m_insert;
        stmt->reset();
        stmt->bind(1, key);
        stmt->bind(2, serialized);
        stmt->exec();
    }
    guard.commit();
}
示例#10
0
int main(int argc, char* argv[])
{
  std::string compiler;
  std::string compilerPath;
  Vstring     linklineA;

  extract_linker(compiler, compilerPath, linklineA);

  Json json;
  json.add("compiler",     compiler);
  json.add("compilerPath", compilerPath);
  json.add("link_line",    linklineA);
  json.fini();

  std::string jsonStr = json.result();
  fprintf(stdout,"%s\n",jsonStr.c_str());

  return 0;
}
EResult<Json> Monica::findAndReplaceReferences(const Json& root, const Json& j)
{
	auto sp = supportedPatterns();

	//auto jstr = j.dump();
	bool success = true;
	vector<string> errors;

	if(j.is_array() && j.array_items().size() > 0)
	{
		J11Array arr;

		bool arrayIsReferenceFunction = false;
		if(j[0].is_string())
		{
			auto p = sp.find(j[0].string_value());
			if(p != sp.end())
			{
				arrayIsReferenceFunction = true;

				//check for nested function invocations in the arguments
				J11Array funcArr;
				for(auto i : j.array_items())
				{
					auto r = findAndReplaceReferences(root, i);
					success = success && r.success();
					if(!r.success())
						for(auto e : r.errors)
							errors.push_back(e);
					funcArr.push_back(r.result);
				}

				//invoke function
				auto jaes = (p->second)(root, funcArr);

				success = success && jaes.success();
				if(!jaes.success())
					for(auto e : jaes.errors)
						errors.push_back(e);

				//if successful try to recurse into result for functions in result
				if(jaes.success())
				{
					auto r = findAndReplaceReferences(root, jaes.result);
					success = success && r.success();
					if(!r.success())
						for(auto e : r.errors)
							errors.push_back(e);
					return{r.result, errors};
				}
				else
					return{J11Object(), errors};
			}
		}

		if(!arrayIsReferenceFunction)
			for(auto jv : j.array_items())
			{
				auto r = findAndReplaceReferences(root, jv);
				success = success && r.success();
				if(!r.success())
					for(auto e : r.errors)
						errors.push_back(e);
				arr.push_back(r.result);
			}

		return{arr, errors};
	}
	else if(j.is_object())
	{
		J11Object obj;

		for(auto p : j.object_items())
		{
			auto r = findAndReplaceReferences(root, p.second);
			success = success && r.success();
			if(!r.success())
				for(auto e : r.errors)
					errors.push_back(e);
			obj[p.first] = r.result;
		}

		return{obj, errors};
	}

	return{j, errors};
}
示例#12
0
CollectOptions::CollectOptions (Json const& json) {
  Json obj = json.get("collectOptions");

  method = methodFromString(JsonHelper::getStringValue(obj.json(), "method", ""));
}
示例#13
0
void BlockColors::load(const std::string& zipFileName, const std::string& cacheFileName)
{
    using namespace json11;

    //Keep filenames for later
    this->zipFileName = zipFileName;
    this->cacheFileName = cacheFileName;

    //Zip file interface
    auto archive = ZipFile::Open(zipFileName);

    //Cache JSON. This is a single { } of key:value of "blockid-meta" to .zip CRC and RGBA color
    // ex: {"2-4": {"crc": 5234231, "color": 2489974272}, ... }
    std::string parseErr;
    Json cacheJson = Json::parse(readFile(cacheFileName), parseErr);
    if(!parseErr.empty()) {
        log("Could not read cache \"", cacheFileName, "\": ", parseErr);
    }

    /* Will be true if computeColor is called, basically if cache is missing
     * or CRC changed in zip for any file */
    bool hadToRecompute = false;

    for(unsigned i = 0; i != archive->GetEntriesCount(); ++i)
    {
        /* Name and CRC of the block image in .zip
         * substr on the name is used to cut off the .png at the end */
        auto entry = archive->GetEntry(i);
        unsigned zipcrc = entry->GetCrc32();
        std::string name = entry->GetName();
        name = name.substr(0, name.find('.'));

        /* To get a block color, first the cache is checked.
         * if it's not there, the color is recomputed. If that happens,
         * "hadToRecompute" is set to true, and a new .json cache will be written out */
         
        Json key = cacheJson[name];
        if(key.is_null()) {
            //Look for key with a 0 meta. e.g, "404-0" and not "404"
            std::string nameWithMeta = name + "-0";
            key = cacheJson[nameWithMeta];
        }

        SDL_Color blockColor;

        if(key.is_object() && (unsigned)key["crc"].int_value() == zipcrc) {
            Uint32 cachePixel = key["color"].int_value();
            SDL_GetRGBA(cachePixel, rgba, &blockColor.r, &blockColor.g, &blockColor.b, &blockColor.a);
        } else {
            blockColor = computeColor(entry);
            hadToRecompute = true;
        }

        //Store color and CRC in this object
        blockColors[name] = std::make_pair(blockColor, zipcrc);
    }

    //If any blocks were not found in cache
    if(hadToRecompute) {
        saveNewJsonCache();
    }
}
示例#14
0
文件: scene.cpp 项目: tapio/weep
Entity SceneLoader::instantiate(Json def, Resources& resources, const string& pathContext)
{
	ASSERT(def.is_object());

	if (def["prefab"].is_string()) {
		const string& prefabName = def["prefab"].string_value();
		auto prefabIter = prefabs.find(prefabName);
		if (prefabIter != prefabs.end()) {
			def = assign(prefabIter->second, def);
		} else if (endsWith(prefabName, ".json")) {
				string err;
				Json extPrefab = Json::parse(resources.getText(resolvePath(pathContext, prefabName), Resources::NO_CACHE), err);
				if (!err.empty()) {
					logError("Failed to parse prefab \"%s\": %s", prefabName.c_str(), err.c_str());
				} else {
					def = assign(extPrefab, def);
					prefabs[prefabName] = extPrefab;
				}
		} else {
			logError("Could not find prefab \"%s\"", prefabName.c_str());
		}
	}

	Entity entity = world->create();

	if (def["name"].is_string()) {
		entity.tag(def["name"].string_value());
#ifdef USE_DEBUG_NAMES
		DebugInfo info;
		info.name = def["name"].string_value();
		entity.add<DebugInfo>(info);
	} else {
		static uint debugId = 0;
		DebugInfo info;
		if (def["prefab"].is_string())
			info.name = def["prefab"].string_value() + "#";
		else if (def["geometry"].is_string())
			info.name = def["geometry"].string_value() + "#";
		else info.name = "object#";
		info.name += std::to_string(debugId++);
		entity.tag(info.name);
		entity.add<DebugInfo>(info);
#endif
	}

	// Parse transform
	if (!def["position"].is_null() || !def["rotation"].is_null() || !def["scale"].is_null() || !def["geometry"].is_null()) {
		Transform transform;
		setVec3(transform.position, def["position"]);
		setVec3(transform.scale, def["scale"]);
		if (!def["rotation"].is_null()) {
			const Json& rot = def["rotation"];
			if (rot.is_array() && rot.array_items().size() == 4)
				transform.rotation = quat(rot[3].number_value(), rot[0].number_value(), rot[1].number_value(), rot[2].number_value());
			else transform.rotation = quat(toVec3(rot));
		}
		entity.add(transform);
	}

	// Parse light
	const Json& lightDef = def["light"];
	if (!lightDef.is_null()) {
		Light light;
		const string& lightType = lightDef["type"].string_value();
		if (lightType == "ambient") light.type = Light::AMBIENT_LIGHT;
		else if (lightType == "point") light.type = Light::POINT_LIGHT;
		else if (lightType == "directional") light.type = Light::DIRECTIONAL_LIGHT;
		else if (lightType == "spot") light.type = Light::SPOT_LIGHT;
		else if (lightType == "area") light.type = Light::AREA_LIGHT;
		else if (lightType == "hemisphere") light.type = Light::HEMISPHERE_LIGHT;
		else logError("Unknown light type \"%s\"", lightType.c_str());
		setColor(light.color, lightDef["color"]);
		if (!def["position"].is_null())
			light.position = toVec3(def["position"]);
		if (!lightDef["direction"].is_null())
			light.direction = toVec3(lightDef["direction"]);
		setNumber(light.distance, lightDef["distance"]);
		setNumber(light.decay, lightDef["decay"]);
		entity.add(light);
		numLights++;
	}

	if (!def["geometry"].is_null()) {
		Model model;
		parseModel(model, def, resources, pathContext);
		entity.add(model);
		numModels++;
	}

	// Patch bounding box
	// TODO: Bounding box is not correct if scale changed at runtime
	if (entity.has<Model>() && entity.has<Transform>()) {
		Model& model = entity.get<Model>();
		const Transform& trans = entity.get<Transform>();
		model.bounds.min = model.lods[0].geometry->bounds.min * trans.scale;
		model.bounds.max = model.lods[0].geometry->bounds.max * trans.scale;
		model.bounds.radius = model.lods[0].geometry->bounds.radius * glm::compMax(trans.scale);
	}

	// Parse body (needs to be after geometry, transform, bounds...)
	if (!def["body"].is_null()) {
		const Json& bodyDef = def["body"];
		ASSERT(bodyDef.is_object());
		ASSERT(entity.has<Model>());
		ASSERT(entity.has<Transform>());
		const Model& model = entity.get<Model>();
		const Transform& transform = entity.get<Transform>();

		float mass = 0.f;
		setNumber(mass, bodyDef["mass"]);

		btCollisionShape* shape = NULL;
		const string& shapeStr = bodyDef["shape"].string_value();
		vec3 extents = model.bounds.max - model.bounds.min;
		if (shapeStr == "box") {
			shape = new btBoxShape(convert(extents * 0.5f));
		} else if (shapeStr == "sphere") {
			shape = new btSphereShape(model.bounds.radius);
		} else if (shapeStr == "cylinder") {
			shape = new btCylinderShape(convert(extents * 0.5f));
		} else if (shapeStr == "capsule") {
			float r = glm::max(extents.x, extents.z) * 0.5f;
			shape = new btCapsuleShape(r, extents.y);
		} else if (shapeStr == "trimesh") {
			Geometry* colGeo = nullptr;
			if (bodyDef["geometry"].is_string()) {
				colGeo = resources.getGeometry(bodyDef["geometry"].string_value());
			} else {
				if (bodyDef["geometry"].is_array())
					logError("LODs not supported for collision mesh.");
				colGeo = model.lods[0].geometry;
			}
			if (!colGeo->collisionMesh)
				colGeo->generateCollisionTriMesh();
			if (mass <= 0.f) { // Static mesh
				shape = new btBvhTriangleMeshShape(colGeo->collisionMesh, true);
			} else {
				shape = new btGImpactMeshShape(colGeo->collisionMesh);
				static_cast<btGImpactMeshShape*>(shape)->updateBound();
			}
		} else {
			logError("Unknown shape %s", shapeStr.c_str());
		}
		ASSERT((shapeStr == "trimesh" || bodyDef["geometry"].is_null()) && "Trimesh shape type required if body.geometry is specified");
		ASSERT(shape);

		btVector3 inertia(0, 0, 0);
		shape->calculateLocalInertia(mass, inertia);

		btRigidBody::btRigidBodyConstructionInfo info(mass, NULL, shape, inertia);
		info.m_startWorldTransform = btTransform(convert(transform.rotation), convert(transform.position));
		setNumber(info.m_friction, bodyDef["friction"]);
		setNumber(info.m_rollingFriction, bodyDef["rollingFriction"]);
		setNumber(info.m_restitution, bodyDef["restitution"]);
		if (bodyDef["noSleep"].bool_value()) {
			info.m_linearSleepingThreshold = 0.f;
			info.m_angularSleepingThreshold = 0.f;
		}
		entity.add<btRigidBody>(info);
		numBodies++;
		btRigidBody& body = entity.get<btRigidBody>();
		if (!bodyDef["angularFactor"].is_null())
			body.setAngularFactor(convert(toVec3(bodyDef["angularFactor"])));
		if (!bodyDef["linearFactor"].is_null())
			body.setLinearFactor(convert(toVec3(bodyDef["linearFactor"])));
		if (bodyDef["noGravity"].bool_value())
			body.setFlags(body.getFlags() | BT_DISABLE_WORLD_GRAVITY);
		body.setUserIndex(entity.get_id());
		if (world->has_system<PhysicsSystem>())
			world->get_system<PhysicsSystem>().add(entity);
	}

	if (!def["animation"].is_null()) {
		ASSERT(entity.has<Model>());
		const Json& animDef = def["animation"];
		BoneAnimation anim;
		setNumber(anim.speed, animDef["speed"]);
		entity.add(anim);
		if (animDef["play"].is_bool() && animDef["play"].bool_value())
			world->get_system<AnimationSystem>().play(entity);
		else world->get_system<AnimationSystem>().stop(entity);
	}

	if (def["trackGround"].bool_value()) {
		ASSERT(entity.has<btRigidBody>());
		entity.add<GroundTracker>();
	}

	if (def["trackContacts"].bool_value()) {
		ASSERT(entity.has<btRigidBody>());
		entity.add<ContactTracker>();
	}

	if (def["triggerVolume"].is_object()) {
		ASSERT(entity.has<Transform>());
		const Json& triggerDef = def["triggerVolume"];
		TriggerVolume& trigger = entity.add<TriggerVolume>();

		setNumber(trigger.times, triggerDef["times"]);
		setNumber(trigger.bounds.radius, triggerDef["radius"]);
		setVec3(trigger.bounds.min, triggerDef["min"]);
		setVec3(trigger.bounds.min, triggerDef["max"]);

		if (triggerDef["receiver"].is_string())
			trigger.receiverModule = id::hash(triggerDef["receiver"].string_value());
		if (triggerDef["enterMessage"].is_string())
			trigger.enterMessage = id::hash(triggerDef["enterMessage"].string_value());
		else if (triggerDef["enterMessage"].is_number())
			trigger.enterMessage = triggerDef["enterMessage"].number_value();
		if (triggerDef["exitMessage"].is_string())
			trigger.exitMessage = id::hash(triggerDef["exitMessage"].string_value());
		else if (triggerDef["exitMessage"].is_number())
			trigger.exitMessage = triggerDef["exitMessage"].number_value();

		if (triggerDef["groups"].is_number())
			trigger.groups = 1 << (uint)triggerDef["groups"].number_value();
		else if (triggerDef["groups"].is_array()) {
			for (const auto& item : triggerDef["groups"].array_items())
				trigger.groups |= 1 << (uint)item.number_value();
		}
	}

	if (def["triggerGroup"].is_number()) {
		ASSERT(entity.has<Transform>());
		entity.add<TriggerGroup>().group = 1 << (uint)def["triggerGroup"].number_value();
	}

	if (!def["moveSound"].is_null()) {
		const Json& soundDef = def["moveSound"];
		MoveSound sound;
		if (soundDef["event"].is_string())
			sound.event = id::hash(soundDef["event"].string_value());
		setNumber(sound.stepLength, soundDef["step"]);
		ASSERT(sound.event);
		ASSERT(entity.has<Transform>());
		sound.prevPos = entity.get<Transform>().position;
		entity.add(sound);
	}

	if (!def["contactSound"].is_null()) {
		const Json& soundDef = def["contactSound"];
		ContactSound sound;
		if (soundDef["event"].is_string())
			sound.event = id::hash(soundDef["event"].string_value());
		ASSERT(sound.event);
		ASSERT(entity.has<Transform>());
		ASSERT(entity.has<ContactTracker>());
		entity.add(sound);
	}

	return entity;
}
示例#15
0
int main(int argc, char **argv) {
    if (argc == 2 && argv[1] == string("--stdin")) {
        parse_from_stdin();
        return 0;
    }

    const string simple_test =
        R"({"k1":"v1", "k2":42, "k3":["a",123,true,false,null]})";

    string err;
    auto json = Json::parse(simple_test, err);

    std::cout << "k1: " << json["k1"].string_value() << "\n";
    std::cout << "k3: " << json["k3"].dump() << "\n";

    for (auto &k : json["k3"].array_items()) {
        std::cout << "    - " << k.dump() << "\n";
    }

    std::list<int> l1 { 1, 2, 3 };
    std::vector<int> l2 { 1, 2, 3 };
    std::set<int> l3 { 1, 2, 3 };
    assert(Json(l1) == Json(l2));
    assert(Json(l2) == Json(l3));

    std::map<string, string> m1 { { "k1", "v1" }, { "k2", "v2" } };
    std::unordered_map<string, string> m2 { { "k1", "v1" }, { "k2", "v2" } };
    assert(Json(m1) == Json(m2));

    // Json literals
    Json obj = Json::object({
        { "k1", "v1" },
        { "k2", 42.0 },
        { "k3", Json::array({ "a", 123.0, true, false, nullptr }) },
    });

    std::cout << "obj: " << obj.dump() << "\n";

    assert(Json("a").number_value() == 0);
    assert(Json("a").string_value() == "a");
    assert(Json().number_value() == 0);

    assert(obj == json);
    assert(Json(42) == Json(42.0));
    assert(Json(42) != Json(42.1));

    const string unicode_escape_test =
        R"([ "blah\ud83d\udca9blah\ud83dblah\udca9blah\u0000blah\u1234" ])";

    const char utf8[] = "blah" "\xf0\x9f\x92\xa9" "blah" "\xed\xa0\xbd" "blah"
                        "\xed\xb2\xa9" "blah" "\0" "blah" "\xe1\x88\xb4";

    Json uni = Json::parse(unicode_escape_test, err);
    assert(uni[0].string_value().size() == (sizeof utf8) - 1);
    assert(memcmp(uni[0].string_value().data(), utf8, sizeof utf8) == 0);

    Json my_json = Json::object {
        { "key1", "value1" },
        { "key2", false },
        { "key3", Json::array { 1, 2, 3 } },
    };
    std::string json_str = my_json.dump();
    printf("%s\n", json_str.c_str());

    class Point {
    public:
        int x;
        int y;
        Point (int x, int y) : x(x), y(y) {}
        Json to_json() const { return Json::array { x, y }; }
    };

    std::vector<Point> points = { { 1, 2 }, { 10, 20 }, { 100, 200 } };
    std::string points_json = Json(points).dump();
    printf("%s\n", points_json.c_str());
}
示例#16
0
  EarthViewer(const Vec2<int>& size, const float scale, const bool oblong, Touch& touch, Keyinp& keyinp, const std::string& path, const std::string& lang) :
    touch_(touch),
    keyinp_(keyinp),
    size_(size.x / scale, size.y / scale),
    params_(path + "devdata/params.json"),
    scale_(scale),
    aspect_((float)size.x / (float)size.y),
    camera_(Camera::PERSPECTIVE),
    cockpit_(Camera::ORTHOGONAL),
    localize_(lang, path),
    earth_(params_.value().get<picojson::object>()["earth"].get<picojson::object>(), path, camera_),
    rotate_mix_(),
    place_index_()
  {
    DOUT << "EarthViewer()" << std::endl;

    picojson::object& params = params_.value().get<picojson::object>();

    camera_.oblong(oblong);
    SetupCamera(camera_, params["camera"].get<picojson::object>(), aspect_);
    cockpit_.setSize(size.x / scale, size.y / scale);

    {
      picojson::array& array = params["lights"].get<picojson::array>();
      for (picojson::array::iterator it = array.begin(); it != array.end(); ++it)
      {
        Light light;
        SetupLight(light, it->get<picojson::object>());
        lights_.push_back(light);
      }
      earth_.light(lights_);
    }

    env_.touch       = &touch_;
    env_.keyinp      = &keyinp_;
    env_.path        = &path;
    env_.savePath    = &path;
    env_.size        = &size_;
    env_.scale       = scale_;
    env_.params      = &params_;
    env_.task        = &task_;
    env_.camera      = &camera_;
    env_.cockpit     = &cockpit_;
    env_.earth       = &earth_;
    env_.earthLight  = &lights_[0];
    env_.fonts       = &fonts_;
    env_.texMng      = &texMng_;
    env_.localize    = &localize_;

    env_.earth_texture = 0;
    earth_.texture(env_.earth_texture);
    earth_.setRotSpeed(0);

    {
      const std::string& file = params["game"].get<picojson::object>()["places"].get<std::string>();
      Json places = Json(path + file);
      places_ = places.value().get<picojson::object>();
      for (picojson::object::iterator it = places_.begin(); it != places_.end(); ++it)
      {
        place_names_.push_back(&it->first);
      }
    }

    task_.add<Control>(TASK_PRIO_SYS, env_);
    task_.add<Game2DSetup>(TASK_PRIO_2D_TOPPRIO, env_);
    task_.add<GameWorld>(TASK_PRIO_3D_TOPPRIO, env_);
    env_.task->add<PlaceDisp>(TASK_PRIO_2D, env_);
    // task_.add<Equator>(TASK_PRIO_3D, env_);
    task_.add<TouchEft>(TASK_PRIO_3D, env_);
  }
示例#17
0
// get anonimous user
Json
get_anon(){
  Json ret = Json::object();
  ret.set("level",    LEVEL_ANON);
  return ret;
}
示例#18
0
void
do_write(const CFG & cfg, int argc, char **argv){
  Err("write"); // set error domain
  check_args(argc, 1);        // check argument number
  char * dbname = argv[1];    // database name

  /* check length and symbols in the database name */
  check_name(dbname);

  /* Get user information. Empty session is an error */
  UserDB udb(cfg, DB_RDONLY);
  Json user = udb.get_by_session(get_secret());
  clr_secret();
  if (!user) throw Err() << "authentication error";

  /* read JSON object from stdin */
  Json data = Json::load_stream(stdin);

  /* get id from object or set it to -1 */
  json_int_t id =-1;
  if (data.exists("id")) id = data["id"].as_integer();
  else data.set("id", id);

  /* del field should be 1 if exists */
  if (data.exists("del")){
    if (data["del"].as_integer()!=0) data.set("del", 1);
    else data.del("del");
  }

  /* Open database; LEVEL_ADMIN can create a new one */
  json_int_t level = user["level"].as_integer();
  size_t dbflags = (level>= LEVEL_ADMIN)? DB_CREATE:0;
  DataDB db(cfg, dbname, dbflags); // open database

  /* Set mtime and muser fields */
  data.set("mtime", (json_int_t)time(NULL));
  data.set("muser", user["sid"]);

  /* Set ctime, cuser, prev fields, store old version in archive if needed */
  if (id==-1){ // new object
    data.set("ctime", (json_int_t)time(NULL));
    data.set("cuser", user["sid"]);
    data.set("prev", -1);
  }
  else { // replace object
    /* check is the old version exists*/
    if (!db.exists(id)) throw Err() << "bad id";
    Json old = db.get(id); // old object
    /* check permissions */
    if (old["cuser"].as_string() != user["sid"].as_string() && level < LEVEL_MODER)
      throw Err() << "not enough permissions to edit";
    data.set("ctime", old["ctime"]);
    data.set("cuser", old["cuser"]);
    old.set("id", -1);
    db.arc.put(old);
    data.set("prev", old["id"]);
  }

  /* build date_key */
  if (data.exists("date1") && data["date1"].is_string() &&
      data.exists("date2") && data["date2"].is_string()){
    //put in data_key first common part of date1 and date2
    string d1 = data["date1"].as_string();
    string d2 = data["date2"].as_string();
    string dk = "";
    for (int i=0;i<std::min(d1.length(),d2.length());i++){
      if (d1[i]==d2[i]) dk+=d1[i];
      else break;
    }
    data.set("date_key", dk);
  }
  else {
    // remove date_key field if it exists
    if (data.exists("date_key")) data.del("date_key");
  }

  /* build coord_key */
  if (data.exists("lat1") && data["lat1"].is_number() &&
      data.exists("lat2") && data["lat2"].is_number() &&
      data.exists("lon1") && data["lon1"].is_number() &&
      data.exists("lon2") && data["lon2"].is_number()){
    double lat1 = data["lat1"].as_real();
    double lat2 = data["lat2"].as_real();
    double lon1 = data["lon1"].as_real();
    double lon2 = data["lon2"].as_real();
    string ck="";
    // todo
    data.set("coord_key", ck);
  }
  else {
    // remove coord_key field if it exists
    if (data.exists("coord_key")) data.del("coord_key");
  }

  db.put(data); // put data
  throw Exc() << data.save_string(JSON_OUT_FLAGS);
}
示例#19
0
  Ranking(GameEnv& env, const int mode, const bool record) :
    env_(env),
    active_(true),
    mode_(mode),
    record_(record),
    params_(env.params->value().get<picojson::object>()["ranking"].get<picojson::object>()),
    rank_tbl_(env.params->value().get<picojson::object>()["rank_tbl"].get<picojson::array>()),
    json_(isSavedParamExists(*env.savePath + "results.json") ? *env.savePath + "results.json" : *env.path + "devdata/results.json"),
    font_(ReadFont("ranking", *env.fonts, *env.path, env.params->value().get<picojson::object>())),
    texture_(env.texMng->read(*env.path + "devdata/round.png")),
    title_(params_["title"].get<picojson::array>()[mode_].get<std::string>()),
    skip_delay_(params_["skip_delay"].get<double>()),
    do_skip_(),
    wipe_(true),
    time_cur_(),
    time_ed_(params_["time_ed"].get<double>()),
    ofs_st_(1, 0, 1),
    ofs_ed_(0, 1, 0),
    scale_(),
    scale_st_(0),
    scale_ed_(1),
    scale_time_ed_(time_ed_ * 0.4),
    disp_time_(record ? 0 : params_["disp_time"].get<double>()),
    col_(1, 1, 1, 1),
    col_index_(),
    col_timer_(),
    col_demo_time_(10000),                          // 最初は動かさない
    col_demo_time_ed_(params_["col_demo_time"].get<double>()),
    col_demo_index_(RESULT_NUM),
    agree_(),
    touched_(),
    finish_()
  {
    DOUT << "Ranking()" << std::endl;

    static const char *record_tbl[] = {
      "normal",
      "advanced",
      "survival"
    };

    picojson::array& array = json_.value().get<picojson::object>()[record_tbl[mode_]].get<picojson::array>();
    // FIXME:コードの下の方でも array を使ってます
    for (picojson::array::iterator it = array.begin(); it != array.end(); ++it)
    {
      int level = it->get<picojson::object>()["level"].get<double>();
      int konahen = it->get<picojson::object>()["konahen"].get<double>();
      int score = it->get<picojson::object>()["score"].get<double>();
      int rank = it->get<picojson::object>()["rank"].get<double>();
      
      GameResult result = {
        level,
        konahen,
        score,
        rank,
        false
      };
      results_.push_back(result);
    }

    if (record_)
    {
      GameResult result = {
        env_.level + 1,
        env_.konahen,
        env_.score,
        env_.rank,
        true
      };
      results_.push_back(result);

      {
        picojson::object obj;
        obj["level"] = picojson::value((float)result.level);
        obj["konahen"] = picojson::value((float)result.konahen);
        obj["score"] = picojson::value((float)result.score);
        obj["rank"] = picojson::value((float)result.rank);

        array.push_back(picojson::value(obj));

        std::string fpath = *env_.savePath + "results.json";
        json_.write(fpath);
      }
    }
    std::sort(results_.begin(), results_.end());
    std::reverse(results_.begin(), results_.end());
    results_.resize(RESULT_NUM);

    bool played = false;
    int index = 0;
    for (std::vector<GameResult>::iterator it = results_.begin(); it != results_.end(); ++it, ++index)
    {
      if (it->played)
      {
        played = it->played;
        break;
      }
    }
    // FIXME:ここはアルゴリズムを使うべきか…

    if (played && (index < RANKIN_INDEX))
    {
      switch (env_.game_mode)
      {
      case GAME_MODE_NORMAL:
        {
          AchievementUnlock("advanced", env_);
        }
        break;

      case GAME_MODE_ADVANCED:
        {
          AchievementUnlock("survival", env_);
        }
        break;

      case GAME_MODE_SURVIVAL:
        {
          AchievementUnlock("earth_texture", env_);
        }
        break;
      }
      // ランクインしたら実績解除
    }

    env_.sound->play("ranking", 1, 0.6);
    env_.touch->resistCallBack(this);
  }
示例#20
0
ShortestPathOptions::ShortestPathOptions(Json const& json) {
  Json obj = json.get("shortestpathFlags");
  weightAttribute = JsonHelper::getStringValue(obj.json(), "weightAttribute", "");
  defaultWeight = JsonHelper::getNumericValue<double>(obj.json(), "defaultWeight", 1);
}
示例#21
0
int main (int argc, char *argv[]) {
    google::InitGoogleLogging(argv[0]);

    namespace po = boost::program_options; 
    string root;
    string synsets_path;
    string out_path;
    size_t streams;
    double file_gbs;
    double container_mbs;
    unsigned threads;
    int resize;
    int max;
    int label;

    po::options_description desc("Allowed options");
    desc.add_options()
    ("help,h", "produce help message.")
    ("synsets", po::value(&synsets_path)->default_value("synsets.txt"), "")
    ("root", po::value(&root), "")
    ("out", po::value(&out_path), "")
    ("streams,s", po::value(&streams)->default_value(20), "")
    ("file-gbs,f", po::value(&file_gbs)->default_value(4), "")
    ("container-mbs,c", po::value(&container_mbs)->default_value(200), "")
    ("threads,t", po::value(&threads)->default_value(0), "")
    ("resize,r", po::value(&resize)->default_value(256), "")
    ("max", po::value(&max)->default_value(0), "")
    ("label", po::value(&label)->default_value(-1), "")
    ;   
    
    po::positional_options_description p;
    p.add("root", 1); 
    p.add("out", 1); 
    p.add("synsets", 1); 

    po::variables_map vm; 
    po::store(po::command_line_parser(argc, argv).
                     options(desc).positional(p).run(), vm);
    po::notify(vm); 

    if (vm.count("help") || !root.size() || !out_path.size()) {
        cerr << desc;
        return 1;
    }
    vector<string> tar_paths;
    {
        ifstream is(synsets_path);
        string synset;
        while (is >> synset) {
            string path = root + "/" + synset + ".tar";
            LOG_IF(ERROR, !boost::filesystem::exists(path)) << "cannot find path " << path;
            tar_paths.push_back(path);
        }
        LOG(INFO) << "Loaded " << tar_paths.size() << " tar paths." << endl;
    }

    Geometry geometry;
    geometry.n_stream = streams;
    geometry.file_size = round(file_gbs * GB);
    geometry.container_size = round(container_mbs * MB);

    {
        boost::timer::auto_cpu_timer t;
        DataSet dataset(out_path, geometry, 0);
        std::atomic<unsigned> serial(0);
        std::atomic<unsigned> done(0);
#pragma omp parallel for
        for (unsigned i = 0; i < tar_paths.size(); ++i) {
            Record rec;
            rec.meta.label = label >= 0 ? label : i;
            Tar tar(tar_paths[i]);
            vector<uint8_t> jpeg;
            Tar::posix_header const *header;
            while (tar.next(&jpeg, &header)) {
                rec.meta.serial = serial.fetch_add(1);
                if (max && rec.meta.serial >= max) break;
                cv::Mat image = cv::imdecode(cv::Mat(jpeg), cv::IMREAD_COLOR);
                if (image.total() == 0) {
                    LOG(WARNING) << "fail to load image of size " << jpeg.size();
                    continue;
                }
                if (resize) {
                    cv::Mat image2;
                    cv::resize(image, image2, cv::Size(resize, resize));
                    cv::imencode(".jpg", image2, jpeg);
                }
                Json json = Json::object {
                    {"fname", header->name},
                    {"ocols", image.cols},    
                    {"orows", image.rows}
                };
                string extra = json.dump();
                rec.image_size = jpeg.size();
                rec.image = reinterpret_cast<char const *>(&jpeg[0]);
                rec.extra = &extra[0];
                rec.extra_size = extra.size();
                unsigned n = rec.meta.serial + 1;
                LOG_IF(INFO, n && ((n % 1000) == 0)) << done << '/' << tar_paths.size() << " tar_paths, " << serial << " images.";
#pragma omp critical
                dataset << rec;
            }
            ++done;
        }
    }
}
示例#22
0
bool Pb2Json::Json2RepeatedMessage(const Json& json, ProtobufMsg& message, const ProtobufFieldDescriptor* field,
                                   const ProtobufReflection* reflection, bool str2enum) {
    int count = json.count(field->name());
    for (auto j = 0; j < count; ++j) {
        switch (field->type()) {
            case ProtobufFieldDescriptor::TYPE_BOOL: {
                if (json[j].is_boolean())
                    reflection->AddBool(&message, field, json[j].get<bool>());
                else if (json[j].is_number_integer())
                    reflection->AddBool(&message, field, json[j].get<uint32_t>() != 0);
                else if (json[j].is_string()) {
                    if (json[j].get<std::string>() == "true")
                        reflection->AddBool(&message, field, true);
                    else if (json[j].get<std::string>() == "false")
                        reflection->AddBool(&message, field, false);
                }
            } break;

            case ProtobufFieldDescriptor::TYPE_ENUM: {
                auto const* pedesc = field->enum_type();
                const ::google::protobuf::EnumValueDescriptor* pevdesc = nullptr;
                if (str2enum) {
                    pevdesc = pedesc->FindValueByName(json[j].get<std::string>());

                } else {
                    pevdesc = pedesc->FindValueByNumber(json[j].get<int32_t>());
                }
                if (nullptr != pevdesc) {
                    reflection->AddEnum(&message, field, pevdesc);
                }

            } break;

            case ProtobufFieldDescriptor::TYPE_INT32:
            case ProtobufFieldDescriptor::TYPE_SINT32:
            case ProtobufFieldDescriptor::TYPE_SFIXED32: {
                if (json[j].is_number()) reflection->AddInt32(&message, field, json[j].get<int32_t>());
            } break;

            case ProtobufFieldDescriptor::TYPE_UINT32:
            case ProtobufFieldDescriptor::TYPE_FIXED32: {
                if (json[j].is_number()) reflection->AddUInt32(&message, field, json[j].get<uint32_t>());
            } break;

            case ProtobufFieldDescriptor::TYPE_INT64:
            case ProtobufFieldDescriptor::TYPE_SINT64:
            case ProtobufFieldDescriptor::TYPE_SFIXED64: {
                if (json[j].is_number()) reflection->AddInt64(&message, field, json[j].get<int64_t>());
            } break;

            case ProtobufFieldDescriptor::TYPE_UINT64:
            case ProtobufFieldDescriptor::TYPE_FIXED64: {
                if (json[j].is_number()) reflection->AddUInt64(&message, field, json[j].get<uint64_t>());
            } break;

            case ProtobufFieldDescriptor::TYPE_FLOAT: {
                if (json[j].is_number()) reflection->AddFloat(&message, field, json[j].get<float>());
            } break;

            case ProtobufFieldDescriptor::TYPE_DOUBLE: {
                if (json[j].is_number()) reflection->AddDouble(&message, field, json[j].get<double>());
            } break;

            case ProtobufFieldDescriptor::TYPE_MESSAGE: {
                if (json[j].is_object()) Json2Message(json[j], *reflection->AddMessage(&message, field));
            } break;

            case ProtobufFieldDescriptor::TYPE_STRING:
            case ProtobufFieldDescriptor::TYPE_BYTES: {
                if (json[j].is_string()) reflection->AddString(&message, field, json[j].get<std::string>());
            } break;

            default:
                break;
        }
    }
    return true;
}
示例#23
0
文件: ipc_mgr.cpp 项目: sjjwind0/blog
void IPCManager::HandleMessage(int show_id, const std::string& data) {
    // TODO: adjust to protobuf
    ParseData(data);
    while (true) {
        std::string next_message = "";
        if (GetNextMessage(next_message)) {
            std::string err;
            auto json = Json::parse(next_message, err);
            if (!err.empty()) {
                std::cout << "error: " << err << std::endl;
                continue;
            }
            // std::cout << "message: " << next_message << std::endl;
            std::string action = json["action"].string_value();
            // std::cout << "action: " << action << std::endl;
            if (action == "request") {
                // 请求
                int req_id = json["id"].int_value();
                std::string method = json["method"].string_value();
                std::string req = json["request"].string_value();
                if (ipc_info_map_[show_id].method_map.find(method) != 
                    ipc_info_map_[show_id].method_map.end()) {
                    std::string response = "";
                    (ipc_info_map_[show_id].method_map[method])(req, response);
                    Json obj = Json::object({
                        { "action", "response" },
                        { "id", req_id }, 
                        { "method", method },
                        { "response", response },
                        { "code", ErrorOK },
                    });
                    ipc_info_map_[show_id].fifo->Write(obj.dump());
                } else {
                    Json obj = Json::object({
                        { "action", "response" },
                        { "id", req_id }, 
                        { "method", method },
                        { "error", "no such api." },
                        { "code", ErrorNoSuchAPI },
                    });
                    ipc_info_map_[show_id].fifo->Write(obj.dump());
                }
            } else if (action == "init") {
                // 收到客户端发过来的初始化完成的消息
                if (ipc_info_map_[show_id].fifo->OpenClientFile()) {
                    if (ipc_info_map_[show_id].server_delegate != nullptr) {
                        ipc_info_map_[show_id].server_delegate->OnAcceptNewClient(this, show_id);
                    }
                } else {
                    std::cout << "open client failed: " << errno;
                }

            } else  if (action == "response") {
                // 请求的回应
                std::string method = json["method"].string_value();
                if (ipc_info_map_[show_id].method_callback_map.find(method) != ipc_info_map_[show_id].method_callback_map.end()) {
                    int req_id = json["id"].int_value();
                    if (ipc_info_map_[show_id].method_callback_map[method].find(req_id) 
                        != ipc_info_map_[show_id].method_callback_map[method].end()) {
                        ErrorCode code = ErrorCode((json["code"].int_value()));
                        if (code == ErrorOK) {
                            std::string req = json["response"].string_value();
                            (ipc_info_map_[show_id].method_callback_map[method][req_id])(code, req);
                        } else {
                            std::string error = json["error"].string_value();
                            (ipc_info_map_[show_id].method_callback_map[method][req_id])(code, error);
                        }
                    }
                }
            } else if (action == "close") {
                // 关闭
                if (ipc_info_map_[show_id].client_delegate != nullptr) {
                    ipc_info_map_[show_id].client_delegate->OnServerClose(this);
                }
            }
        } else {
            break;
        }
    }
}
示例#24
0
static void processFile(const boost::filesystem::path &path, int hrsOffset, result_t &results)
{
    std::string fn = path.string();
    std::time_t t = boost::filesystem::last_write_time(path);

    boost::posix_time::ptime lwt = boost::posix_time::from_time_t(t);
    lwt = boost::date_time::c_local_adjustor<boost::posix_time::ptime>::utc_to_local(lwt);
    lwt += boost::posix_time::time_duration(hrsOffset, 0, 0, 0);

    StatusReport statusReport(fn);

    std::ifstream in(fn.c_str());
    Json json;
    while (!in.eof())
    {
        char c;
        in.get(c);
        json.nextChar(c);
    }

    map_t::const_iterator itor = json.getMap().find("eventlog");
    if (itor != json.getMap().end())
    {
        std::vector<std::string> v;
        json.getArray(itor->second, v);
        if (v.size() > 1) 
        {   // more than just labels
            std::vector<std::string> labels;
            json.getArray(v[0], labels);
            std::map<int, int> colMap;
            for (int j = 0; j < (int)NUM_COLUMNS; j++)
            {
                std::string l; l += '"'; l += Columns[j]; l += '"';
                for (int k = 0; k < labels.size(); k++)
                {
                    if (labels[k] == l)
                        colMap[j] = k;
                }
            }
            if (colMap.size() == (int)NUM_COLUMNS)
            {   // every column we expect appears?
                for (int i = 1; i < v.size(); i++)
                {
                    std::vector<std::string> vals;
                    json.getArray(v[i], vals);
                    if (vals.size() == labels.size())
                    {   // this record has an entry for every label?
                        boost::posix_time::time_duration todFile = lwt.time_of_day();
                        int todHors = todFile.hours();
                        int todMins = todFile.minutes();
                        int hrs = atoi(vals[colMap[HOUR]].c_str());
                        int min = atoi(vals[colMap[MINUTE]].c_str());
                        boost::posix_time::time_duration tod(hrs, min, 0, 0), delta;
                        delta = tod - todFile;
                        const int minMin = 2;
                        if (delta.total_seconds() > (minMin * 60)) // assume rolled over midnight
                            delta -= boost::posix_time::time_duration(24,0,0,0);
                        long ts = delta.total_seconds();
                        const int maxMin = 120;
                        if ((ts > (minMin * 60)) || (ts < (maxMin * -60)))
                        {
                            std::ostringstream oss;
                            oss << "Time label (" << hrs << ':' << min << ") not in window " << maxMin << "min before file stamp ("
                                << todHors << ':' << todMins << ") ts=" << ts;    
                            statusReport.report(oss.str());
                            continue;
                        }
                        boost::posix_time::ptime tstamp = lwt + delta;
                        results[tstamp] = Event(vals[colMap[RELAY]].c_str(), 
                            vals[colMap[TEMPERATURE]].c_str(),
                            vals[colMap[TARGET_TEMPERATURE]].c_str(), 
                            vals[colMap[HUMIDITY]].c_str(),
                            path.filename().string());
                    }
                }
            }
        }
    }
    else statusReport.report("No eventlog in json");
}
示例#25
0
void cli(Json& top, Json js, vector<string>& path) {
start:
    Json::Type type = js.type();
    string fullpath;
    follow(top, path, &fullpath);
    cout << (fullpath == "" ? "at top" : fullpath) << ": " << typetag[type] << endl;
    if (type == Json::Type::OBJECT) {
        int n = 0;
        for (string key : js.keys()) {
            Json prop = js.get(key);
            cout << setw(3) << n++ << ". " << key;
            if (prop.type() == Json::ARRAY)
                cout << " [" << prop.size() << "]";
            else if (prop.type() == Json::OBJECT)
                cout << " {" << prop.size() << "}";
            else
                cout << ": " << prop;
            cout << endl;
        }
    } else if (type == Json::Type::ARRAY) {
        int n = 0;
        for (unsigned i = 0; i < js.size(); i++) {
            cout << setw(3) << n++ << ". ";
            Json elem = js[i];
            Json::Type eltype = elem.type();
            if (eltype == Json::ARRAY)
                cout << typetag[eltype] << " [" << elem.size() << "]";
            else if (eltype == Json::OBJECT)
                cout << typetag[eltype] << " {" << elem.size() << "}";
            else
                cout << elem;
            cout << endl;
        }
    } else
        cout << js << endl;
    char line[1024];
    do {
        cout << "> ";
        cin.getline(line, sizeof(line));
        if (cin.eof()) {
            cout << '\n';
            exit(0);
        }
        char* p = line;
        while (isspace(*p))
            p++;
        if (*p == 0)
            continue;
        if (*p == 'h' || *p == '?') {
            cout << "enter a number to select an object, q to go back\n";
            cout << ".             : list current object\n";
            cout << "p [file.json] : print out current object [into file]\n";
#ifdef WITH_SCHEMA
            cout << "s file.json   : load file as a json schema\n";
#endif
            cout << "= text        : replace current object by parsed text\n";
            continue;
        }
        if (*p == '.')
            goto start;
        if (*p == 'q') {
            if (!path.empty())
                path.pop_back();
            return;
        }
        if (*p == 'p') {
            while (isspace(*++p));
            if (*p == 0) {
                cout << js << '\n';
                continue;
            }
            ofstream out(p);
            if (!out) {
                cout << "cannot write to '" << p << "'\n";
                continue;
            }
            out << js << '\n';
            if (out.bad())
                cout << "i/o error occured while writing\n";
            out.close();
            continue;
        }
#ifdef WITH_SCHEMA
        if (*p == 's') {
            while (isspace(*++p));
            if (*p == 0) {
                cout << "file name expected\n";
                continue;
            }
            ifstream ifs(p);
            if (!ifs) {
                cout << "cannot read " << p << '\n';
                continue;
            }
            try {
                ifs >> schema;
            } catch (std::exception& ex) {
                cout << "exception: " << ex.what() << '\n';
            }
            string reason;
            if (!js.valid(schema, &reason))
                cout << reason << '\n';
            continue;
        }
#endif
        if (*p == '=') {
            try {
                js = Json::parse(p + 1);
                if (path.empty()) {
                    top = js;
                    continue;
                }
                vector<string> ppath(path.begin(), path.end()-1);
                Json parent = follow(top, ppath, nullptr);
                if (parent.type() == Json::Type::ARRAY)
                    parent.replace(stoi(path.back()), js);
                else
                    parent.set(path.back(), js);
            }catch (Json::use_error& ex) {
                cout << "use_error: " << ex.what() << '\n';
            } catch (Json::parse_error& ex) {
                cout << "parse_error: " << ex.what() << '\n';
                cout << "line: " << ex.line << ", col: " << ex.col << '\n';
            }
            continue;
        }
        int n = -1;
        while (isdigit(*p)) {
            if (n < 0)
                n = 0;
            n = 10 * n + (*p++ - '0');
        }
        if (n < 0) {
            cout << "?  (type 'h' for help)\n";
            continue;
        }
        if ((type == Json::OBJECT || type == Json::ARRAY) && n >= (int)js.size()) {
            cout << "out of range\n";
            continue;
        }
        Json next;
        string name;
        if (type == Json::OBJECT) {
            name = js.keys()[n];
            next = js[name];
        } else if (type == Json::ARRAY) {
            name = to_string(n);
            next = js[n];
        }
        if (next.type() != Json::JSNULL) {
            path.push_back(name);
            cli(top, next, path);
            goto start;
        }
    } while (true);
}
示例#26
0
文件: scene.cpp 项目: tapio/weep
void SceneLoader::load_internal(const string& path, Resources& resources)
{
	string pathContext = dirname(path);
	std::string err;
	Json jsonScene = Json::parse(resources.getText(path, Resources::NO_CACHE), err);
	if (!err.empty())
		panic("Failed to read scene %s: %s", path.c_str(), err.c_str());

	if (jsonScene.is_object()) {
		// Handle includes
		if (jsonScene["include"].is_string()) {
			load_internal(resolvePath(pathContext, jsonScene["include"].string_value()), resources);
		} else if (jsonScene["include"].is_array()) {
			for (auto& includePath : jsonScene["include"].array_items())
				load_internal(resolvePath(pathContext, includePath.string_value()), resources);
		}

		// Parse modules
		if (jsonScene["modules"].is_array() && world->has_system<ModuleSystem>()) {
			world->get_system<ModuleSystem>().load(jsonScene["modules"], false);
		}

		// Parse environment
		if (jsonScene["environment"].is_object()) {
			m_environment = assign(m_environment, jsonScene["environment"]);
		}

		// Parse fonts
		if (jsonScene["fonts"].is_object() && world->has_system<ImGuiSystem>()) {
			const Json::object& fonts = jsonScene["fonts"].object_items();
			ImGuiSystem& imgui = world->get_system<ImGuiSystem>();
			for (auto& it : fonts) {
				ASSERT(it.second.is_object());
				string path = resources.findPath(resolvePath(pathContext, it.second["path"].string_value()));
				float size = it.second["size"].number_value();
				imgui.loadFont(it.first, path, size);
			}
		}

		// Parse sounds
		if (jsonScene["sounds"].is_object() && world->has_system<AudioSystem>()) {
			const Json::object& sounds = jsonScene["sounds"].object_items();
			AudioSystem& audio = world->get_system<AudioSystem>();
			for (auto& it : sounds) {
				if (it.second.is_string()) {
					audio.add(it.first, resources.getBinary(resolvePath(pathContext, it.second.string_value())));
				} else if (it.second.is_array()) {
					for (auto& it2 : it.second.array_items()) {
						ASSERT(it2.is_string());
						audio.add(it.first, resources.getBinary(resolvePath(pathContext, it2.string_value())));
					}
				}
			}
		}

		// Parse prefabs
		if (jsonScene["prefabs"].is_object()) {
			const Json::object& scenePrefabs = jsonScene["prefabs"].object_items();
			for (auto& it : scenePrefabs)
				prefabs[it.first] = it.second;
		}
	}

	// Parse objects
	const Json::array& objects = jsonScene.is_array() ? jsonScene.array_items() : jsonScene["objects"].array_items();
	for (uint i = 0; i < objects.size(); ++i) {
		instantiate(objects[i], resources, pathContext);
	}
}
示例#27
0
static bool _body_from_json(const Json &obj)
{
	if (!obj.is_number_integer()) return false;
	Body *body = Pi::game->GetSpace()->GetBodyByIndex(obj);
	return push_body_to_lua(body);
}
示例#28
0
/** If the configuration of this installation has not been reported for the
 *  current version, collect the hardware statistics and send it to STK's
 *  server.
 */
void reportHardwareStats()
{
    // Version of the hw report, which is stored in the DB. If new fields
    // are added, increase this version. Each STK installation will report
    // its configuration only once (per version number). So if the version
    // number is increased, a new report will be sent.
    const int report_version = 1;
    if(UserConfigParams::m_last_hw_report_version>=report_version) return;
    while(UserConfigParams::m_random_identifier==0)
    {
        RandomGenerator rg;
        UserConfigParams::m_random_identifier = rg.get(1<<30);
        user_config->saveConfig();
    }

    Json json;
#ifdef WIN32
    json.add("os_win", 1);
#else
    json.add("os_win", 0);
#endif
#ifdef __APPLE__
    json.add("os_macosx", 1);
#else
    json.add("os_macosx", 0);
#endif
#ifdef __linux__
    json.add("os_linux", 1);
    json.add("os_unix", 1);
#else
    json.add("os_linux", 0);
    json.add("os_unix", 0);
#endif
#ifdef DEBUG
    json.add("build_debug", 1);
#endif

    json.add("os_version", getOSVersion());

    unsigned int ogl_version = irr_driver->getGLSLVersion();
    unsigned int major = ogl_version/100;
    unsigned int minor = ogl_version - 100*major;
    std::string version =
        StringUtils::insertValues("%d.%d", major, minor);
    json.add("GL_SHADING_LANGUAGE_VERSION", version);

    std::string vendor, renderer, full_version;
    irr_driver->getOpenGLData(&vendor, &renderer, &full_version);
    json.add("GL_VENDOR",   vendor          );
    json.add("GL_RENDERER", renderer        );
    json.add("GL_VERSION",  full_version    );
    json.add("gfx_drv_ver", "OpenGL "+vendor);

    std::string card_name = vendor;
    if(StringUtils::startsWith(card_name, "ATI Technologies Inc."))
        card_name="ATI";
    else if (StringUtils::startsWith(card_name, "NVIDIA Corporation"))
        card_name="NVIDIA";
    else if(StringUtils::startsWith(card_name, "S3 Graphics"))
        card_name="S3";
    json.add("gfx_card", card_name+" "+renderer);

    json.add("video_xres", UserConfigParams::m_width );
    json.add("video_yres", UserConfigParams::m_height);

    int mem = getRAM();
    if(mem>0)
        json.add("ram_total", mem);

    int nr_procs = getNumProcessors();
    if(nr_procs>0)
        json.add("cpu_numprocs", nr_procs);

    json.add("GL_EXTENSIONS", getGLExtensions());
    getGLLimits(&json);
    json.finish();

    // ------------------------------------------------------------------------
    /** A small class which sends the HW report to the STK server. On
     *  completion, it will either update the last-submitted-hw-report version,
     *  or log an error message (in which case next time STK is started it
     *  wil try again to log the report).
     */
    class HWReportRequest : public Online::HTTPRequest
    {
    private:
        /** Version number of the hw report. */
        int m_version;
    public:
        HWReportRequest(int version) : Online::HTTPRequest(/*manage memory*/true, 1)
                                     , m_version(version)
        {}
        // --------------------------------------------------------------------
        /** Callback after the request has been executed.
         */
        virtual void callback()
        {
            // If the request contains incorrect data, it will not have a
            // download error, but return an error string as return value:
            if(hadDownloadError() || getData()=="<h1>Bad Request (400)</h1>")
            {
                Log::error("HW report", "Error uploading the HW report.");
                if(hadDownloadError())
                    Log::error("HW report", "%s", getDownloadErrorMessage());
                else
                    Log::error("HW report", "%s", getData().c_str());
            }
            else
            {
                Log::info("HW report", "Upload successful.");
                UserConfigParams::m_last_hw_report_version = m_version;
                // The callback is executed by the main thread, so no need
                // to worry about locks when writing the file.
                user_config->saveConfig();
            }
        }   // callback

    };   // HWReportRequest
    // ------------------------------------------------------------------------

    Online::HTTPRequest *request = new HWReportRequest(report_version);
    request->addParameter("user_id", UserConfigParams::m_random_identifier);
    request->addParameter("time", StkTime::getTimeSinceEpoch());
    request->addParameter("type", "hwdetect");
    request->addParameter("version", report_version);
    request->addParameter("data", json.toString());
    request->setURL((std::string)UserConfigParams::m_server_hw_report+"/upload/v1/");
    //request->setURL("http://127.0.0.1:8000/upload/v1/");
    request->queue();

}   // reportHardwareStats
示例#29
0
文件: load-dir.cpp 项目: caomw/picpoc
int main (int argc, char *argv[]) {
    google::InitGoogleLogging(argv[0]);
    namespace po = boost::program_options; 
    vector<string> dirs;
    string out_path;
    string list;
    size_t streams;
    double file_gbs;
    double container_mbs;
    int resize;
    int label;

    po::options_description desc("Allowed options");
    desc.add_options()
    ("help,h", "produce help message.")
    ("dir", po::value(&dirs), "")
    ("out", po::value(&out_path), "")
    ("streams,s", po::value(&streams)->default_value(20), "")
    ("file-gbs,f", po::value(&file_gbs)->default_value(4), "")
    ("container-mbs,c", po::value(&container_mbs)->default_value(200), "")
    ("resize,r", po::value(&resize)->default_value(256), "")
    ("label,l", po::value(&label)->default_value(0), "")
    ("shuffle", "")
    ("list", po::value(&list), "")
    ;   
    
    po::positional_options_description p;
    p.add("out", 1); 
    p.add("dir", -1); 

    po::variables_map vm; 
    po::store(po::command_line_parser(argc, argv).
                     options(desc).positional(p).run(), vm);
    po::notify(vm); 

    if (vm.count("help") || !out_path.size()) {
        cerr << desc;
        return 1;
    }
    vector<Line> lines;
    {
        Line line;
        line.serial = 0;
        line.label = label;
        for (string const &dir: dirs) {
            fs::recursive_directory_iterator it(fs::path(dir), fs::symlink_option::recurse), end;
            for (; it != end; ++it) {
                if (it->status().type() == fs::regular_file) {
                    line.path = it->path().string();
                    lines.push_back(line);
                    ++line.serial;
                }
            }
        }
        LOG(INFO) << "Loaded " << lines.size() << " lines." << endl;
        if (list.size()) {
            ofstream os(list.c_str());
            for (auto const &l: lines) {
                os << l.path << '\t' << l.label << endl;
            }
        }
    }

    if (vm.count("shuffle")) {
        random_shuffle(lines.begin(), lines.end());
    }

    Geometry geometry;
    geometry.n_stream = streams;
    geometry.file_size = round(file_gbs * GB);
    geometry.container_size = round(container_mbs * MB);

    {
        boost::timer::auto_cpu_timer t;
        DataSet dataset(out_path, geometry, 0);
        std::atomic<unsigned> done(0);
#pragma omp parallel for
        for (unsigned i = 0; i < lines.size(); ++i) {
            Record rec;
            string const &path = lines[i].path;
            rec.meta.label = lines[i].label;
            rec.meta.serial = lines[i].serial;
            cv::Mat image = cv::imread(path, cv::IMREAD_COLOR);
            vector<uint8_t> jpeg;
            if (image.total() == 0) {
                LOG(WARNING) << "fail to load image " << path;
                continue;
            }
            if (resize) {
                cv::Mat image2;
                cv::resize(image, image2, cv::Size(resize, resize));
                cv::imencode(".jpg", image2, jpeg);
            }
            Json json = Json::object {
                {"fname", path},
                {"ocols", image.cols},    
                {"orows", image.rows}
            };
            string extra = json.dump();
            rec.image_size = jpeg.size();
            rec.image = reinterpret_cast<char const *>(&jpeg[0]);
            rec.extra = &extra[0];
            rec.extra_size = extra.size();
#pragma omp critical
            dataset << rec;
            unsigned n = done.fetch_add(1);
            LOG_IF(INFO, n && ((n % 1000) == 0)) << n << '/' << lines.size() << " images.";
        }
    }
}
示例#30
0
文件: test.cpp 项目: Dushistov/json11
    JSON11_TEST_ASSERT(!err_failing_comment.empty());

    std::list<int> l1 { 1, 2, 3 };
    std::vector<int> l2 { 1, 2, 3 };
    std::set<int> l3 { 1, 2, 3 };
    JSON11_TEST_ASSERT(Json(l1) == Json(l2));
    JSON11_TEST_ASSERT(Json(l2) == Json(l3));

    std::map<string, string> m1 { { "k1", "v1" }, { "k2", "v2" } };
    std::unordered_map<string, string> m2 { { "k1", "v1" }, { "k2", "v2" } };
    JSON11_TEST_ASSERT(Json(m1) == Json(m2));

    // Json literals
    const Json obj = Json::object({
        { "k1", "v1" },
        { "k2", 42.0 },
        { "k3", Json::array({ "a", 123.0, true, false, nullptr }) },
    });

    std::cout << "obj: " << obj.dump() << "\n";
    JSON11_TEST_ASSERT(obj.dump() == "{\"k1\": \"v1\", \"k2\": 42, \"k3\": [\"a\", 123, true, false, null]}");

    JSON11_TEST_ASSERT(Json("a").number_value() == 0);
    JSON11_TEST_ASSERT(Json("a").string_value() == "a");
    JSON11_TEST_ASSERT(Json().number_value() == 0);

    JSON11_TEST_ASSERT(obj == json);
    JSON11_TEST_ASSERT(Json(42) == Json(42.0));
    JSON11_TEST_ASSERT(Json(42) != Json(42.1));

    const string unicode_escape_test =