Пример #1
0
static void LoadSaveData(void)
{
	char *file = GetSaveDataFile();

	if(existFile(file))
	{
		autoBlock_t *fileData = readBinary(file);
		char *fileText;
		autoList_t *lines;
		autoList_t *sVals;

		DoMask(fileData);
		fileText = unbindBlock2Line(fileData);
		fileText = replaceLine(fileText, "\r\n", "\n", 0);
		lines = tokenize(fileText, '\n');
		sVals = tokenize(getLine(lines, 1), ',');
		StageNo = toValue(refLine(sVals, 0));
		HiScore = toValue(refLine(sVals, 1));
		ExtraOpened = getCount(lines) == 3;
		memFree(fileText);
		releaseDim(lines, 1);
		releaseDim(sVals, 1);
	}
	memFree(file);
}
Пример #2
0
	void CodeGen::Visit(FuncDefNode* _node)
	{
		auto c_state = state;
		int var_id = -1;
		if (_node->name)
			var_id = state->AddVariable(_node->name->name);

		auto new_state = GenState::CreateNewState(state);

		state = new_state;

		for (auto i = _node->parameters.begin();
			i != _node->parameters.end(); ++i)
			Visit(*i);

		Visit(_node->block);
		AddInst(Instruction(VM_CODE::RETURN, 0));

		state = new_state->GetPrevState();

		auto new_fun = Context::GetGC()->New<Function>(GenState::GenerateCodePack(new_state));

		delete new_state;

		int const_id = state->AddConstant(new_fun->toValue());
		AddInst(Instruction(VM_CODE::LOAD_C, const_id));
		AddInst(Instruction(VM_CODE::CLOSURE, 0));

		if (var_id >= 0)
			AddInst(Instruction(VM_CODE::STORE_V, var_id));
	}
Пример #3
0
/*!
 * \brief  UTCからローカル時間に変換
 */
void DateTime::toLocal()
{
#if defined(_WINDOWS)
    TIME_ZONE_INFORMATION timeZone;
    GetTimeZoneInformation(&timeZone);

    int32_t bias = -timeZone.Bias / 60;
#else
    struct timezone tz;
    gettimeofday(nullptr, &tz);

    int32_t bias = -tz.tz_minuteswest / 60;
#endif

    struct tm tm;
    tm.tm_year = getYear() - 1900;
    tm.tm_mon =  getMonth() - 1;
    tm.tm_mday = getDay();
    tm.tm_hour = getHour() + bias;
    tm.tm_min =  getMinute();
    tm.tm_sec =  getSecond();
    tm.tm_yday =
    tm.tm_wday =
    tm.tm_isdst = 0;

#if defined(_WINDOWS)
    time_t time = mktime(&tm);
#else
    time_t time = mktime(&tm);
//  time_t time = timegm(&tm);
#endif
    struct tm* tmLocal = localtime(&time);

    toValue(tmLocal, getMilliSecond());
}
Пример #4
0
void RegionList::create(rt_wdb* wdbp)
{
    wmember allRegions;
    BU_LIST_INIT(&allRegions.l);

    for (std::map<std::string, Bot>::iterator it = m_list.begin();
	 it != m_list.end();
	 ++it) {
	it->second.write(wdbp);

	wmember regionContent;
	BU_LIST_INIT(&regionContent.l);
	mk_addmember(it->second.name().c_str(), &regionContent.l, 0, WMOP_UNION);

	int id = (int)toValue(it->first.c_str());

	mk_lrcomb(wdbp,
		  it->first.c_str(),
		  &regionContent,
		  1,
		  "plastic",
		  "sh=4 sp=0.5 di=0.5 re=0.1",
		  0,
		  id,
		  0,
		  0,
		  100,
		  0);
	mk_addmember(it->first.c_str(), &allRegions.l, 0, WMOP_UNION);
	mk_freemembers(&regionContent.l);
    }

    mk_lfcomb(wdbp, "all.g", &allRegions, 0);
    mk_freemembers(&allRegions.l);
}
Пример #5
0
template <> RubyValue Conversion<QRectF>::to(const QRectF &rect)
{
    static auto klass = RubyClass::fromPath("QML::Geometry::Rectangle");
    return klass.toValue().send(RUBYQML_INTERN("new"),
                                RubyValue::from(rect.x()), RubyValue::from(rect.y()),
                                RubyValue::from(rect.width()), RubyValue::from(rect.height()));
}
Пример #6
0
/*
 * For converting default values specified in nodespec
 */
Value toValue(const std::string& yamlstring, NTA_BasicType dataType)
{
    // IMemStream s(yamlstring, ::strlen(yamlstring));

    // yaml-cpp bug: append a space if it is only one character
    // This is very inefficient, but should be ok since it is
    // just used at construction time for short strings
    std::string paddedstring(yamlstring);
    if (paddedstring.size() < 2)
        paddedstring = paddedstring + " ";
    std::stringstream s(paddedstring);

    // TODO -- return value? exceptions?
    bool success = false;
    YAML::Node doc;
    try
    {
        YAML::Parser parser(s);
        success = parser.GetNextDocument(doc);
        // } catch(YAML::ParserException& e) {
    } catch(...) {
        success = false;
    }
    if (!success)
    {
        std::string ys(paddedstring);
        if (ys.size() > 30)
        {
            ys = ys.substr(0, 30) + "...";
        }
        NTA_THROW << "Unable to parse YAML string '" << ys << "' for a scalar value";
    }
    Value v = toValue(doc, dataType);
    return v;
}
Пример #7
0
/*!
 * \brief  日付時間をtime_tで設定
 */
void DateTime::setTime_t(time_t value, uint32_t milliSecond)
{
//  tm* tm = localtime(&value);
    tm* tm = gmtime(&value);

    toValue(tm, milliSecond);
}
Пример #8
0
int main(int argc, char **argv)
{
readArgs:
	if(argIs("/D"))
	{
		MaxDepth = toValue(nextArg());
		goto readArgs;
	}
	if(argIs("/W"))
	{
		Field_W = toValue(nextArg());
		goto readArgs;
	}
	if(argIs("/H"))
	{
		Field_H = toValue(nextArg());
		goto readArgs;
	}
	if(argIs("/F"))
	{
		SetField(nextArg());
		goto readArgs;
	}

	errorCase(!m_isRange(MaxDepth, 0, IMAX));
	errorCase(!m_isRange(Field_W, 1, FIELD_W_MAX));
	errorCase(!m_isRange(Field_H, 1, FIELD_H_MAX));

readCmds:
	if(argIs("/C")) // curr eval
	{
		cout("%u\n", GetEval());
		goto readCmds;
	}
	if(argIs("/N")) // next eval
	{
		uint evals[FIELD_W_MAX];
		uint index;

		GetNextEvals(evals);

		for(index = 0; index < Field_W; index++)
			cout("%u\n", evals[index]);

		goto readCmds;
	}
}
Пример #9
0
void MarginValueWidget::setMargin(float m)
{
    m_margin = m;
    double v = toValue(m, m_mode);
    m_block = true;
    setValue(v);
    m_block = false;
    emit marginChanged(m_margin);
}
void SVGAnimationElement::startedActiveInterval()
{
    m_animationValid = false;

    if (!isValid())
        return;

    if (!hasValidAttributeType())
        return;

    // These validations are appropriate for all animation modes.
    if (fastHasAttribute(SVGNames::keyPointsAttr) && m_keyPoints.size() != m_keyTimes.size())
        return;

    AnimationMode animationMode = this->animationMode();
    CalcMode calcMode = this->calcMode();
    if (calcMode == CalcModeSpline) {
        unsigned splinesCount = m_keySplines.size();
        if (!splinesCount
            || (fastHasAttribute(SVGNames::keyPointsAttr) && m_keyPoints.size() - 1 != splinesCount)
            || (animationMode == ValuesAnimation && m_values.size() - 1 != splinesCount)
            || (fastHasAttribute(SVGNames::keyTimesAttr) && m_keyTimes.size() - 1 != splinesCount))
            return;
    }

    String from = fromValue();
    String to = toValue();
    String by = byValue();
    if (animationMode == NoAnimation)
        return;
    if ((animationMode == FromToAnimation || animationMode == FromByAnimation || animationMode == ToAnimation || animationMode == ByAnimation)
        && (fastHasAttribute(SVGNames::keyPointsAttr) && fastHasAttribute(SVGNames::keyTimesAttr) && (m_keyTimes.size() < 2 || m_keyTimes.size() != m_keyPoints.size())))
        return;
    if (animationMode == FromToAnimation) {
        m_animationValid = calculateFromAndToValues(from, to);
    } else if (animationMode == ToAnimation) {
        // For to-animations the from value is the current accumulated value from lower priority animations.
        // The value is not static and is determined during the animation.
        m_animationValid = calculateFromAndToValues(emptyString(), to);
    } else if (animationMode == FromByAnimation) {
        m_animationValid = calculateFromAndByValues(from, by);
    } else if (animationMode == ByAnimation) {
        m_animationValid = calculateFromAndByValues(emptyString(), by);
    } else if (animationMode == ValuesAnimation) {
        m_animationValid = m_values.size() >= 1
            && (calcMode == CalcModePaced || !fastHasAttribute(SVGNames::keyTimesAttr) || fastHasAttribute(SVGNames::keyPointsAttr) || (m_values.size() == m_keyTimes.size()))
            && (calcMode == CalcModeDiscrete || !m_keyTimes.size() || m_keyTimes.last() == 1)
            && (calcMode != CalcModeSpline || ((m_keySplines.size() && (m_keySplines.size() == m_values.size() - 1)) || m_keySplines.size() == m_keyPoints.size() - 1))
            && (!fastHasAttribute(SVGNames::keyPointsAttr) || (m_keyTimes.size() > 1 && m_keyTimes.size() == m_keyPoints.size()));
        if (m_animationValid)
            m_animationValid = calculateToAtEndOfDurationValue(m_values.last());
        if (calcMode == CalcModePaced && m_animationValid)
            calculateKeyTimesForCalcModePaced();
    } else if (animationMode == PathAnimation) {
        m_animationValid = calcMode == CalcModePaced || !fastHasAttribute(SVGNames::keyPointsAttr) || (m_keyTimes.size() > 1 && m_keyTimes.size() == m_keyPoints.size());
    }
}
Пример #11
0
int main(int argc, char **argv)
{
	ServerDomain = nextArg();
	ServerPort = toValue(nextArg());
	MutexName = nextArg();
	StartEventName = nextArg();
	AnswerEventName = nextArg();
	ParamsFile = nextArg();
	AnswerFile = nextArg();

	errorCase(isEmptyJTkn(ServerDomain));
	errorCase(ServerPort < 1 || 0xffff < ServerPort);
	errorCase(isEmptyJTkn(MutexName));
	errorCase(isEmptyJTkn(StartEventName));
	errorCase(isEmptyJTkn(AnswerEventName));
	errorCase(isEmptyJTkn(ParamsFile));
	errorCase(isEmptyJTkn(AnswerFile));

	MutexHandle = mutexOpen(MutexName);
	StartEventHandle = eventOpen(StartEventName);
	AnswerEventHandle = eventOpen(AnswerEventName);
	StopAppEventHandle = eventOpen_x(xcout("cerulean.charlotte Factory Requester stop app event object %s %u", c_md5_makeHexHashLine(ServerDomain), ServerPort));

	if(argIs("/T"))
	{
		Serializer = TextFltr;
		Deserializer = TextFltr;
	}
	if(argIs("/TS") || argIs("/TP"))
	{
		Serializer = TextFltr;
	}
	if(argIs("/TD") || argIs("/TA"))
	{
		Deserializer = TextFltr;
	}

	if(argIs("/S"))
	{
		eventSet(StopAppEventHandle);
	}
	else if(argIs("/1"))
	{
		error(); // todo: request at once
	}
	else
	{
		MainLoop();
	}

	handleClose(MutexHandle);
	handleClose(StartEventHandle);
	handleClose(AnswerEventHandle);
	handleClose(StopAppEventHandle);
}
Пример #12
0
	CodeGen::GenState* CodeGen::GenerateDefaultState()
	{
		auto state = GenState::CreateNewState();
		auto _print_fun_ = Context::GetGC()->New<Function>(Context::_print_);
		auto _fun_id = state->AddConstant(_print_fun_->toValue());

		auto var_id = state->AddVariable(u"print");
		state->AddInstruction(VM_CODE::LOAD_C, _fun_id);
		state->AddInstruction(VM_CODE::STORE_V, var_id);
		return state;
	}
Пример #13
0
void Rigid::load( MyGUI::xml::ElementPtr node )
{
    string ms;
	VisualObject::load(node);
    if(node->findAttribute("mass", ms))
    {
        mMassDensity = toValue(ms,(dReal)1);
    }
    _init();
	_visual2physic();
}
void SVGAnimationElement::updateAnimationMode()
{
    // http://www.w3.org/TR/2001/REC-smil-animation-20010904/#AnimFuncValues
    if (hasAttribute(SVGNames::valuesAttr))
        setAnimationMode(ValuesAnimation);
    else if (!toValue().isEmpty())
        setAnimationMode(fromValue().isEmpty() ? ToAnimation : FromToAnimation);
    else if (!byValue().isEmpty())
        setAnimationMode(fromValue().isEmpty() ? ByAnimation : FromByAnimation);
    else
        setAnimationMode(NoAnimation);
}
Пример #15
0
AIDA::Dev::IDevCloud1D * iAIDA::AIDA_XMLStore::Cloud1DTranslator::createFromXML(AIDA::Dev::IDevHistogramFactory& factory)
{ 
  // read header 
  std::string title,options = emptyString;
  getObjectHeader(m_element,m_name,title,m_path,options); 
  int nMax = -1; 
  toValue(m_element.getAttributeValue("maxEntries"), nMax);


  // read annotation
  AnnotationData annoData; 
  getAnnotation(m_element,annoData); 

  // Now I can create the cloud 

  AIDA::Dev::IDevCloud1D * cloud  = 
    factory.createCloud1D( title, nMax,options );

  if (!cloud) { 
    std::cerr << " AIDA_XMLStore::Cloud1DTranslator - Cannot create Cloud1D " << std::endl; 
    return 0; 
  }

  //no need to  get statistics since for AIDA 

  // set annotation
  AIDA::IAnnotation & anno = cloud->annotation(); 
  setAnnotation(&anno,annoData); 

  // get the data 
 
  const DataXML::DataObject * dataElement = m_element.getChild("entries1d");
  if (!dataElement) return cloud; 
  //int i = 0; 
  //cout << " Number of elements " << dataElement->children().size() << endl; 
  for (std::vector<DataXML::DataObject>::const_iterator entryElement = dataElement->children().begin(); entryElement != dataElement->children().end(); ++entryElement) {  
    // need to check on the name to eliminate white spaces
    if (entryElement->name() == "entry1d") { 
      double xval,yval,zval = 0;    
      double weight = 1; 
      getCloudEntryData(*entryElement,1,xval,yval,zval,weight);
      // fill the cloud with the contents 
      //cout << " entry " << entryElement->name() << " " << i << " x " << xval << " w " << weight << endl; 
      cloud->fill(xval,weight); 
      //i++;
    }
  }

  //  std::cout << " cloud entries = " << cloud->entries() << endl; 

  return cloud; 
}
Пример #16
0
void SVGAnimationElement::startedActiveInterval()
{
    m_animationValid = false;

    if (!hasValidTarget()) {
        return;
    }

    AnimationMode animationMode = this->animationMode();
    if (animationMode == NoAnimation) {
        return;
    }
    if (animationMode == FromToAnimation) {
        m_animationValid = calculateFromAndToValues(fromValue(), toValue());
    } else if (animationMode == ToAnimation) {
        // For to-animations the from value is the current accumulated value from lower priority animations.
        // The value is not static and is determined during the animation.
        m_animationValid = calculateFromAndToValues(String(), toValue());
    } else if (animationMode == FromByAnimation) {
        m_animationValid = calculateFromAndByValues(fromValue(), byValue());
    } else if (animationMode == ByAnimation) {
        m_animationValid = calculateFromAndByValues(String(), byValue());
    } else if (animationMode == ValuesAnimation) {
        CalcMode calcMode = this->calcMode();
        m_animationValid = m_values.size() > 1
                           && (calcMode == CalcModePaced || !hasAttribute(SVGNames::keyTimesAttr) || hasAttribute(SVGNames::keyPointsAttr) || (m_values.size() == m_keyTimes.size()))
                           && (calcMode == CalcModeDiscrete || !m_keyTimes.size() || m_keyTimes.last() == 1.0)
                           && (calcMode != CalcModeSpline || (m_keySplines.size() && (m_keySplines.size() == m_values.size() - 1) || m_keySplines.size() == m_keyPoints.size() - 1))
                           && (!hasAttribute(SVGNames::keyPointsAttr) || (m_keyTimes.size() > 1 && m_keyTimes.size() == m_keyPoints.size()));
        if (calcMode == CalcModePaced && m_animationValid) {
            calculateKeyTimesForCalcModePaced();
        }
    } else if (animationMode == PathAnimation) {
        m_animationValid = calcMode() == CalcModePaced || !hasAttribute(SVGNames::keyPointsAttr) || (m_keyTimes.size() > 1 && m_keyTimes.size() == m_keyPoints.size());
    }
}
Пример #17
0
SVGAnimationElement::AnimationMode SVGAnimationElement::animationMode() const
{
    // http://www.w3.org/TR/2001/REC-smil-animation-20010904/#AnimFuncValues
    if (hasTagName(SVGNames::setTag)) {
        return ToAnimation;
    }
    if (!animationPath().isEmpty()) {
        return PathAnimation;
    }
    if (hasAttribute(SVGNames::valuesAttr)) {
        return ValuesAnimation;
    }
    if (!toValue().isEmpty()) {
        return fromValue().isEmpty() ? ToAnimation : FromToAnimation;
    }
    if (!byValue().isEmpty()) {
        return fromValue().isEmpty() ? ByAnimation : FromByAnimation;
    }
    return NoAnimation;
}
Пример #18
0
void MarginValueWidget::setMode(int m)
{
    if(m != m_mode)
    {
        m_block = true;
        m_mode = m;
        double v = toValue(m_margin, m);
        if(m == Pixels)
        {
            setPrecision(0);
            setRange(0.0, 999.0, 1.0, false);
        }
        else
        {
            setPrecision(3);
            setRange(0.0, 999.0, 0.01, false);
        }
        setValue(v);
        m_block = false;
    }
}
Пример #19
0
			bool listen(datum::time_point Time_, bool Err_, const std::string& Data_)override{
				if(Data_.size() == 0)return true;

				if(static_cast<unsigned char>(Data_[0]) == 0x00){
					if(Data_.size() != 3)return true;
					//データを温度に変換
					Value = toValue(static_cast<unsigned char>(Data_[1]), static_cast<unsigned char>(Data_[2]));
					Time = Time_;
					signal_newData(Value, Time);
					return false;
				} else if(static_cast<unsigned char>(Data_[0]) == 0x10){
					if(Data_.size() != 1)return true;
					DataModeFlagirl.set_pic(true);
					return false;
				} else if(static_cast<unsigned char>(Data_[0]) == 0x11){
					if(Data_.size() != 1)return true;
					DataModeFlagirl.set_pic(false);
					return false;
				}
				return true;
			}
Пример #20
0
/**
 * Called by setValue in the case where a user has disabled multiple file
 *loading.
 *
 * @param propValue :: A string of the allowed format, indicating the user's
 *choice of files.
 * @return A string indicating the outcome of the attempt to set the property.
 *An empty string indicates success.
 */
std::string
MultipleFileProperty::setValueAsSingleFile(const std::string &propValue) {
  // Use a slave FileProperty to do the job for us.
  FileProperty slaveFileProp("Slave", "", FileProperty::Load, m_exts,
                             Direction::Input);

  std::string error = slaveFileProp.setValue(propValue);

  if (!error.empty())
    return error;

  // Store.
  try {
    std::vector<std::vector<std::string>> result;
    toValue(slaveFileProp(), result, "", "");
    PropertyWithValue<std::vector<std::vector<std::string>>>::operator=(result);
  } catch (std::invalid_argument &except) {
    g_log.debug() << "Could not set property " << name() << ": "
                  << except.what();
    return except.what();
  }
  return "";
}
Пример #21
0
std::string getJSONType(const Convertible& value) {
    if (isUndefined(value)) {
        return "null";
    }
    if (isArray(value)) {
        return "array";
    }
    if (isObject(value)) {
        return "object";
    }
    optional<mbgl::Value> v = toValue(value);

    // Since we've already checked the non-atomic types above, value must then
    // be a string, number, or boolean -- thus, assume that the toValue()
    // conversion succeeds.
    assert(v);

    return v->match(
        [&] (const std::string&) { return "string"; },
        [&] (bool) { return "boolean"; },
        [&] (auto) { return "number"; }
    );
}
Пример #22
0
/**
 * Called by setValue in the case where a user has disabled multiple file
 *loading.
 *
 * @param propValue :: A string of the allowed format, indicating the user's
 *choice of files.
 * @return A string indicating the outcome of the attempt to set the property.
 *An empty string indicates success.
 */
std::string
MultipleFileProperty::setValueAsSingleFile(const std::string &propValue) {
  // if value is unchanged use the cached version
  if ((propValue == m_oldPropValue) && (!m_oldFoundValue.empty())) {
    PropertyWithValue<std::vector<std::vector<std::string>>>::operator=(
        m_oldFoundValue);
    return SUCCESS;
  }

  // Use a slave FileProperty to do the job for us.
  FileProperty slaveFileProp("Slave", "", FileProperty::Load, m_exts,
                             Direction::Input);

  std::string error = slaveFileProp.setValue(propValue);

  if (!error.empty())
    return error;

  // Store.
  std::vector<std::vector<std::string>> foundFiles;
  try {
    toValue(slaveFileProp(), foundFiles, "", "");
    PropertyWithValue<std::vector<std::vector<std::string>>>::operator=(
        foundFiles);
  } catch (std::invalid_argument &except) {
    g_log.debug() << "Could not set property " << name() << ": "
                  << except.what();
    return except.what();
  }

  // cache the new version of things
  m_oldPropValue = propValue;
  m_oldFoundValue = std::move(foundFiles);

  return SUCCESS;
}
Пример #23
0
/*
 * For converting param specs for Regions and LinkPolicies
 */
ValueMap toValueMap(const char *yamlstring,
                    Collection<ParameterSpec> &parameters,
                    const std::string &nodeType,
                    const std::string &regionName) {

  ValueMap vm;

  // special value that applies to all regions.
  ParameterSpec dim_spec("Buffer dimensions for region's global dimensions. "
                    "Syntax: {dim: [2,3]}",  // description
	                  NTA_BasicType_UInt32,
							      0,                         // elementCount (an array of unknown size)
							      "",                        // constraints
							      "",                        // defaultValue
							      ParameterSpec::ReadWriteAccess);


  std::string paddedstring(yamlstring);
  // TODO: strip white space to determine if empty
  bool empty = (paddedstring.size() == 0);

  // TODO: utf-8 compatible?
  const YAML::Node doc = YAML::Load(paddedstring);
  if(!empty) {
    // A ValueMap is specified as a dictionary
    if (doc.Type() != YAML::NodeType::Map) {
      std::string ys(yamlstring);
      if (ys.size() > 30) {
        ys = ys.substr(0, 30) + "...";
      }
      NTA_THROW
          << "YAML string '" << ys
          << "' does not not specify a dictionary of key-value pairs. "
          << "Region and Link parameters must be specified as a dictionary";
    }
  }
  // Grab each value out of the YAML dictionary and put into the ValueMap
  // if it is allowed by the nodespec.
  for (auto i = doc.begin(); i != doc.end(); i++)
  {
    ParameterSpec ps;

    const auto key = i->first.as<std::string>();
    if (key == "dim")
      ps = dim_spec;
    else {
      if (!parameters.contains(key))
      {
        std::stringstream ss;
        for (UInt j = 0; j < parameters.getCount(); j++){
          ss << "   " << parameters.getByIndex(j).first << "\n";
        }

        if (nodeType == std::string("")) {
          NTA_THROW << "Unknown parameter '" << key << "'\n"
                    << "Valid parameters are:\n" << ss.str();
        } else {
          NTA_CHECK(regionName != std::string(""));
          NTA_THROW << "Unknown parameter '" << key << "' for region '"
                    << regionName << "' of type '" << nodeType << "'\n"
                    << "Valid parameters are:\n"
                    << ss.str();
        }
      }
      ps = parameters.getByName(key); // makes a copy of ParameterSpec
    }
    if (vm.contains(key))
        NTA_THROW << "Parameter '" << key << "' specified more than once in YAML document";
    try
    {
      if (ps.accessMode == ParameterSpec::ReadOnlyAccess) {
        NTA_THROW << "Parameter '" << key << "'. This is ReadOnly access. Cannot be set.";
      }
      Value v = toValue(i->second, ps.dataType);
      if (v.isScalar() && ps.count != 1)
      {
        NTA_THROW << "Parameter '" << key << "'. Bad value in runtime parameters. Expected array value but got scalar value";
      }
      if (!v.isScalar() && ps.count == 1)
      {
        NTA_THROW << "Parameter '" << key << "'. Bad value in runtime parameters. Expected scalar value but got array value";
      }
      vm.add(key, v);
    } catch (std::runtime_error &e) {
      NTA_THROW << "Unable to set parameter '" << key << "'. " << e.what();
    }
  } //end for

  // Populate ValueMap with default values if they were not specified in the YAML dictionary.
  for (size_t i = 0; i < parameters.getCount(); i++)
  {
    const std::pair<std::string, ParameterSpec>& item = parameters.getByIndex(i);
    if (!vm.contains(item.first))
    {
      const ParameterSpec & ps = item.second;
      if (ps.defaultValue != "")
      {
        // TODO: This check should be uncommented after dropping NuPIC 1.x nodes (which don't comply) //FIXME try this
        // if (ps.accessMode != ParameterSpec::CreateAccess)
        // {
        //   NTA_THROW << "Default value for non-create parameter: " << item.first;
        // }

        try {
#ifdef YAMLDEBUG
          NTA_DEBUG << "Adding default value '" << ps.defaultValue
                    << "' to parameter " << item.first << " of type "
                    << BasicType::getName(ps.dataType) << " count " << ps.count;
#endif
          // NOTE: this can handle both scalers and arrays
          //       Arrays MUST be in Yaml sequence format even if one element.
          //       i.e.  [1,2,3]
          Value v = toValue(ps.defaultValue, ps.dataType);
          if (v.isScalar() && ps.count != 1)
          {
            NTA_THROW << "Parameter '" << item.first << "'. Bad default value in spec. Expected array value but got scalar value";
          }
          if (!v.isScalar() && ps.count == 1)
          {
            NTA_THROW << "Parameter '" << item.first << "'. Bad default value in spec. Expected scalar value but got array value";
          }
          vm.add(item.first, v);
        } catch (...) {
          NTA_THROW << "Unable to set default value for item '" << item.first
                    << "' of datatype " << BasicType::getName(ps.dataType)
                    << " with value '" << ps.defaultValue << "'";
        }
      }
    }
  }

  return vm;
}
Пример #24
0
template <> RubyValue Conversion<QPointF>::to(const QPointF &point)
{
    static auto klass = RubyClass::fromPath("QML::Geometry::Point");
    return klass.toValue().send(RUBYQML_INTERN("new"), RubyValue::from(point.x()), RubyValue::from(point.y()));
}
Пример #25
0
/*
 * For converting param specs for Regions and LinkPolicies
 */
ValueMap toValueMap(const char* yamlstring,
                    Collection<ParameterSpec>& parameters,
                    const std::string & nodeType,
                    const std::string & regionName)
{

    ValueMap vm;

    // yaml-cpp bug: append a space if it is only one character
    // This is very inefficient, but should be ok since it is
    // just used at construction time for short strings
    std::string paddedstring(yamlstring);
    // TODO: strip white space to determine if empty
    bool empty = (paddedstring.size() == 0);

    if (paddedstring.size() < 2)
        paddedstring = paddedstring + " ";
    std::stringstream s(paddedstring);
    // IMemStream s(yamlstring, ::strlen(yamlstring));

    // TODO: utf-8 compatible?
    YAML::Node doc;
    if (!empty)
    {
        YAML::Parser parser(s);
        bool success = parser.GetNextDocument(doc);

        if (!success)
            NTA_THROW << "Unable to find document in YAML string";

        // A ValueMap is specified as a dictionary
        if (doc.Type() != YAML::NodeType::Map)
        {
            std::string ys(yamlstring);
            if (ys.size() > 30)
            {
                ys = ys.substr(0, 30) + "...";
            }
            NTA_THROW << "YAML string '" << ys
                      << "' does not not specify a dictionary of key-value pairs. "
                      << "Region and Link parameters must be specified at a dictionary";
        }
    }

    // Grab each value out of the YAML dictionary and put into the ValueMap
    // if it is allowed by the nodespec.
    YAML::Iterator i;
    for (i = doc.begin(); i != doc.end(); i++)
    {
        const std::string key = i.first().to<std::string>();
        if (!parameters.contains(key))
        {
            std::stringstream ss;
            for (UInt j = 0; j < parameters.getCount(); j++)
            {
                ss << "   " << parameters.getByIndex(j).first << "\n";
            }

            if (nodeType == std::string(""))
            {
                NTA_THROW << "Unknown parameter '" << key << "'\n"
                          << "Valid parameters are:\n" << ss.str();
            }
            else
            {
                NTA_CHECK(regionName != std::string(""));
                NTA_THROW << "Unknown parameter '" << key << "' for region '"
                          << regionName << "' of type '" << nodeType << "'\n"
                          << "Valid parameters are:\n" << ss.str();
            }
        }
        if (vm.contains(key))
            NTA_THROW << "Parameter '" << key << "' specified more than once in YAML document";
        ParameterSpec spec = parameters.getByName(key);
        try
        {
            Value v = toValue(i.second(), spec.dataType);
            if (v.isScalar() && spec.count != 1)
            {
                throw std::runtime_error("Expected array value but got scalar value");
            }
            if (!v.isScalar() && spec.count == 1)
            {
                throw std::runtime_error("Expected scalar value but got array value");
            }
            vm.add(key, v);
        } catch (std::runtime_error& e) {
            NTA_THROW << "Unable to set parameter '" << key << "'. " << e.what();
        }
    }

    // Populate ValueMap with default values if they were not specified in the YAML dictionary.
    for (size_t i = 0; i < parameters.getCount(); i++)
    {
        std::pair<std::string, ParameterSpec>& item = parameters.getByIndex(i);
        if (!vm.contains(item.first))
        {
            ParameterSpec & ps = item.second;
            if (ps.defaultValue != "")
            {
                // TODO: This check should be uncommented after dropping NuPIC 1.x nodes (which don't comply)
                // if (ps.accessMode != ParameterSpec::CreateAccess)
                // {
                //   NTA_THROW << "Default value for non-create parameter: " << item.first;
                // }

                try {
#ifdef YAMLDEBUG
                    NTA_DEBUG << "Adding default value '" << ps.defaultValue
                              << "' to parameter " << item.first
                              << " of type " << BasicType::getName(ps.dataType)
                              << " count " << ps.count;
#endif
                    Value v = toValue(ps.defaultValue, ps.dataType);
                    vm.add(item.first, v);
                } catch (...) {
                    NTA_THROW << "Unable to set default value for item '"
                              << item.first << "' of datatype "
                              << BasicType::getName(ps.dataType)
                              <<" with value '" << ps.defaultValue << "'";
                }
            }
        }
    }

    return vm;
}
Пример #26
0
template <> RubyValue Conversion<QSizeF>::to(const QSizeF &size)
{
    static auto klass = RubyClass::fromPath("QML::Geometry::Size");
    return klass.toValue().send(RUBYQML_INTERN("new"), RubyValue::from(size.width()), RubyValue::from(size.height()));
}
Пример #27
0
Backend::FieldInfo toFieldInfo(const Timestamp uts)
{
  return Backend::FieldInfo{ Backend::Tag{"But::Timestamp"}, toValue(uts) };
}
Пример #28
0
Value Symbol::toValue(const std::shared_ptr<Project> &project,
                      Flags<ToStringFlag> toStringFlags,
                      Flags<Location::ToStringFlag> locationToStringFlags,
                      const Set<String> &pieceFilters) const
{
    auto filterPiece = [&pieceFilters](const char *name) { return pieceFilters.isEmpty() || pieceFilters.contains(name); };
    std::function<Value(const Symbol &, Flags<ToStringFlag>)> toValue = [&](const Symbol &symbol, Flags<ToStringFlag> f) {
        Value ret;
        auto formatLocation = [locationToStringFlags,&filterPiece, &ret](Location loc, const char *key, const char *ctxKey,
                                                                         const char *keyFilter = 0,
                                                                         const char *ctxKeyFilter = 0,
                                                                         Value *val = 0) {
            if (!val)
                val = &ret;
            if (filterPiece(keyFilter ? keyFilter : key))
                (*val)[key] = loc.toString(locationToStringFlags & ~Location::ShowContext);
            if (locationToStringFlags & Location::ShowContext && filterPiece(ctxKeyFilter ? ctxKeyFilter : ctxKey)) {
                (*val)[ctxKey] = loc.context(locationToStringFlags);
            }
        };
        if (!symbol.location.isNull()) {
            formatLocation(symbol.location, "location", "context");
        }
        if (!symbol.isNull()) {
            if (symbol.argumentUsage.index != String::npos) {
                formatLocation(symbol.argumentUsage.invocation, "invocation", "invocationContext", 0, "invocationcontext");
                if (filterPiece("invokedfunction"))
                    ret["invokedFunction"] = symbol.argumentUsage.invokedFunction.toString(locationToStringFlags);
                formatLocation(symbol.argumentUsage.argument.location, "functionArgumentLocation", "functionArgumentLocationContext",
                               "functionargumentlocation", "functionargumentlocationcontext");
                if (filterPiece("functionargumentcursor"))
                    ret["functionArgumentCursor"] = symbol.argumentUsage.argument.cursor.toString(locationToStringFlags);
                if (filterPiece("functionargumentlength"))
                    ret["functionArgumentLength"] = symbol.argumentUsage.argument.length;
                if (filterPiece("argumentindex"))
                    ret["argumentIndex"] = symbol.argumentUsage.index;
            }
            if (!symbol.symbolName.isEmpty() && filterPiece("symbolname"))
                ret["symbolName"] = symbol.symbolName;
            if (!symbol.usr.isEmpty() && filterPiece("usr"))
                ret["usr"] = symbol.usr;
            if (filterPiece("type")) {
                if (!symbol.typeName.isEmpty()) {
                    ret["type"] = symbol.typeName;
                } else if (symbol.type != CXType_Invalid) {
                    String str;
                    Log(&str) << symbol.type;
                    ret["type"] = str;
                }
            }

            if (!symbol.baseClasses.isEmpty() && filterPiece("baseclasses"))
                ret["baseClasses"] = symbol.baseClasses;
            if (!symbol.arguments.isEmpty() && filterPiece("arguments")) {
                Value args;
                for (const auto &arg : symbol.arguments) {
                    Value a;
                    formatLocation(arg.location, "location", "context", "arguments", "arguments", &a);
                    formatLocation(arg.location, "cursor", "cursorContext", "arguments", "arguments", &a);
                    a["length"] = arg.length;
                    args.push_back(a);
                }
                ret["arguments"] = args;
            }
            if (filterPiece("symbollength"))
                ret["symbolLength"] = symbol.symbolLength;
            if (filterPiece("kind")) {
                String str;
                Log(&str) << symbol.kind;
                ret["kind"] = str;
            }
            if (filterPiece("linkage")) {
                String str;
                Log(&str) << symbol.linkage;
                ret["linkage"] = str;
            }

            if (!symbol.briefComment.isEmpty() && filterPiece("briefcomment"))
                ret["briefComment"] = symbol.briefComment;
            if (!symbol.xmlComment.isEmpty() && filterPiece("xmlcomment"))
                ret["xmlComment"] = symbol.xmlComment;
            if (filterPiece("range")) {
                ret["startLine"] = symbol.startLine;
                ret["startColumn"] = symbol.startColumn;
                ret["endLine"] = symbol.endLine;
                ret["endColumn"] = symbol.endColumn;
            }
            if (symbol.size && filterPiece("sizeof"))
                ret["sizeof"] = symbol.size;
            if (symbol.fieldOffset >= 0 && filterPiece("fieldoffset"))
                ret["fieldOffset"] = symbol.fieldOffset;
            if (symbol.alignment >= 0 && filterPiece("alignment"))
                ret["alignment"] = symbol.alignment;
            if (symbol.kind == CXCursor_EnumConstantDecl && filterPiece("enumvalue"))
                ret["enumValue"] = symbol.enumValue;
            if (symbol.isDefinition()) {
                if (filterPiece("definition"))
                    ret["definition"] = true;
                if (RTags::isFunction(symbol.kind) && filterPiece("stackcost"))
                    ret["stackCost"] = symbol.stackCost;
            } else if (symbol.isReference() && filterPiece("reference")) {
                ret["reference"] = true;
            }
            if (symbol.isContainer() && filterPiece("container"))
                ret["container"] = true;
            if ((symbol.flags & Symbol::PureVirtualMethod) == Symbol::PureVirtualMethod && filterPiece("purevirtual"))
                ret["purevirtual"] = true;
            if (symbol.flags & Symbol::VirtualMethod && filterPiece("virtual"))
                ret["virtual"] = true;
            if (symbol.flags & Symbol::ConstMethod && filterPiece("constmethod"))
                ret["constmethod"] = true;
            if (symbol.flags & Symbol::StaticMethod && filterPiece("staticmethod"))
                ret["staticmethod"] = true;
            if (symbol.flags & Symbol::Variadic && filterPiece("variadic"))
                ret["variadic"] = true;
            if (symbol.flags & Symbol::Auto && filterPiece("auto"))
                ret["auto"] = true;
            if (symbol.flags & Symbol::MacroExpansion && filterPiece("macroexpansion"))
                ret["macroexpansion"] = true;
            if (symbol.flags & Symbol::TemplateSpecialization && filterPiece("templatespecialization"))
                ret["templatespecialization"] = true;
            if (symbol.flags & Symbol::TemplateReference && filterPiece("templatereference"))
                ret["templatereference"] = true;
            if (f & IncludeTargets) {
                const auto targets = project->findTargets(symbol);
                if (!targets.isEmpty() && filterPiece("targets")) {
                    Value t;
                    for (const auto &target : targets) {
                        t.push_back(toValue(target, NullFlags));
                    }
                    ret["targets"] = t;
                }
            }
            if (f & IncludeReferences) {
                const auto references = project->findCallers(symbol);
                if (!references.isEmpty() && filterPiece("references")) {
                    Value r;
                    for (const auto &ref : references) {
                        r.push_back(toValue(ref, NullFlags));
                    }
                    ret["references"] = r;
                }
            }
            if (f & IncludeBaseClasses && filterPiece("baseclasses")) {
                List<Value> b;
                for (const auto &base : symbol.baseClasses) {
                    for (const Symbol &s : project->findByUsr(base, symbol.location.fileId(), Project::ArgDependsOn)) {
                        b.append(toValue(s, NullFlags));
                        break;
                    }
                }
                if (!baseClasses.isEmpty()) {
                    ret["baseClasses"] = b;
                }
            }

            if ((f & IncludeParents && filterPiece("parent"))
                || (f & (IncludeContainingFunction) && filterPiece("cf"))
                || (f & (IncludeContainingFunctionLocation) && (filterPiece("cfl") || filterPiece("cflcontext")))) {
                auto syms = project->openSymbols(symbol.location.fileId());
                uint32_t idx = -1;
                if (syms) {
                    idx = syms->lowerBound(symbol.location);
                    if (idx == std::numeric_limits<uint32_t>::max()) {
                        idx = syms->count() - 1;
                    }
                }
                const unsigned int line = symbol.location.line();
                const unsigned int column = symbol.location.column();
                while (idx-- > 0) {
                    const Symbol s = syms->valueAt(idx);
                    if (s.isDefinition()
                        && s.isContainer()
                        && comparePosition(line, column, s.startLine, s.startColumn) >= 0
                        && comparePosition(line, column, s.endLine, s.endColumn) <= 0) {
                        if (f & IncludeContainingFunctionLocation) {
                            formatLocation(s.location, "cfl", "cflcontext");
                        }
                        if (f & IncludeContainingFunction && filterPiece("cf"))
                            ret["cf"] = s.symbolName;
                        if (f & IncludeParents && filterPiece("parent"))
                            ret["parent"] = toValue(s, IncludeParents);
                        break;
                    }
                }
            }
        }
        return ret;
    };
    return toValue(*this, toStringFlags);
}
Пример #29
0
/*
 * For converting default values specified in nodespec string
 */
Value toValue(const std::string& yamlstring, NTA_BasicType dataType)
{
  // TODO -- return value? exceptions?
  const YAML::Node doc = YAML::Load(yamlstring);
  return toValue(doc, dataType);
}
Пример #30
0
Value Symbol::toValue(const std::shared_ptr<Project> &project,
                      Flags<ToStringFlag> toStringFlags,
                      Flags<Location::ToStringFlag> locationToStringFlags) const
{
    std::function<Value(const Symbol &, Flags<ToStringFlag>)> toValue = [&](const Symbol &symbol, Flags<ToStringFlag> f) {
        Value ret;
        if (!symbol.isNull()) {
            ret["location"] = symbol.location.toString(locationToStringFlags);
            if (symbol.argumentUsage.index != String::npos) {
                ret["invocation"] = symbol.argumentUsage.invocation.toString(locationToStringFlags);
                ret["invokedFunction"] = symbol.argumentUsage.invokedFunction.toString(locationToStringFlags);
                ret["functionArgumentLocation"] = symbol.argumentUsage.argument.location.toString(locationToStringFlags);
                ret["functionArgumentCursor"] = symbol.argumentUsage.argument.cursor.toString(locationToStringFlags);
                ret["functionArgumentLength"] = symbol.argumentUsage.argument.length;
                ret["argumentIndex"] = symbol.argumentUsage.index;
            }
            if (!symbol.symbolName.isEmpty())
                ret["symbolName"] = symbol.symbolName;
            if (!symbol.usr.isEmpty())
                ret["usr"] = symbol.usr;
            if (!symbol.typeName.isEmpty()) {
                ret["type"] = symbol.typeName;
            } else if (symbol.type != CXType_Invalid) {
                String str;
                Log(&str) << symbol.type;
                ret["type"] = str;
            }

            if (!symbol.baseClasses.isEmpty())
                ret["baseClasses"] = symbol.baseClasses;
            if (!symbol.arguments.isEmpty()) {
                Value args;
                for (const auto &arg : symbol.arguments) {
                    Value a;
                    a["location"] = arg.location.toString(locationToStringFlags);
                    a["cursor"] = arg.cursor.toString(locationToStringFlags);
                    a["length"] = arg.length;
                    args.push_back(a);
                }
                ret["arguments"] = args;
            }
            ret["symbolLength"] = symbol.symbolLength;
            {
                String str;
                Log(&str) << symbol.kind;
                ret["kind"] = str;
            }
            {
                String str;
                Log(&str) << symbol.linkage;
                ret["linkage"] = str;
            }

            if (!symbol.briefComment.isEmpty())
                ret["briefComment"] = symbol.briefComment;
            if (!symbol.xmlComment.isEmpty())
                ret["xmlComment"] = symbol.xmlComment;
            ret["startLine"] = symbol.startLine;
            ret["startColumn"] = symbol.startColumn;
            ret["endLine"] = symbol.endLine;
            ret["endColumn"] = symbol.endColumn;
            if (symbol.size > 0)
                ret["sizeof"] = symbol.size;
            if (symbol.fieldOffset > 0)
                ret["fieldOffset"] = symbol.fieldOffset;
            if (symbol.alignment > 0)
                ret["alignment"] = symbol.alignment;
            if (symbol.kind == CXCursor_EnumConstantDecl)
                ret["enumValue"] = symbol.enumValue;
            if (symbol.isDefinition()) {
                ret["definition"] = true;
                if (RTags::isFunction(symbol.kind))
                    ret["stackCost"] = symbol.stackCost;
            } else if (symbol.isReference()) {
                ret["reference"] = true;
            }
            if (symbol.isContainer())
                ret["container"] = true;
            if ((symbol.flags & Symbol::PureVirtualMethod) == Symbol::PureVirtualMethod)
                ret["purevirtual"] = true;
            if (symbol.flags & Symbol::VirtualMethod)
                ret["virtual"] = true;
            if (symbol.flags & Symbol::ConstMethod)
                ret["constmethod"] = true;
            if (symbol.flags & Symbol::StaticMethod)
                ret["staticmethod"] = true;
            if (symbol.flags & Symbol::Variadic)
                ret["variadic"] = true;
            if (symbol.flags & Symbol::Auto)
                ret["auto"] = true;
            if (symbol.flags & Symbol::AutoRef)
                ret["autoref"] = true;
            if (symbol.flags & Symbol::MacroExpansion)
                ret["macroexpansion"] = true;
            if (symbol.flags & Symbol::TemplateSpecialization)
                ret["templatespecialization"] = true;
            if (f & IncludeTargets) {
                const auto targets = project->findTargets(symbol);
                if (!targets.isEmpty()) {
                    Value t;
                    for (const auto &target : targets) {
                        t.push_back(toValue(target, NullFlags));
                    }
                    ret["targets"] = t;
                }
            }
            if (f & IncludeReferences) {
                const auto references = project->findCallers(symbol);
                if (!references.isEmpty()) {
                    Value r;
                    for (const auto &ref : references) {
                        r.push_back(toValue(ref, NullFlags));
                    }
                    ret["references"] = r;
                }
            }
            if (f & IncludeBaseClasses) {
                List<Value> b;
                for (const auto &base : symbol.baseClasses) {
                    for (const Symbol &s : project->findByUsr(base, symbol.location.fileId(), Project::ArgDependsOn, symbol.location)) {
                        b.append(toValue(s, NullFlags));
                        break;
                    }
                }
                if (!baseClasses.isEmpty()) {
                    ret["baseClasses"] = b;
                }
            }

            if (f & IncludeParents) {
                auto syms = project->openSymbols(symbol.location.fileId());
                uint32_t idx = -1;
                if (syms) {
                    idx = syms->lowerBound(symbol.location);
                    if (idx == std::numeric_limits<uint32_t>::max()) {
                        idx = syms->count() - 1;
                    }
                }
                const unsigned int line = symbol.location.line();
                const unsigned int column = symbol.location.column();
                while (idx-- > 0) {
                    const Symbol s = syms->valueAt(idx);
                    if (s.isDefinition()
                        && s.isContainer()
                        && comparePosition(line, column, s.startLine, s.startColumn) >= 0
                        && comparePosition(line, column, s.endLine, s.endColumn) <= 0) {
                        ret["parent"] = toValue(s, IncludeParents);
                        break;
                    }
                }
            }
        }
        return ret;
    };
    return toValue(*this, toStringFlags);
}