Example #1
0
void StateGraphViewerPanel::OnMouseOver(std::string const &NodeID)
{
  auto const Unescaped = wxURI::Unescape(NodeID).ToStdString();
  auto const SpacePos = Unescaped.find(' ');
  auto const NodeType = Unescaped.substr(0, SpacePos);
  
  std::shared_ptr<Displayable const> NodeDisplayable;

  if (NodeType == "value") {
    auto const NodeData = Unescaped.substr(SpacePos + 1);
    auto const ID = seec::callbackfs::ParseImpl<uintptr_t>::impl(NodeData);
    auto const &Value = *reinterpret_cast<seec::cm::Value const *>(ID);
    NodeDisplayable = std::make_shared<DisplayableValue>(Value);
  }
  else if (NodeType == "dereference") {
    auto const NodeData = Unescaped.substr(SpacePos + 1);
    auto const ID = seec::callbackfs::ParseImpl<uintptr_t>::impl(NodeData);
    auto const &Ptr = *reinterpret_cast<seec::cm::ValueOfPointer const *>(ID);
    NodeDisplayable = std::make_shared<DisplayableDereference>(Ptr);
  }
  else if (NodeType == "function") {
    auto const NodeData = Unescaped.substr(SpacePos + 1);
    auto const ID = seec::callbackfs::ParseImpl<uintptr_t>::impl(NodeData);
    auto &Fn = *reinterpret_cast<seec::cm::FunctionState *>(ID);
    NodeDisplayable = std::make_shared<DisplayableFunctionState>(Fn);
  }
  else if (NodeType == "local") {
    auto const NodeData = Unescaped.substr(SpacePos + 1);
    auto const ID = seec::callbackfs::ParseImpl<uintptr_t>::impl(NodeData);
    auto const &Local = *reinterpret_cast<seec::cm::LocalState const *>(ID);
    NodeDisplayable = std::make_shared<DisplayableLocalState>(Local);
  }
  else if (NodeType == "param") {
    auto const NodeData = Unescaped.substr(SpacePos + 1);
    auto const ID = seec::callbackfs::ParseImpl<uintptr_t>::impl(NodeData);
    auto const &Param = *reinterpret_cast<seec::cm::ParamState const *>(ID);
    NodeDisplayable = std::make_shared<DisplayableParamState>(Param);
  }
  else if (NodeType == "global") {
    auto const NodeData = Unescaped.substr(SpacePos + 1);
    auto const ID = seec::callbackfs::ParseImpl<uintptr_t>::impl(NodeData);
    auto const &GV = *reinterpret_cast<seec::cm::GlobalVariable const *>(ID);
    NodeDisplayable = std::make_shared<DisplayableGlobalVariable>(GV);
  }
  else if (NodeType == "area") {
    auto const NodeData = Unescaped.substr(SpacePos + 1);
    auto const Comma1 = NodeData.find(',');
    if (Comma1 == std::string::npos) {
      wxLogDebug("Bad area node data: %s", wxString{NodeData});
      return;
    }
    
    auto const Comma2 = NodeData.find(',', Comma1 + 1);
    if (Comma2 == std::string::npos) {
      wxLogDebug("Bad area node data: %s", wxString{NodeData});
      return;
    }
    
    auto const StrStart = NodeData.substr(0,          Comma1);
    auto const StrEnd   = NodeData.substr(Comma1 + 1, Comma2 - Comma1);
    auto const StrID    = NodeData.substr(Comma2 + 1);
    
    auto const Start = seec::callbackfs::ParseImpl<uint64_t>::impl(StrStart);
    auto const End   = seec::callbackfs::ParseImpl<uint64_t>::impl(StrEnd);
    auto const ID    = seec::callbackfs::ParseImpl<uintptr_t>::impl(StrID);
    auto const &Ptr  = *reinterpret_cast<seec::cm::ValueOfPointer const *>(ID);
    
    NodeDisplayable = std::make_shared<DisplayableReferencedArea>
                                      (Start, End, Ptr);
  }
  else if (NodeType != "null"){
    wxLogDebug("Bad node: %s", wxString{Unescaped});
    return;
  }
  
  // If the node was Displayable, push the event to the GUI thread.
  MouseOverDisplayableEvent Ev {
    SEEC_EV_MOUSE_OVER_DISPLAYABLE,
    this->GetId(),
    std::move(NodeDisplayable)
  };
  
  Ev.SetEventObject(this);
    
  this->GetEventHandler()->AddPendingEvent(Ev);
}
Example #2
0
/**
 *  This follows the Java URI algorithm:
 *   1. All "." segments are removed.
 *   2. If a ".." segment is preceded by a non-".." segment
 *          then both of these segments are removed. This step
 *          is repeated until it is no longer applicable.
 *   3. If the path is relative, and if its first segment
 *          contains a colon character (':'), then a "." segment
 *          is prepended. This prevents a relative URI with a path
 *          such as "a:b/c/d" from later being re-parsed as an
 *          opaque URI with a scheme of "a" and a scheme-specific
 *          part of "b/c/d". (Deviation from RFC 2396)
 */
void URI::normalize()
{
    std::vector< std::vector<int> > segments;

    //## Collect segments
    if (path.size()<2)
        return;
    bool abs = false;
    int pos=0;
    int len = (int) path.size();

    if (path[0]=='/')
        {
        abs = true;
        pos++;
        }

    while (pos < len)
        {
        int pos2 = find(path, '/', pos);
        if (pos2 < 0)
            {
            std::vector<int> seg = substr(path, pos, path.size()-pos);
            //printf("last segment:%s\n", toStr(seg).c_str());
            segments.push_back(seg);
            break;
            }
        if (pos2>pos)
            {
            std::vector<int> seg = substr(path, pos, pos2-pos);
            //printf("segment:%s\n", toStr(seg).c_str());
            segments.push_back(seg);
            }
        pos = pos2;
        pos++;
        }

    //## Clean up (normalize) segments
    bool edited = false;
    std::vector< std::vector<int> >::iterator iter;
    for (iter=segments.begin() ; iter!=segments.end() ; )
        {
        std::vector<int> s = *iter;
        if (sequ(s,"."))
            {
            iter = segments.erase(iter);
            edited = true;
            }
        else if (sequ(s, "..") && iter != segments.begin() &&
                 !sequ(*(iter-1), ".."))
            {
            --iter; //back up, then erase two entries
            iter = segments.erase(iter);
            iter = segments.erase(iter);
            edited = true;
            }
        else
            ++iter;
        }

    //## Rebuild path, if necessary
    if (edited)
        {
        path.clear();
        if (abs)
            {
            path.push_back('/');
            }
        std::vector< std::vector<int> >::iterator iter;
        for (iter=segments.begin() ; iter!=segments.end() ; ++iter)
            {
            if (iter != segments.begin())
                path.push_back('/');
            std::vector<int> seg = *iter;
            for (unsigned int i = 0; i<seg.size() ; i++)
                path.push_back(seg[i]);
            }
        }

}
Example #3
0
void
MultivariateModel
::UpdateModel(const Realizations &R, int Type,
            const std::vector<std::string, std::allocator<std::string>> Names)
{
  /// Given a list of names (which in fact corresponds to the variables that have potentially changed),
  /// the function updates the parameters associated to these names
  
  
  /// Possible parameters to update, depending on the name being in "vect<> Names"
  bool ComputeG = false;
  bool ComputeDelta = false;
  bool ComputeBasis = false;
  bool ComputeA = false;
  bool ComputeSpaceShift = false;
  bool ComputeBlock_ = false;
  bool IndividualOnly = (Type > -1);
  
  /// Parameters to update, depending on the names called
  for(auto it = Names.begin(); it != Names.end(); ++it)
  {
    std::string Name = it->substr(0, it->find_first_of("#"));
    if(Name == "None")
    {
      continue;
    }
    else if(Name == "Ksi" or Name == "Tau") 
    {
      continue;
    }
    else if("G" == Name)
    {
      IndividualOnly = false;
      ComputeBasis = true;
      ComputeA = true;
      ComputeSpaceShift = true;
      ComputeBlock_ = true;
    }
    else if("Delta" == Name)
    {
      IndividualOnly = false;
      ComputeBasis = true;
      ComputeA = true;
      ComputeSpaceShift = true;
      ComputeBlock_ = true;
    }
    else if("Beta" == Name) 
    {
      IndividualOnly = false;
      ComputeA = true;
      ComputeSpaceShift = true;
    }
    else if("S" == Name)
    {
      ComputeSpaceShift = true;
    }
    else if("All" == Name)
    {
      ComputeSubjectTimePoint(R, -1);
      IndividualOnly = false;
      ComputeG = true;
      ComputeDelta = true;
      ComputeBasis = true;
      ComputeA = true;
      ComputeSpaceShift = true;
      ComputeBlock_ = true;
    } 
    else
    {
      std::cerr << "The realization does not exist in the multivariate model > update model" << std::endl;
    }
  }
  
  
  // TODO : To parse it even faster, update just the coordinates within the names
  if(IndividualOnly) ComputeSubjectTimePoint(R, Type);
  
  if(ComputeG)          m_G = exp(R.at("G", 0));
  if(ComputeDelta)      ComputeDeltas(R);
  if(ComputeBasis)      ComputeOrthonormalBasis();
  if(ComputeA)          ComputeAMatrix(R);
  if(ComputeSpaceShift) ComputeSpaceShifts(R);
  if(ComputeBlock_)     ComputeBlock(R);
}
Example #4
0
string file_base(string s) {
    int i = s.rfind('.');
    return i == -1 ? s : substr(s, 0, i);
}
Example #5
0
/*
 * Function to print help. The help argument is in argv[0] here.
 */
static void
help_func(int argc, char *argv[])
{
	struct help_file hfile;
	struct help_pos match, last_match;
	const char *line;
	char key[100];
	int level;
	int i, has_sub_topics;

	memset(&hfile, 0, sizeof(hfile));
	memset(&match, 0, sizeof(match));
	memset(&last_match, 0, sizeof(last_match));

	if (argc == 0) {
		/* only 'help' - show intro */
		if ((argv[0] = strdup("intro")) == NULL)
			err(1, NULL);
		argc = 1;
	}

	optind = 0;
	match.pos = -1;
	last_match.pos = -1;
	for (;;) {
		/* read next line */
		if ((line = help_next_line(&hfile)) == NULL) {
			/* EOF */
			level = 999;
			goto stop;
		}
		if (line[0] != '^' || line[1] == '^')
			continue;

		if (sscanf(line + 1, "%d%99s", &level, key) != 2)
			errx(1, "error in help file '%s'", line);

		if (level < optind) {
  stop:
			/* next higher level entry - stop this level */
			if (match.pos == -1) {
				/* not found */
				goto not_found;
			}
			/* go back to the match */
			help_file_seek(&hfile, &match);
			last_match = match;
			memset(&match, 0, sizeof(match));
			match.pos = -1;

			/* go to next key */
			if (++optind >= argc)
				break;
		}
		if (level == optind) {
			if (substr(argv[optind], key)) {
				if (match.pos != -1) {
					printf("Ambiguous topic.");
					goto list_topics;
				}
				help_file_tell(&hfile, &match);
			}
		}
	}

	/* before breaking above we have seeked back to the matching point */
	for (;;) {
		if ((line = help_next_line(&hfile)) == NULL)
			break;

		if (line[0] == '#')
			continue;
		if (line[0] == '^') {
			if (line[1] == '^')
				continue;
			break;
		}
		if (strncmp(line, "$MAIN", 5) == 0) {
			help_get_0topics(&hfile);
			continue;
		}
		printf("%s", line);
	}

	exit(0);

  not_found:
	printf("Topic not found.");

  list_topics:
	printf(" Use one of:\natmconfig help");
	for (i = 0; i < optind; i++)
		printf(" %s", argv[i]);

	printf(" [");

	/* list all the keys at this level */
	if (last_match.pos == -1)
		/* go back to start of help */
		help_file_rewind(&hfile);
	else
		help_file_seek(&hfile, &last_match);

	has_sub_topics = 0;
	while ((line = help_next_line(&hfile)) != NULL) {
		if (line[0] == '#' || line[0] != '^' || line[1] == '^')
			continue;

		if (sscanf(line + 1, "%d%99s", &level, key) != 2)
			errx(1, "error in help file '%s'", line);

		if (level < optind)
			break;
		if (level == optind) {
			has_sub_topics = 1;
			printf(" %s", key);
		}
	}
	printf(" ].");
	if (!has_sub_topics)
		printf(" No sub-topics found.");
	printf("\n");
	exit(1);
}
Example #6
0
int main()
{
	int userid;
	int allgood=0;
	char sline[LINELEN], line[LINELEN];
	MYSQL_RES *res;
	MYSQL_ROW row;
	char email[255];
	char title[255];
	char content[4096]; //FIXME
	char query[4096]; // too

	// extract email addr
	while(!feof(stdin))
	{
		fgets(line, LINELEN, stdin);
		substr(sline, line, 0, 6);
		if(!strcmp(sline, "From: "))
		{
			emailtrim(line, email);
			if (allgood==1)
				break;
			else
				allgood=1;
		}
		substr(sline, line, 0, 8);
		if(!strcmp(sline, "Subject:"))
		{
			substr(title, line, 8, strlen(line)-8);
			if(allgood==1)
				break;
			else
				allgood=1;
		}
	}

	//skip headers
	while(!feof(stdin))
	{
		fgets(line, LINELEN, stdin);
		if(!strcmp(line, "\n"))
			break;
	}
	while(!feof(stdin))
	{
		fgets(line, LINELEN, stdin);
		if(strcmp(sline, line))
			strncat(content, line, 4096);
		strcpy(sline, line);
	}

	if(strlen(email) > 254 || strlen(title) > 254 || strlen(content) > 4094)
	{
		fprintf(stderr, "one or more fields are too long");
		return(1);
	}

	printf("mail: %s\n", email);
	printf("cim: %s\n", title);
	printf("stuff: %s\n", content);
	//return(0);

	if(!(sock = mysql_real_connect(&demo_db, HOST, USERNAME, PASSWD, DBNAME, 0, MYSQL_UNIX_ADDR,0)))
	{
		printf("Connecting failed: %s\n", mysql_error(&demo_db));
		return(1);
	}

	sprintf(query, "SELECT id FROM users WHERE email='%s'", email);
	if(mysql_query(sock, query))
	{
		printf("Query failed: %s\n", mysql_error(&demo_db));
		return(1);
	}

	res=mysql_store_result(&demo_db); /* Download result from server */
	if(!(row=mysql_fetch_row(res))) /* Get a row from the results */
	{
		printf("no such user\n");
		return(1);
	}
	
	userid = atoi(row[0]);
	mysql_free_result(res); /* Release memory used to store results. */
	sprintf(query, "INSERT INTO posts (userid, title, content, modositas, letrehozas) VALUES (%d, '%s', '%s', NOW(), NOW())", userid, addslashes(title), addslashes(content));
	if(mysql_query(sock, query))
	{
		printf("Query failed: %s\n", mysql_error(&demo_db));
		return(1);
	}
	mysql_close(&demo_db);

	return(0);
}
Example #7
0
string strip_dir(string s) {
    return substr(s, s.rfind('/')+1);    
}
Example #8
0
Bool parse_body_info(char * body_info, BStateInfo *bsinfo)
{
    char s1[10],s2[10],s3[10],temp[BUFSIZE1];


    s1[0] = s2[0] = s3[0] = temp[0] = '\0' ;
    substr(temp,body_info,1,strlen(body_info)-2);
    sscanf(temp,"%s %s %s",s1,s2,s3);
    if (s1[0] == '\0') {
        return FALSE ;
    }
    if(!strcmp(s1,"view_mode")) {
        if (s2[0] == 'h') /* high */
            bsinfo->quality = VQ_high ;
        else if (s2[0] == 'l') /* low */
            bsinfo->quality = VQ_low ;
        else
            bsinfo->quality = VQ_Error ;
        if (s3[0] == 'n' ) { /* normal or narrow */
            if (s3[1] == 'o') /* normal */
                bsinfo->width = VW_Normal ;
            else if (s3[1] == 'a')
                bsinfo->width = VW_Narrow ;
            else
                bsinfo->width = VW_Error ;
        }
        else if (s3[0] == 'w') /* wide */
            bsinfo->width = VW_Wide ;
        else
            bsinfo->width = VW_Error ;
    }
    else if(!strcmp(s1,"stamina")) {
        if (s2[0] == '\0')
            bsinfo->short_stamina = Stamina_Error ;
        else
            bsinfo->short_stamina = atof(s2);
        if (s3[0] == '\0')
            bsinfo->long_stamina = Stamina_Error ;
        else
            bsinfo->long_stamina = atof(s3);
    }
    else if (!strcmp(s1,"speed")) {
        if (s2[0] == '\0')
            bsinfo->speed = Speed_Error ;
        else
            bsinfo->speed = atof(s2) ;
    }
    else if (!strcmp(s1,"kick")) {
        if (s2[0] == '\0')
            bsinfo->kick = Kick_Error ;
        else
            bsinfo->kick = atoi(s2) ;
    }
    else if (!strcmp(s1,"dash")) {
        if (s2[0] == '\0')
            bsinfo->dash = Kick_Error ;
        else
            bsinfo->dash = atoi(s2) ;
    }
    else if (!strcmp(s1,"turn")) {
        if (s2[0] == '\0')
            bsinfo->turn = Turn_Error ;
        else
            bsinfo->turn = atoi(s2) ;
    }
    else if (!strcmp(s1,"say")) {
        if (s2[0] == '\0')
            bsinfo->say = Say_Error ;
        else
            bsinfo->say = atoi(s2) ;
    }
    else
        return FALSE ;
    return TRUE ;
}
Example #9
0
int sendMessage(MESSAGE *m) {
	int i, bcc = 0, error = 0;
	char ocp[3], oc[3], cmd[3], head[7], message[m->message_length];

	/* convert HEX to string */
	if (m->message_type == 'A') {
		convert(cmd,  m->command);
	} else {
		convert(ocp,  m->op_code_page);
		convert(oc,   m->op_code);
	}

	if (getDebug() > 0) {
		puts(">>>> >>>  >>   >");
		puts("I: Preparing message:");
	}

	/* create head string */
	sprintf(head, "%c%c%c%c%c%s",
		m->soh,
		m->reserve,
		m->destination,
		m->source,
		m->message_type,
		int2strhex(m->message_length, 2)
	);
	if (getDebug() > 0) {
		printf("   * Head       = [");
		print(7, head);
		printf("]\n");
	}

	/* create message string */
	if (m->message_type == 'A')
		/* command */
    		sprintf(message, "%c%s%c",
			m->stx,
			cmd,
			m->etx
		);
	else if (m->message_type == 'C')
		/* get current parameter */
    		sprintf(message, "%c%s%s%c",
			m->stx,
			ocp,
			oc,
			m->etx
		);
	else if (m->message_type == 'E')
		/* set parameter message */
    		sprintf(message, "%c%s%s%s%c",
			m->stx,
			ocp,
			oc,
			m->value,
			m->etx
		);

	if (getDebug() > 0) {
		printf("   * Message    = [");
		print(m->message_length, message);
		printf("]\n");
	}

	/* count check code */
	for (i=1; i<7; i++)
		bcc ^= head[i];
	for (i=0; i<m->message_length; i++)
		bcc ^= message[i];

	if (getDebug() > 0) {
		printf("   * Check code = [%#x]\n", bcc);
		printf("   * Delimiter  = [%#x]\n", m->cr);
	}

	m->msg = calloc(19, sizeof(char));
	sprintf(m->msg, "%s%s%c%c", head, message, bcc, m->cr);

	m->replay = NULL;
	send_message(m->msg, &m->replay);

	if (getDebug() > 0 && m->replay == NULL)
		perror("E: No replay!");
	else if (getDebug() > 1 && m->replay != NULL) {
		REPLAY r;

		r.initReplay = initReplay;
		r.initReplay(&r, &m->replay);

		r.printReplay = printReplay;
		r.printReplay(&r);
	}

	if (m->replay == NULL || strcmp(substr(m->replay, 8, 2), "00") != 0)
		error = -1;

	if (getDebug() > 0 ) puts("<   <<  <<< <<<<");
	return error;
}
Example #10
0
	const Selector::MatchResult AttributeSelector::Match(const Node* node) const
	{		
		switch (m_operator)
		{
			case SelectorOperator::Exists:
			{						
				if (node->HasAttribute(m_attributeNameRef))
				{
					return MatchResult(node);
				}
			}
			break;

			case SelectorOperator::ValueContains:
			{
				auto attributeValue = node->GetAttributeValue(m_attributeNameRef);

				if (attributeValue.size() == 0)
				{
					return nullptr;
				}

				// Just do a search
				auto searchResult = attributeValue.find(m_attributeValueRef);

				// Simply return whether or not we got any matches.
				if (searchResult != boost::string_ref::npos)
				{
					return MatchResult(node);
				}
			}
			break;

			case SelectorOperator::ValueEquals:
			{
				auto attributeValue = node->GetAttributeValue(m_attributeNameRef);

				auto oneSize = attributeValue.size();
				auto twoSize = m_attributeValueRef.size();

				if (oneSize == 0 || oneSize != twoSize)
				{
					return nullptr;
				}

				if (oneSize >= 4)
				{
					if ((attributeValue[0] == m_attributeValueRef[0]) &&
						(attributeValue[1] == m_attributeValueRef[1]) &&
						(attributeValue[oneSize - 1] == m_attributeValueRef[oneSize - 1]) &&
						(attributeValue[oneSize - 2] == m_attributeValueRef[oneSize - 2]))
					{
						if (std::memcmp(attributeValue.begin(), m_attributeValueRef.begin(), oneSize) == 0)
						{
							return MatchResult(node);
						}
					}
				}
				else
				{
					if (std::memcmp(attributeValue.begin(), m_attributeValueRef.begin(), oneSize) == 0)
					{
						return MatchResult(node);
					}
				}

				return nullptr;
			}
			break;

			case SelectorOperator::ValueHasPrefix:
			{
				auto attributeValue = node->GetAttributeValue(m_attributeNameRef);
						
				auto subSize = m_attributeValueRef.size();

				if (attributeValue.size() == 0 || attributeValue.size() <= subSize)
				{					
					return nullptr;
				}				

				auto sub = attributeValue.substr(0, subSize);

				subSize = sub.size();

				if (subSize == m_attributeValueRef.size())
				{
					if (subSize >= 4)
					{
						if ((sub[0] == m_attributeValueRef[0]) &&
							(sub[1] == m_attributeValueRef[1]) &&
							(sub[subSize - 1] == m_attributeValueRef[subSize - 1]) &&
							(sub[subSize - 2] == m_attributeValueRef[subSize - 2]))
						{
							if (std::memcmp(sub.begin(), m_attributeValueRef.begin(), subSize) == 0)
							{
								return MatchResult(node);
							}
						}
					}
					else
					{
						if (std::memcmp(sub.begin(), m_attributeValueRef.begin(), subSize) == 0)
						{
							return MatchResult(node);
						}
					}
				}

				return nullptr;
			}
			break;

			case SelectorOperator::ValueHasSuffix:
			{
				auto attributeValue = node->GetAttributeValue(m_attributeNameRef);

				auto subSize = m_attributeValueRef.size();

				// If our suffix is greater than the attribute value, we can just move on.
				if (attributeValue.size() == 0 || subSize >= attributeValue.size())
				{
					return nullptr;
				}

				// Test equality of same-length substring taken from the end.
				boost::string_ref sub = attributeValue.substr((attributeValue.size() - subSize));

				subSize = sub.size();

				if (subSize == m_attributeValueRef.size())
				{
					if (subSize >= 4)
					{
						if ((sub[0] == m_attributeValueRef[0]) &&
							(sub[1] == m_attributeValueRef[1]) &&
							(sub[subSize - 1] == m_attributeValueRef[subSize - 1]) &&
							(sub[subSize - 2] == m_attributeValueRef[subSize - 2]))
						{
							if (std::memcmp(sub.begin(), m_attributeValueRef.begin(), subSize) == 0)
							{
								return MatchResult(node);
							}
						}
					}
					else
					{
						if (std::memcmp(sub.begin(), m_attributeValueRef.begin(), subSize) == 0)
						{
							return MatchResult(node);
						}
					}
				}

				return nullptr;
			}
			break;

			case SelectorOperator::ValueContainsElementInWhitespaceSeparatedList:
			{
				auto attributeValue = node->GetAttributeValue(m_attributeNameRef);

				// If the attribute value to check is smaller than our value, then we can just
				// return false right away.
				if (attributeValue.size() == 0 || attributeValue.size() < m_attributeValueRef.size())
				{
					return nullptr;
				}

				if (attributeValue.size() == m_attributeValueRef.size())
				{
					// If the two values match exactly, this is considered a match with this
					// selector type. If they do not match, the only other possible type of match
					// this operator can make is the match the selector value PLUS whitespace, in
					// which case this isn't possible (being the two strings equal length), so
					// letting boost::iequals return false or true is the right answer either way.

					auto oneSize = attributeValue.size();

					if (oneSize >= 4)
					{
						if ((attributeValue[0] == m_attributeValueRef[0]) && 
							(attributeValue[1] == m_attributeValueRef[1]) &&
							(attributeValue[oneSize - 1] == m_attributeValueRef[oneSize - 1]) &&
							(attributeValue[oneSize - 2] == m_attributeValueRef[oneSize - 2]))
						{
							if (std::memcmp(attributeValue.begin(), m_attributeValueRef.begin(), oneSize) == 0)
							{
								return MatchResult(node);
							}
						}
					}
					else
					{
						if (std::memcmp(attributeValue.begin(), m_attributeValueRef.begin(), oneSize) == 0)
						{
							return MatchResult(node);
						}
					}

					return nullptr;
				}

				// If there isn't anything that qualifies as whitespace in the CSS selector world,
				// then we can just immediately return false.
				auto anySpacePosition = attributeValue.find(' ');

				if (anySpacePosition == boost::string_ref::npos)
				{
					return nullptr;
				}				
				
				auto firstSpace = attributeValue.find(' ');

				while (firstSpace != boost::string_ref::npos && attributeValue.size() > 0)
				{					
					if (firstSpace > 0 && firstSpace == m_attributeValueRef.size())
					{
						auto sub = attributeValue.substr(0, firstSpace);

						auto subSize = sub.size();

						if (subSize == m_attributeValueRef.size())
						{
							if (subSize >= 4)
							{
								if ((sub[0] == m_attributeValueRef[0]) &&
									(sub[1] == m_attributeValueRef[1]) &&
									(sub[subSize - 1] == m_attributeValueRef[subSize - 1]) &&
									(sub[subSize - 2] == m_attributeValueRef[subSize - 2]))
								{
									if (std::memcmp(sub.begin(), m_attributeValueRef.begin(), subSize) == 0)
									{
										return MatchResult(node);
									}
								}
							}
							else
							{
								if (std::memcmp(sub.begin(), m_attributeValueRef.begin(), subSize) == 0)
								{
									return MatchResult(node);
								}
							}
						}						
					}

					attributeValue = attributeValue.substr(firstSpace + 1);
					firstSpace = attributeValue.find(' ');
				}

				return nullptr;
			}
			break;

			case SelectorOperator::ValueIsHyphenSeparatedListStartingWith:
			{
				auto attributeValue = node->GetAttributeValue(m_attributeNameRef);

				// If the attribute value to check is smaller than our value, then we can just
				// return false right away.
				if (attributeValue.size() == 0 || attributeValue.size() < m_attributeValueRef.size())
				{
					return nullptr;
				}

				if (attributeValue.size() == m_attributeValueRef.size())
				{
					// If the two values match exactly, this is considered a match with this
					// selector type. If they do not match, the only other possible type of match
					// this operator can make is the match the selector value PLUS a dash, in which
					// case this isn't possible (being the two strings equal length), so letting
					// boost::iequals return false or true is the right answer either way.

					auto oneSize = attributeValue.size();

					if (oneSize >= 4)
					{
						if ((attributeValue[0] == m_attributeValueRef[0]) &&
							(attributeValue[1] == m_attributeValueRef[1]) &&
							(attributeValue[oneSize - 1] == m_attributeValueRef[oneSize - 1]) &&
							(attributeValue[oneSize - 2] == m_attributeValueRef[oneSize - 2]))
						{
							if (std::memcmp(attributeValue.begin(), m_attributeValueRef.begin(), oneSize) == 0)
							{
								return MatchResult(node);
							}
						}
					}
					else
					{
						if (std::memcmp(attributeValue.begin(), m_attributeValueRef.begin(), oneSize) == 0)
						{
							return MatchResult(node);
						}
					}

					return nullptr;
				}

				// If we didn't find an exact match, then the only hope of a match now is finding
				// the selector value at the start of the attribute value, immediately followed by a
				// hyphen. Therefore, if we can't find a hypen, then we simply return false right
				// away.
				auto anyHyphen = attributeValue.find('-');

				if (anyHyphen == boost::string_ref::npos)
				{
					return nullptr;
				}

				// A hyphen was found, so all we have to do is make a case-insensitive match against
				// a substring of equal length to our member value.
				boost::string_ref sub = attributeValue.substr(0, m_attributeValueRef.size() + 1);

				if (sub[sub.length() - 1] != '-')
				{
					// If the last character in the substring isn't a dash, it can't possibly be a match anyway.
					return nullptr;
				}

				sub = attributeValue.substr(0, m_attributeValueRef.size());

				auto subSize = sub.size();

				if (subSize == m_attributeValueRef.size())
				{
					if (subSize >= 4)
					{
						if ((sub[0] == m_attributeValueRef[0]) &&
							(sub[1] == m_attributeValueRef[1]) &&
							(sub[subSize - 1] == m_attributeValueRef[subSize - 1]) &&
							(sub[subSize - 2] == m_attributeValueRef[subSize - 2]))
						{
							if (std::memcmp(sub.begin(), m_attributeValueRef.begin(), subSize) == 0)
							{
								return MatchResult(node);
							}
						}
					}
					else
					{
						if (std::memcmp(sub.begin(), m_attributeValueRef.begin(), subSize) == 0)
						{
							return MatchResult(node);
						}
					}
				}		

				return nullptr;
			}
			break;
		}

		return nullptr;
	}
Example #11
0
std::vector<cleaver::AbstractScalarField*>
NRRDTools::segmentationToIndicatorFunctions(std::string filename, double sigma) {
  // read file using ITK
  if (filename.find(".nrrd") != std::string::npos) {
    itk::NrrdImageIOFactory::RegisterOneFactory();
  } else if (filename.find(".mha") != std::string::npos) {
    itk::MetaImageIOFactory::RegisterOneFactory();
  }
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(filename);
  reader->Update();
  ImageType::Pointer image = reader->GetOutput();
  //determine the number of labels in the segmentations
  ImageCalculatorFilterType::Pointer imageCalculatorFilter
    = ImageCalculatorFilterType::New();
  imageCalculatorFilter->SetImage(reader->GetOutput());
  imageCalculatorFilter->Compute();
  auto maxLabel = static_cast<size_t>(imageCalculatorFilter->GetMaximum());
  auto minLabel = static_cast<size_t>(imageCalculatorFilter->GetMinimum());
  std::vector<cleaver::AbstractScalarField*> fields;
  //extract images from each label for an indicator function
  for (size_t i = minLabel, num = 0; i <= maxLabel; i++, num++) {
    //pull out this label
    ThreshType::Pointer thresh = ThreshType::New();
    thresh->SetInput(image);
    thresh->SetOutsideValue(0);
    thresh->ThresholdOutside(static_cast<double>(i) - 0.001,
      static_cast<double>(i) + 0.001);
    thresh->Update();
    //change the values to be from 0 to 1
    MultiplyImageFilterType::Pointer multiplyImageFilter =
      MultiplyImageFilterType::New();
    multiplyImageFilter->SetInput(thresh->GetOutput());
    multiplyImageFilter->SetConstant(1. / static_cast<double>(i));
    multiplyImageFilter->Update();
    //do some blurring
    GaussianBlurType::Pointer blur = GaussianBlurType::New();
    blur->SetInput(multiplyImageFilter->GetOutput());
    blur->SetVariance(sigma * sigma);
    blur->Update();
    //find the average value between
    ImageCalculatorFilterType::Pointer calc =
      ImageCalculatorFilterType::New();
    calc->SetImage(blur->GetOutput());
    calc->Compute();
    float mx = calc->GetMaximum();
    float mn = calc->GetMinimum();
    auto md = (mx + mn) / 2.f;
    //create a distance map with that minimum value as the levelset
    DMapType::Pointer dm = DMapType::New();
    dm->SetInput(blur->GetOutput());
    dm->SetInsideValue(md + 0.1f);
    dm->SetOutsideValue(md -0.1f);
    dm->Update();
    //MultiplyImageFilterType::Pointer mult =
    //  MultiplyImageFilterType::New();
    //mult->SetInput(blur->GetOutput());
    //mult->SetConstant(-20. / (mx - mn));
    //mult->Update();
    /*SubtractImageFilterType::Pointer subtractFilter
      = SubtractImageFilterType::New();
    subtractFilter->SetInput1(mult->GetOutput());
    subtractFilter->SetConstant2(1.);
    subtractFilter->Update();*/
    //convert the image to a cleaver "abstract field"
    auto img = dm->GetOutput();
    auto region = img->GetLargestPossibleRegion();
    auto numPixel = region.GetNumberOfPixels();
    float *data = new float[numPixel];
    auto x = region.GetSize()[0], y = region.GetSize()[1], z = region.GetSize()[2];
    fields.push_back(new cleaver::FloatField(data, x, y, z));
    auto beg = filename.find_last_of("/") + 1;
    auto name = filename.substr(beg, filename.size() - beg);
    auto fin = name.find_last_of(".");
    name = name.substr(0, fin);
    std::stringstream ss;
    ss << name << i;
    fields[num]->setName(ss.str());
    itk::ImageRegionConstIterator<ImageType> imageIterator(img, region);
    size_t pixel = 0;
    while (!imageIterator.IsAtEnd()) {
      // Get the value of the current pixel
      float val = static_cast<float>(imageIterator.Get());
      ((cleaver::FloatField*)fields[num])->data()[pixel++] = -val;
      ++imageIterator;
    }
    auto spacing = img->GetSpacing();
    ((cleaver::FloatField*)fields[num])->setScale(
      cleaver::vec3(spacing[0], spacing[1], spacing[2]));
    //NRRDTools::saveNRRDFile(fields[num], "a" + std::to_string(num));
  }
  return fields;
}
Example #12
0
	virtual void Run()
	{
		Given("an output stream and output", [&]()
		{
			m_actualOutput.str("");
			m_output = std::unique_ptr<ut11::out::StdOutput>(new ut11::out::StdOutput(m_actualOutput));
		});
		When("begin and end without running any tests", [&]()
		{
			m_output->Begin();
			m_output->Finish(10, 7);
		});
		Then("the output is as expected", [&]()
		{
			AssertThat(m_actualOutput.str(), ut11::Is::EqualTo("\nFinished!\nRan: 10\nSucceeded: 7\n"));
		});

		When("running a test fixture with just a Then", [&]()
		{
			m_output->Begin();
			m_output->BeginFixture("fixture");
			m_output->BeginTest();
			m_output->BeginThen("then");
			m_output->EndThen("then");
			m_output->EndTest();
			m_output->EndFixture("fixture");
			m_output->Finish(1, 1);
		});
		Then("the output is as expected", [&]()
		{
			auto stringVal = m_actualOutput.str();
			auto startOfTime = stringVal.find('[');
			auto endOfTime = stringVal.find(']');
			stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1);

			AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\t\t\tThen: then \n\nFinished!\nRan: 1\nSucceeded: 1\n"));
		});

		When("running two test fixtures with just a Then", [&]()
		{
			m_output->Begin();
			m_output->BeginFixture("fixture");
			m_output->BeginTest();
			m_output->BeginThen("then");
			m_output->EndThen("then");
			m_output->EndTest();
			m_output->EndFixture("fixture");
			m_output->BeginFixture("fixture2");
			m_output->BeginTest();
			m_output->BeginThen("then2");
			m_output->EndThen("then2");
			m_output->EndTest();
			m_output->EndFixture("fixture2");
			m_output->Finish(2, 2);
		});
		Then("the output is as expected", [&]()
		{
			auto stringVal = m_actualOutput.str();
			auto startOfTime = stringVal.find('[');
			auto endOfTime = stringVal.find(']');
			stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1);

			startOfTime = stringVal.find('[');
			endOfTime = stringVal.find(']');
			stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1);

			AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\t\t\tThen: then \nFixture: fixture2\n\t\t\tThen: then2 \n\nFinished!\nRan: 2\nSucceeded: 2\n"));
		});

		When("running a test fixture with just a When and Then", [&]()
		{
			m_output->Begin();
			m_output->BeginFixture("fixture");
			m_output->BeginTest();
			m_output->BeginWhen("when");
			m_output->EndWhen("then");
			m_output->BeginThen("then");
			m_output->EndThen("then");
			m_output->EndTest();
			m_output->EndFixture("fixture");
			m_output->Finish(1, 1);
		});
		Then("the output is as expected", [&]()
		{
			auto stringVal = m_actualOutput.str();
			auto startOfTime = stringVal.find('[');
			auto endOfTime = stringVal.find(']');
			stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1);

			AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\t\tWhen: when\n\t\t\tThen: then \n\nFinished!\nRan: 1\nSucceeded: 1\n"));
		});

		When("running a test fixture with a Given When and Then", [&]()
		{
			m_output->Begin();
			m_output->BeginFixture("fixture");
			m_output->BeginTest();
			m_output->BeginGiven("given");
			m_output->EndGiven("given");
			m_output->BeginWhen("when");
			m_output->EndWhen("then");
			m_output->BeginThen("then");
			m_output->EndThen("then");
			m_output->EndTest();
			m_output->EndFixture("fixture");
			m_output->Finish(1, 1);
		});
		Then("the output is as expected", [&]()
		{
			auto stringVal = m_actualOutput.str();
			auto startOfTime = stringVal.find('[');
			auto endOfTime = stringVal.find(']');
			stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1);

			AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\tGiven: given\n\t\tWhen: when\n\t\t\tThen: then \n\nFinished!\nRan: 1\nSucceeded: 1\n"));
		});

		When("running a test fixture with a Given When Then Finally", [&]()
		{
			m_output->Begin();
			m_output->BeginFixture("fixture");
			m_output->BeginTest();
			m_output->BeginGiven("given");
			m_output->EndGiven("given");
			m_output->BeginWhen("when");
			m_output->EndWhen("then");
			m_output->BeginThen("then");
			m_output->EndThen("then");
			m_output->BeginFinally("finally");
			m_output->EndFinally("finally");
			m_output->EndTest();
			m_output->EndFixture("fixture");
			m_output->Finish(1, 1);
		});
		Then("the output is as expected", [&]()
		{
			auto stringVal = m_actualOutput.str();
			auto startOfTime = stringVal.find('[');
			auto endOfTime = stringVal.find(']');
			stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1);

			AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\tGiven: given\n\t\tWhen: when\n\t\t\tThen: then \n\tFinally: finally\n\nFinished!\nRan: 1\nSucceeded: 1\n"));
		});

		When("running a test fixture with multiple tests with a Given When Then Finally where the Given and Whens repeat", [&]()
		{
			m_output->Begin();
			m_output->BeginFixture("fixture");
			m_output->BeginTest();
			m_output->BeginGiven("given");
			m_output->EndGiven("given");
			m_output->BeginWhen("when");
			m_output->EndWhen("then");
			m_output->BeginThen("then");
			m_output->EndThen("then");
			m_output->BeginFinally("finally");
			m_output->EndFinally("finally");
			m_output->EndTest();
			m_output->BeginTest();
			m_output->BeginGiven("given");
			m_output->EndGiven("given");
			m_output->BeginWhen("when");
			m_output->EndWhen("then");
			m_output->BeginThen("then2");
			m_output->EndThen("then2");
			m_output->BeginFinally("finally");
			m_output->EndFinally("finally");
			m_output->EndTest();
			m_output->EndFixture("fixture");
			m_output->Finish(1, 1);
		});
		Then("the output is as expected", [&]()
		{
			auto stringVal = m_actualOutput.str();
			auto startOfTime = stringVal.find('[');
			auto endOfTime = stringVal.find(']');
			stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1);

			startOfTime = stringVal.find('[');
			endOfTime = stringVal.find(']');
			stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1);

			AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\tGiven: given\n\t\tWhen: when\n\t\t\tThen: then \n\t\t\tThen: then2 \n\tFinally: finally\n\nFinished!\nRan: 1\nSucceeded: 1\n"));
		});

		When("running a test fixture with a When Then Finally", [&]()
		{
			m_output->Begin();
			m_output->BeginFixture("fixture");
			m_output->BeginTest();
			m_output->BeginWhen("when");
			m_output->EndWhen("then");
			m_output->BeginThen("then");
			m_output->EndThen("then");
			m_output->BeginFinally("finally");
			m_output->EndFinally("finally");
			m_output->EndTest();
			m_output->EndFixture("fixture");
			m_output->Finish(1, 1);
		});
		Then("the output is as expected", [&]()
		{
			auto stringVal = m_actualOutput.str();
			auto startOfTime = stringVal.find('[');
			auto endOfTime = stringVal.find(']');
			stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1);

			AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\t\tWhen: when\n\t\t\tThen: then \n\tFinally: finally\n\nFinished!\nRan: 1\nSucceeded: 1\n"));
		});

		When("running a test fixture with a Then Finally", [&]()
		{
			m_output->Begin();
			m_output->BeginFixture("fixture");
			m_output->BeginTest();
			m_output->BeginThen("then");
			m_output->EndThen("then");
			m_output->BeginFinally("finally");
			m_output->EndFinally("finally");
			m_output->EndTest();
			m_output->EndFixture("fixture");
			m_output->Finish(1, 1);
		});
		Then("the output is as expected", [&]()
		{
			auto stringVal = m_actualOutput.str();
			auto startOfTime = stringVal.find('[');
			auto endOfTime = stringVal.find(']');
			stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1);

			AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\t\t\tThen: then \n\tFinally: finally\n\nFinished!\nRan: 1\nSucceeded: 1\n"));
		});

		When("running a test fixture with a Given When Then Finally and the Then fails with an std::exception", [&]()
		{
			m_output->Begin();
			m_output->BeginFixture("fixture");
			m_output->BeginTest();
			m_output->BeginGiven("given");
			m_output->EndGiven("given");
			m_output->BeginWhen("when");
			m_output->EndWhen("then");
			m_output->BeginThen("then");
			m_output->OnError(std::runtime_error("error"));
			m_output->EndThen("then");
			m_output->BeginFinally("finally");
			m_output->EndFinally("finally");
			m_output->EndTest();
			m_output->EndFixture("fixture");
			m_output->Finish(1, 0);
		});
		Then("the output is as expected", [&]()
		{
			auto stringVal = m_actualOutput.str();
			auto startOfTime = stringVal.find('[');
			startOfTime = stringVal.substr(startOfTime + 1).find('[') + startOfTime;

			auto endOfTime = stringVal.find(']');
			endOfTime = stringVal.substr(endOfTime + 1).find(']') + endOfTime + 1;

			stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1);

			AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\tGiven: given\n\t\tWhen: when\n\t\t\tThen: then\n\tFailed: std::exception was thrown [what(): error]\n\tFinally: finally\n\nFinished!\nRan: 1\nSucceeded: 0\n"));
		});

		When("running a test fixture with a Given When Then Finally and the Then fails with an unknown error", [&]()
		{
			m_output->Begin();
			m_output->BeginFixture("fixture");
			m_output->BeginTest();
			m_output->BeginGiven("given");
			m_output->EndGiven("given");
			m_output->BeginWhen("when");
			m_output->EndWhen("then");
			m_output->BeginThen("then");
			m_output->OnUnknownError();
			m_output->EndThen("then");
			m_output->BeginFinally("finally");
			m_output->EndFinally("finally");
			m_output->EndTest();
			m_output->EndFixture("fixture");
			m_output->Finish(1, 0);
		});
		Then("the output is as expected", [&]()
		{
			auto stringVal = m_actualOutput.str();
			auto startOfTime = stringVal.find('[');
			startOfTime = stringVal.substr(startOfTime + 1).find('[') + startOfTime;

			auto endOfTime = stringVal.find(']');
			endOfTime = stringVal.substr(endOfTime + 1).find(']') + endOfTime + 1;

			stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1);

			AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\tGiven: given\n\t\tWhen: when\n\t\t\tThen: then\n\tFailed: Unknown Error\n\tFinally: finally\n\nFinished!\nRan: 1\nSucceeded: 0\n"));
		});

		When("running a test fixture with a Given When Then Finally and the Then fails", [&]()
		{
			m_output->Begin();
			m_output->BeginFixture("fixture");
			m_output->BeginTest();
			m_output->BeginGiven("given");
			m_output->EndGiven("given");
			m_output->BeginWhen("when");
			m_output->EndWhen("then");
			m_output->BeginThen("then");
			m_output->OnError(10, "file", "error");
			m_output->EndThen("then");
			m_output->BeginFinally("finally");
			m_output->EndFinally("finally");
			m_output->EndTest();
			m_output->EndFixture("fixture");
			m_output->Finish(1, 0);
		});
		Then("the output is as expected", [&]()
		{
			auto stringVal = m_actualOutput.str();
			auto startOfTime = stringVal.find('[');
			startOfTime = stringVal.substr(startOfTime + 1).find('[') + startOfTime;

			auto endOfTime = stringVal.find(']');
			endOfTime = stringVal.substr(endOfTime + 1).find(']') + endOfTime + 1;

			stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1);

			AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\tGiven: given\n\t\tWhen: when\n\t\t\tThen: then\n\tFailed: [10:file] error\n\tFinally: finally\n\nFinished!\nRan: 1\nSucceeded: 0\n"));
		});


		When("running a test fixture with a Given When Finally and the When fails", [&]()
		{
			m_output->Begin();
			m_output->BeginFixture("fixture");
			m_output->BeginTest();
			m_output->BeginGiven("given");
			m_output->EndGiven("given");
			m_output->BeginWhen("when");
			m_output->OnError(10, "file", "error");
			m_output->EndWhen("then");
			m_output->BeginFinally("finally");
			m_output->EndFinally("finally");
			m_output->EndTest();
			m_output->EndFixture("fixture");
			m_output->Finish(1, 0);
		});
		Then("the output is as expected", [&]()
		{
			auto stringVal = m_actualOutput.str();
			auto startOfTime = stringVal.find('[');
			startOfTime = stringVal.substr(startOfTime + 1).find('[') + startOfTime;

			auto endOfTime = stringVal.find(']');
			endOfTime = stringVal.substr(endOfTime + 1).find(']') + endOfTime + 1;

			stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1);

			AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\tGiven: given\n\t\tWhen: when\n\tFailed: [10:file] error\n\tFinally: finally\n\nFinished!\nRan: 1\nSucceeded: 0\n"));
		});


		When("running a test fixture with a Given Finally and the Given fails", [&]()
		{
			m_output->Begin();
			m_output->BeginFixture("fixture");
			m_output->BeginTest();
			m_output->BeginGiven("given");
			m_output->OnError(10, "file", "error");
			m_output->EndGiven("given");
			m_output->BeginFinally("finally");
			m_output->EndFinally("finally");
			m_output->EndTest();
			m_output->EndFixture("fixture");
			m_output->Finish(1, 0);
		});
		Then("the output is as expected", [&]()
		{
			auto stringVal = m_actualOutput.str();
			auto startOfTime = stringVal.find('[');
			startOfTime = stringVal.substr(startOfTime + 1).find('[') + startOfTime;

			auto endOfTime = stringVal.find(']');
			endOfTime = stringVal.substr(endOfTime + 1).find(']') + endOfTime + 1;

			stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1);

			AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\tGiven: given\n\tFailed: [10:file] error\n\tFinally: finally\n\nFinished!\nRan: 1\nSucceeded: 0\n"));
		});

		When("running a test fixture with a Given Finally and the Finally fails", [&]()
		{
			m_output->Begin();
			m_output->BeginFixture("fixture");
			m_output->BeginTest();
			m_output->BeginGiven("given");
			m_output->EndGiven("given");
			m_output->BeginFinally("finally");
			m_output->OnError(10, "file", "error");
			m_output->EndFinally("finally");
			m_output->EndTest();
			m_output->EndFixture("fixture");
			m_output->Finish(1, 0);
		});
		Then("the output is as expected", [&]()
		{
			auto stringVal = m_actualOutput.str();
			auto startOfTime = stringVal.find('[');
			startOfTime = stringVal.substr(startOfTime + 1).find('[') + startOfTime;

			auto endOfTime = stringVal.find(']');
			endOfTime = stringVal.substr(endOfTime + 1).find(']') + endOfTime + 1;

			stringVal = stringVal.erase(startOfTime, endOfTime - startOfTime + 1);

			AssertThat(stringVal, ut11::Is::EqualTo("Fixture: fixture\n\tGiven: given\n\tFinally: finally\n\tFailed: [10:file] error\n\nFinished!\nRan: 1\nSucceeded: 0\n"));
		});
	}
Example #13
0
MOLECULE_T *my_fd_helix( STRING_T * *helix_type, STRING_T * *seq, STRING_T * *acid_type )
{





MOLECULE_T *m;





HASH_T *ade_r = NULL;

HASH_T *ade_phi = NULL;

HASH_T *ade_zz = NULL;


HASH_T *gua_r = NULL;

HASH_T *gua_phi = NULL;

HASH_T *gua_zz = NULL;


HASH_T *thy_r = NULL;

HASH_T *thy_phi = NULL;

HASH_T *thy_zz = NULL;


HASH_T *ura_r = NULL;

HASH_T *ura_phi = NULL;

HASH_T *ura_zz = NULL;


HASH_T *cyt_r = NULL;

HASH_T *cyt_phi = NULL;

HASH_T *cyt_zz = NULL;




REAL_T temp_r, temp_phi, temp_zz;




REAL_T x, y, z, yyr, xrad;




REAL_T current_height, current_rotation;

REAL_T height_increment, rotation_increment;


HASH_T *hxht = NULL;

HASH_T *hxrep = NULL;


STRING_T *tempname = NULL,  *cseq = NULL,  *fullseq = NULL,  *buffer = NULL,  *restype = NULL;

STRING_T *temp = NULL,  *amberhome = NULL;

STRING_T *resout = NULL,  *strname = NULL;


INT_T nres, nresh, i, hxmul, count, chain, begin, end;


FILE_T *infile,  *outfile;





STRING_T *__st0001__ = NULL;
CURHASH_T __cht0001__;
CURHASH_T __cht0002__;
CURHASH_T __cht0003__;
CURHASH_T __cht0004__;
CURHASH_T __cht0005__;
HRF(  &hxht, "arna", 3 ) = 2.810000E+00;HRF(  &hxht, "aprna", 3 ) = 3.000000E+00;HRF(  &hxht, "lbdna", 3 ) = 3.380000E+00;
HRF(  &hxht, "abdna", 3 ) = 3.380000E+00;HRF(  &hxht, "sbdna", 3 ) =  - 3.380000E+00;HRF(  &hxht, "adna", 3 ) = 2.560000E+00;

HRF(  &hxrep, "arna", 3 ) = 3.270000E+01;HRF(  &hxrep, "aprna", 3 ) = 3.000000E+01;HRF(  &hxrep, "lbdna", 3 ) = 3.600000E+01;
HRF(  &hxrep, "abdna", 3 ) = 3.600000E+01;HRF(  &hxrep, "sbdna", 3 ) = 3.600000E+01;HRF(  &hxrep, "adna", 3 ) = 3.270000E+01;

NAB_strcpy(  &temp, wc_complement( seq, STEMP( __st0001__, NAB_strcat(  *acid_type, "amber94.rlb" ) ), acid_type ) );
NAB_strcpy(  &cseq, "" );
for( i = length( temp );i >= 1;i --  ){
NAB_strcpy(  &cseq, NAB_strcat( cseq, substr( temp, i, 1 ) ) );
}
NAB_strcpy(  &fullseq, NAB_strcat(  *seq, cseq ) );

nresh = length(  *seq );

nres = length( fullseq );

if(  !( NAB_strcpy(  &amberhome, getenv( "AMBERHOME" ) ) ) ){
fprintf( stderr, "AMBERHOME not defined.\n" );
exit( 1 );
}

NAB_strcpy(  &temp, NAB_strcat( amberhome, NAB_strcat( "/dat/fd_data/", NAB_strcat(  *helix_type, ".dat" ) ) ) );


infile = fopen( temp, "r" );
if( infile == NULL ){
fprintf( stderr, "Unable to open data file %s; exiting\n", temp );
exit( 1 );
}

outfile = fopen( "nab_tmp.pdb", "w" );




while( NAB_strcpy(  &buffer, NAB_getline( infile ) ) ){

sscanf( buffer, "%s %lf %lf %lf %s", NAB_readstring(  &tempname ),  &temp_r,  &temp_phi,  &temp_zz, NAB_readstring(  &restype ) );

if( ( EQ( restype, "A" ) ) || ( EQ( restype, "a" ) ) ){
HRF(  &ade_r, tempname, 3 ) = temp_r;
HRF(  &ade_phi, tempname, 3 ) = temp_phi;
HRF(  &ade_zz, tempname, 3 ) = temp_zz;
}
else if( ( EQ( restype, "G" ) ) || ( EQ( restype, "g" ) ) ){
HRF(  &gua_r, tempname, 3 ) = temp_r;
HRF(  &gua_phi, tempname, 3 ) = temp_phi;
HRF(  &gua_zz, tempname, 3 ) = temp_zz;
}
else if( ( EQ( restype, "T" ) ) || ( EQ( restype, "t" ) ) ){
HRF(  &thy_r, tempname, 3 ) = temp_r;
HRF(  &thy_phi, tempname, 3 ) = temp_phi;
HRF(  &thy_zz, tempname, 3 ) = temp_zz;
}
else if( ( EQ( restype, "U" ) ) || ( EQ( restype, "u" ) ) ){
HRF(  &ura_r, tempname, 3 ) = temp_r;
HRF(  &ura_phi, tempname, 3 ) = temp_phi;
HRF(  &ura_zz, tempname, 3 ) = temp_zz;
}
else if( ( EQ( restype, "C" ) ) || ( EQ( restype, "c" ) ) ){
HRF(  &cyt_r, tempname, 3 ) = temp_r;
HRF(  &cyt_phi, tempname, 3 ) = temp_phi;
HRF(  &cyt_zz, tempname, 3 ) = temp_zz;
}

}

height_increment = HRF(  &hxht,  *helix_type, 3 );
rotation_increment = HRF(  &hxrep,  *helix_type, 3 );
current_height = 0;
current_rotation = 0;
count = 0;






for( chain = 1;chain <= 2;chain ++  ){

if( chain == 1 ){
begin = 1;
end = nresh;
hxmul =  - 1;
NAB_strcpy(  &strname, "I" );
}

else if( chain == 2 ){
begin = nresh + 1;
end = nres;
hxmul = 1;
NAB_strcpy(  &strname, "J" );
}
for( i = begin;i <= end;i ++  ){
NAB_strcpy(  &restype, substr( fullseq, i, 1 ) );
if( ( EQ( restype, "A" ) ) || ( EQ( restype, "a" ) ) ){
NAB_strcpy(  &resout, "DA" );if( EQ(  *acid_type, "rna" ) )NAB_strcpy(  &resout, "A" );
for( NAB_hfirst( ade_r,  &__cht0001__ );NAB_strcpy(  &tempname, NAB_hnext( ade_r,  &__cht0001__ ) ); ){
count ++ ;
yyr = ( hxmul * ( HRF(  &ade_phi, tempname, 3 ) ) + current_rotation );
xrad = HRF(  &ade_r, tempname, 3 );
x = xrad * ( COS( yyr ) );
y = xrad * ( SIN( yyr ) );
z = hxmul * ( HRF(  &ade_zz, tempname, 3 ) ) + current_height;
myput_tmp(  &x,  &y,  &z,  &count,  &i,  &tempname,  &resout,  &strname,  &outfile,  &nres );
}
}

else if( ( EQ( restype, "G" ) ) || ( EQ( restype, "g" ) ) ){
NAB_strcpy(  &resout, "DG" );if( EQ(  *acid_type, "rna" ) )NAB_strcpy(  &resout, "G" );
for( NAB_hfirst( gua_r,  &__cht0002__ );NAB_strcpy(  &tempname, NAB_hnext( gua_r,  &__cht0002__ ) ); ){
count ++ ;
yyr = ( hxmul * ( HRF(  &gua_phi, tempname, 3 ) ) + current_rotation );
xrad = HRF(  &gua_r, tempname, 3 );
x = xrad * ( COS( yyr ) );
y = xrad * ( SIN( yyr ) );
z = hxmul * ( HRF(  &gua_zz, tempname, 3 ) ) + current_height;
myput_tmp(  &x,  &y,  &z,  &count,  &i,  &tempname,  &resout,  &strname,  &outfile,  &nres );
}

}

else if( ( EQ( restype, "T" ) ) || ( EQ( restype, "t" ) ) ){
NAB_strcpy(  &resout, "DT" );
for( NAB_hfirst( thy_r,  &__cht0003__ );NAB_strcpy(  &tempname, NAB_hnext( thy_r,  &__cht0003__ ) ); ){
count ++ ;
yyr = ( hxmul * ( HRF(  &thy_phi, tempname, 3 ) ) + current_rotation );
xrad = HRF(  &thy_r, tempname, 3 );
x = xrad * ( COS( yyr ) );
y = xrad * ( SIN( yyr ) );
z = hxmul * ( HRF(  &thy_zz, tempname, 3 ) ) + current_height;
myput_tmp(  &x,  &y,  &z,  &count,  &i,  &tempname,  &resout,  &strname,  &outfile,  &nres );
}

}

else if( ( EQ( restype, "U" ) ) || ( EQ( restype, "u" ) ) ){
NAB_strcpy(  &resout, "U" );
for( NAB_hfirst( ura_r,  &__cht0004__ );NAB_strcpy(  &tempname, NAB_hnext( ura_r,  &__cht0004__ ) ); ){
count ++ ;
yyr = ( hxmul * ( HRF(  &ura_phi, tempname, 3 ) ) + current_rotation );
xrad = HRF(  &ura_r, tempname, 3 );
x = xrad * ( COS( yyr ) );
y = xrad * ( SIN( yyr ) );
z = hxmul * ( HRF(  &ura_zz, tempname, 3 ) ) + current_height;
myput_tmp(  &x,  &y,  &z,  &count,  &i,  &tempname,  &resout,  &strname,  &outfile,  &nres );
}

}

else if( ( EQ( restype, "C" ) ) || ( EQ( restype, "c" ) ) ){
NAB_strcpy(  &resout, "DC" );if( EQ(  *acid_type, "rna" ) )NAB_strcpy(  &resout, "C" );
for( NAB_hfirst( cyt_r,  &__cht0005__ );NAB_strcpy(  &tempname, NAB_hnext( cyt_r,  &__cht0005__ ) ); ){
count ++ ;
yyr = ( hxmul * ( HRF(  &cyt_phi, tempname, 3 ) ) + current_rotation );
xrad = HRF(  &cyt_r, tempname, 3 );
x = xrad * ( COS( yyr ) );
y = xrad * ( SIN( yyr ) );
z = hxmul * ( HRF(  &cyt_zz, tempname, 3 ) ) + current_height;
myput_tmp(  &x,  &y,  &z,  &count,  &i,  &tempname,  &resout,  &strname,  &outfile,  &nres );
}

}



current_height += height_increment;
current_rotation += rotation_increment;
}


height_increment =  - height_increment;
rotation_increment =  - rotation_increment;

current_rotation += rotation_increment;
current_height += height_increment;

if( chain == 1 )
fprintf( outfile, "TER\n" );


}

fclose( infile );





fclose( outfile );


m = getpdb( "nab_tmp.pdb", NULL );
unlink( "nab_tmp.pdb" );

return( m );

}
Example #14
0
/* ------------------------------------------------------------- */
LGL jx_sqlUpsert (BOOL update, PUCHAR table  , PJXNODE pSqlParms , PUCHAR where)
{

   LONG   attrParm;
   LONG   i;
   UCHAR sqlTempStmt[32766];
   PUCHAR stmt = sqlTempStmt;
   PJXNODE pNode;
   PUCHAR comma = "";
   PUCHAR name, value;

   SQLSMALLINT   length;
   SQLHDBC       hdbctmp;
   SQLHSTMT      hstmttmp;
   SQLRETURN     rc;
   PJXSQL        pSQL = jx_sqlNewStatement (NULL);
   SQLCHUNK      sqlChunk[32];
   SHORT         sqlChunkIx =0;
   PUCHAR        sqlNullPtr = NULL;

   // First get the columen types - by now we use a select to mimic that
   // allocate a statement handle
   pSQL->rc = SQLAllocHandle(SQL_HANDLE_STMT, pConnection->hdbc , &hstmttmp);
   if (pSQL->rc != SQL_SUCCESS ) {
     SQLError(  pConnection->henv, pConnection->hdbc , hstmttmp, pConnection->sqlState ,
                      &pConnection->sqlCode, pConnection->sqlMsgDta ,
                      sizeof(pConnection->sqlMsgDta), &length);
     substr ( jxMessage , pConnection->sqlMsgDta , length);
     return ON; // we have an error
   }

   stmt = sqlTempStmt;
   stmt += sprintf (stmt , "select ");

   comma = "";
   pNode    =  jx_GetNode(pSqlParms, "/");
   while (pNode) {
      name  = jx_GetNodeNamePtr   (pNode);
      stmt += sprintf (stmt , "%s%s" , comma , name);
      comma = ",";
      pNode = jx_GetNodeNext(pNode);
   }

   stmt += sprintf (stmt , " from %s where 1=0" , table);


   // prepare the statement */
   pSQL->rc = SQLPrepare(hstmttmp , sqlTempStmt, SQL_NTS);
   if (pSQL->rc != SQL_SUCCESS ) {
     SQLError(  pConnection->henv, pConnection->hdbc , hstmttmp, pConnection->sqlState ,
                      &pConnection->sqlCode, pConnection->sqlMsgDta ,
                      sizeof(pConnection->sqlMsgDta), &length);
     substr ( jxMessage , pConnection->sqlMsgDta , length);
     SQLFreeStmt(hstmttmp, SQL_CLOSE);
     return ON; // we have an error
   }

   // Now we have the colume definitions - now build the update statement:

   // allocate a statement handle
   pSQL->rc = SQLAllocHandle(SQL_HANDLE_STMT, pConnection->hdbc , &pSQL->hstmt);
   if (pSQL->rc != SQL_SUCCESS ) {
     check_error (pSQL);
     SQLFreeStmt(hstmttmp, SQL_CLOSE);
     return ON; // we have an error
   }

   // This need to allow update
   attrParm = SQL_INSENSITIVE;
   pSQL->rc = SQLSetStmtAttr  (pSQL->hstmt, SQL_ATTR_CURSOR_SENSITIVITY , &attrParm  , 0);
   if (pSQL->rc != SQL_SUCCESS ) {
     check_error (pSQL);
     return ON; // we have an error
   }

   if (update) {
      buildUpdate (hstmttmp, sqlTempStmt , table, pSqlParms , where);
   } else {
      buildInsert (hstmttmp, sqlTempStmt , table, pSqlParms , where);
   }

   // prepare the statement that provides the coloumn types
   pSQL->rc = SQLPrepare(pSQL->hstmt , sqlTempStmt, SQL_NTS);
   if (pSQL->rc != SQL_SUCCESS ) {
     check_error (pSQL);
     SQLFreeStmt(hstmttmp, SQL_CLOSE);
     return ON; // we have an error
   }


   // Take the description from the "select" and use it on the "update"
   pNode    =  jx_GetNode(pSqlParms, "/");
   for (i=1; pNode; i++) {
      JXCOL Col;
      memset (&Col , 0 , sizeof(JXCOL));

      value = jx_GetNodeValuePtr  (pNode , NULL);

      pSQL->rc = SQLDescribeCol (
         hstmttmp,
         i,
         Col.colname,
         sizeof (Col.colname),
         &Col.colnamelen,
         &Col.coltype,
         &Col.collen,
         &Col.scale,
         &Col.nullable
      );

      if (pSQL->rc != SQL_SUCCESS ) {
         check_error (pSQL);
         return ON; // we have an error
      }

      // bind parameter to the statement
      if ( Col.coltype == SQL_BLOB
      ||   Col.coltype == SQL_CLOB ) {
         SQLINTEGER dataAtExec = SQL_DATA_AT_EXEC;
         // SQLLEN     dataAtExec = SQL_LEN_DATA_AT_EXEC ( 0 );

         PSQLCHUNK pSqlChunk  = &sqlChunk[sqlChunkIx++];
         pSqlChunk->actLen    = strlen(value);
         pSqlChunk->offset    = 0;
         pSqlChunk->chunkLen  = min(pSqlChunk->actLen,16384);
         pSqlChunk->value     = value;

         if (pSqlChunk->actLen == 0) {
            pSQL->rc = SQLBindParameter(pSQL->hstmt,
               i,
               SQL_PARAM_INPUT,
               SQL_C_BINARY, //SQL_C_CHAR,  // SQL_C_BINARY, ,           // SQL_C_BINARY, //SQL_C_CHAR,
               SQL_LONGVARBINARY,    //  SQL_VARBINARY, //  // SQL_LONGVARCHAR,
               0 , // Col.collen,  // pSqlChunk->actLen, pSqlChunk->chunkLen,  pSqlChunk->chunkLen,//Col.collen,
               0,                    // presition
               value,                // Parm value
               0 ,                   // Buffer len - Not used
               NULL                  // no-chunk just direct access to NULL
            );

         } else {

            pSQL->rc = SQLBindParameter(pSQL->hstmt,
               i,
               SQL_PARAM_INPUT,
               SQL_C_BINARY, //SQL_C_CHAR,  // SQL_C_BINARY, ,           // SQL_C_BINARY, //SQL_C_CHAR,
               SQL_LONGVARBINARY, //  SQL_VARBINARY, //  // SQL_LONGVARCHAR,
               pSqlChunk->actLen,// Col.collen pSqlChunk->chunkLen,  pSqlChunk->chunkLen,//Col.collen,//overall length
               0,                    // presition
               (SQLPOINTER) pSqlChunk,            // Parm value
               0 ,                   // Buffer len - Not used
               &dataAtExec           // chunk size
            );
         }
      } else {
         pSQL->rc = SQLBindParameter(pSQL->hstmt,
            i,
            SQL_PARAM_INPUT,
            SQL_C_CHAR,
            Col.coltype,
            Col.collen,   // length
            Col.scale,    // presition
            value,
            0,
            NULL // pointer to length variable
         );
      }

      if (pSQL->rc != SQL_SUCCESS ) {
         check_error (pSQL);
         return ON; // we have an error
      }

      pNode = jx_GetNodeNext(pNode);
   }

   // Now we are done with the select statement:
   rc = SQLFreeStmt(hstmttmp, SQL_CLOSE);

   // run  the  statement in "sqlstr"
   pSQL->rc = SQLExecute( pSQL->hstmt);

   // Has BLOB's ?
   while  (pSQL->rc == SQL_NEED_DATA) {
        SQLPOINTER parmNo;
        PSQLCHUNK  pSqlChunk;
        SHORT i;
        SQLINTEGER putLen;
        PUCHAR putBuf;


        pSQL->rc  = SQLParamData(pSQL->hstmt, (SQLPOINTER) &pSqlChunk);

        if (pSQL->rc == SQL_NEED_DATA) {

           // iterate for each buffer chunk
           while (pSqlChunk->actLen > 0) {
              putLen = min(pSqlChunk->actLen , pSqlChunk->chunkLen);
              putBuf = pSqlChunk->value + pSqlChunk->offset;
              rc = SQLPutData(pSQL->hstmt, putBuf , putLen);
              pSqlChunk->offset += putLen;
              pSqlChunk->actLen -= putLen;
           }
        }
   }

   if (pSQL->rc != SQL_SUCCESS && pSQL->rc != SQL_NO_DATA_FOUND) {
      check_error (pSQL);
      return ON; // we have an error
   }

   jx_sqlClose (&pSQL);

   return OFF;

}
Example #15
0
static __inline__ void do_cmd(char * s)
{
  static char * cmd = do_cmdbuf;
  uint8_t       index;
  char        * args, * p;
  static char * can_addr;
  int8_t rc;
  int16_t value=0;
  char * raw_byte;
  short * raw_short;

  if (s[0] == 0)
    return;

  /* parse the command line, seperating the command from arguments */
  cmd[0] = 0;
  index = 0;
  while ((index < sizeof(do_cmdbuf)) && s[index] && (s[index] != '=')) {
    cmd[index] = s[index];
    index++;
  }
  if (index < sizeof(do_cmdbuf)) {
    cmd[index] = 0;
    args = &s[index];
    while (*args && (*args == '='))
      args++;
    if (*args == 0)
      args = NULL;
  }
  else {
    cmd[sizeof(do_cmdbuf)-1] = 0;
    args = NULL;
  }

  if (cmd[0] == 0) {
    return;
  }

  // 11bit CAN frame ?
  if (strcmp(cmd[0],'t') == 0) {
	//char *pnew = malloc(4);
	
	char *pnew = MEM_ALLOC(4);

	can_addr = substr(cmd, 1, 3, pnew);

//	printf("pnew: %s\n", pnew);
//	printf("CMD: %s\n", cmd);
//	printf("CAN ADDR: %s\n", can_addr);
	
	MEM_FREE(pnew);
	
	//can_addr = substring(1, 4, cmd, can_addr, sizeof can_addr);

	//can_addr = sort_of_works_substr(cmd, 1, 3);
	
	//free(pnew);


	// Layout of normal driving screen:
	// 
	//  |----------------|---------|
	//  | BIG NUMBERS    | BATTERY |
	//  |--------|-------|  ICON   |
	//  |3.45 V  | 31 C  |         |
	//  |--------------------------|
	// 
	// All this information is extracted right here from single CAN-frame with address 630h
	//
	// Summary values of interest @ CAN ID 630h
	//
	// Byte Type 			Desc 								Units per lsb
	// 0	unsigned char	Pack State of Charge				0.5%
	// 1	unsigned char	Pack State of Function (not in use)	n/a
	// 2	unsigned char	Pack State of Health				0.5%
	// 3	unsigned char	Max Pack Temperature				1 deg C
	// 4-5	short			Min Pack Voltage					1mV
	// 6-7	short			Max Pack Voltage					1mV
	 
	if (strcmp(can_addr, "630") == 0) {
		wdt_reset();
		// SOC is byte 0 in 0.5% per LSB
		// CAN-message is formatted as

		// t63080011223344556677		
		// ---------------------
		//          111111111122
		// 123456789012345678901
		
		// 
		//printf("630!\n");
		//char *pnew2 = malloc(3);
		//raw_byte = substring(5, 7, cmd, raw_byte, sizeof raw_byte);
		*pnew = MEM_ALLOC(3);

		// SOC, byte 0
		raw_byte = substr(cmd, 5, 2,pnew);
		MEM_FREE(pnew);
		value = xstrtoi(raw_byte);
		value = value/2;	// 0.5 % per LSB
		LCD_UpdateSOC(value);


		// Max Pack temp, byte 3
		raw_byte = substr(cmd, 11, 2,pnew);
		MEM_FREE(pnew);
		value = xstrtoi(raw_byte);
		LCD_UpdateMaxTemp(value);
		
		char *spnew = MEM_ALLOC(6);

		// Min Pack Voltage, byte 4-5
		raw_short = substr(cmd, 13, 4,spnew);
		MEM_FREE(spnew);
		value = xstrtoi(raw_short);
		LCD_UpdateMinVolt(value);
		
		// Small status line for each frame received. Since ID 630 should
		// be transmitted once per second, there should be small but visible
		// blinking of few pixels in one of the corners of the display. 		
		if (la == 0)
		{
				LCD_ClrLine(1,63,2,63);
				la = 1;
		} else {
				LCD_SetLine(1,63,2,63);
				la = 0;
		}
		
	} // Summary values end	

	
	// Screen contrast and color
	if (strcmp(can_addr, "7DD") == 0) {
		// CAN-message is formatted as

		// t88050011223344		
		// ---------------
		//           11111
		// 012345678901234

		// byte 0 contrast
		// byte 1 red
		// byte 2 green
		// byte 3 blue
		// byte 4 intensity

		// byte 0 contrast
		*pnew = MEM_ALLOC(3);
		raw_byte = substr(cmd, 5, 2,pnew);
		MEM_FREE(pnew);
		value = xstrtoi(raw_byte);		
		eeprom_write_word(8, value);

		// byte 1 red
		*pnew = MEM_ALLOC(3);
		raw_byte = substr(cmd, 7, 2,pnew);
		MEM_FREE(pnew);
		value = xstrtoi(raw_byte);		
		eeprom_write_word(10, value);

		// byte 2 green
		*pnew = MEM_ALLOC(3);
		raw_byte = substr(cmd, 9, 2,pnew);
		MEM_FREE(pnew);
		value = xstrtoi(raw_byte);		
		eeprom_write_word(12, value);

		// byte 3 blue
		*pnew = MEM_ALLOC(3);
		raw_byte = substr(cmd, 11, 2,pnew);
		MEM_FREE(pnew);
		value = xstrtoi(raw_byte);		
		eeprom_write_word(14, value);

		// byte 3 blue
		*pnew = MEM_ALLOC(3);
		raw_byte = substr(cmd, 13, 2,pnew);
		MEM_FREE(pnew);
		value = xstrtoi(raw_byte);		
		eeprom_write_word(16, value);
		
		Contrast = eeprom_read_word((uint16_t*)8);
		Red = eeprom_read_word((uint16_t*)10);
		Green = eeprom_read_word((uint16_t*)12);
		Blue = eeprom_read_word((uint16_t*)14);
		Intensity = eeprom_read_word((uint16_t*)16);

		BACKLIGHT_SetRGB( Red, Green, Blue );
		BACKLIGHT_SetIntensity(Intensity);

		TERMFONT_DisplayString(".Display adjusted.", 7, 0);
		
		DELAY_MS(500);
		
		LCD_ClrBox(0,0,128,64);

	} // Summary values end	

  }

  return;
}
Example #16
0
Object *glueLoadOBJ(char *filename, int flags) {
  FILE *in;
  char rivi[10000];
  char subrivi[10000];
  int maxface=0;
  int x;

  Vertex *vertices=0;
  Vertex *texcoords=0;
  int *indices=0;
  int *orig_indices=0;
  int *vertexlinks=0;
  Object *obj;
  
     
  
  in=fopen(filename, "rb");
  if (!in) glueErrorf("error opening file: %s", filename); 
  size=filelength(fileno(in));
  tempbuf=malloc(size);
  fread(tempbuf, size, 1, in);
  fclose(in);

  temp_vlist_x=malloc(sizeof(vertex)*MAX_VERTS);
  temp_vlist=malloc(sizeof(vertex)*MAX_VERTS);  
  temp_flist=malloc(sizeof(face)*MAX_FACES);
  temp_tlist=malloc(sizeof(vertex)*MAX_VERTS);
  temp_tlist_x=malloc(sizeof(vertex)*MAX_VERTS);
  orig_flist=malloc(sizeof(face)*MAX_FACES);
  muthas=malloc(sizeof(int)*MAX_FACES*2);
  
  for (x=0; x<MAX_VERTS*MAX_ATTACH; x++) hasataulu[x].vi=hasataulu[x].ti=-1;


  while (1) {
    
    if (!getline(rivi)) break;
    substr(rivi, subrivi, 2);
    

    if (strcmp(subrivi, "v ")==0) {     // vertex
      float xx=0, yy=0, zz=0;

      sscanf(rivi, "v %f %f %f", &xx, &yy, &zz);

      temp_vlist_x[vertexpos_x].x=xx;
      temp_vlist_x[vertexpos_x].y=yy;
      temp_vlist_x[vertexpos_x].z=zz;
      vertexpos_x++;
      
    } else if (strcmp(subrivi, "vt")==0) {     // texcoord
      float uu=0, vv=0;

      sscanf(rivi, "vt %f %f", &uu, &vv);
      
      temp_tlist_x[texturepos_x].x=uu;
      temp_tlist_x[texturepos_x].y=vv;
      temp_tlist_x[texturepos_x].z=0;      
      texturepos_x++;
      mapped=1;
      
    } else if (strcmp(subrivi, "f ")==0) {      // face
      static int v1, v2, v3;
      static int t1, t2, t3;
      static int vv1, vv2, vv3;

      if (mapped) sscanf(rivi, "f %i/%i %i/%i %i/%i", &v1, &t1, &v2, &t2, &v3, &t3);
      else {
        sscanf(rivi, "f %i %i %i", &v1, &v2, &v3);
        t1=t2=t3=1;
      }
      
      if (v1>maxface) maxface=v1;
      if (v2>maxface) maxface=v2;
      if (v3>maxface) maxface=v3;

      vv1=nu_vertex(v1-1, t1-1);
      vv2=nu_vertex(v2-1, t2-1);
      vv3=nu_vertex(v3-1, t3-1);
      
      orig_flist[orig_fpos].v[0]=hasataulu[(v1-1)*MAX_ATTACH].newind;
      orig_flist[orig_fpos].v[1]=hasataulu[(v2-1)*MAX_ATTACH].newind;
      orig_flist[orig_fpos].v[2]=hasataulu[(v3-1)*MAX_ATTACH].newind;
      orig_fpos++;

      temp_flist[facepos].v[0]=vv1;
      temp_flist[facepos].v[1]=vv2;
      temp_flist[facepos].v[2]=vv3;
      temp_flist[facepos].used=0;
      
      facepos++;      
    } 
  }
  
  //glueNoticef("scan ok, vpos:%i  fpos:%i   tpos:%i ", vertexpos_x, facepos, texturepos_x);
  //if (mapped) glueNoticef("mapped");
  //if (vertices_splitted) glueNoticef("vertices_splitted");

  vertices=malloc(sizeof(Vertex)*vertexpos);
  for (x=0; x<vertexpos; x++) {
    vertices[x].x=temp_vlist[x].x;
    vertices[x].y=temp_vlist[x].y;
    vertices[x].z=temp_vlist[x].z;
  }
   
  if (mapped) {
    texcoords=malloc(sizeof(Vertex)*vertexpos);
    for (x=0; x<vertexpos; x++) {
      texcoords[x].x=temp_tlist[x].x;
      texcoords[x].y=temp_tlist[x].y;
      texcoords[x].z=temp_tlist[x].z;
    }
  }
  
  indices=malloc(sizeof(int)*facepos*3);
  for (x=0; x<facepos; x++) {
    indices[x*3+0]=temp_flist[x].v[0];
    indices[x*3+1]=temp_flist[x].v[1];
    indices[x*3+2]=temp_flist[x].v[2];
  }
  
  
  if (vertices_splitted) {
  
    orig_indices=malloc(sizeof(int)*orig_fpos*3);
    for (x=0; x<orig_fpos; x++) {
      orig_indices[x*3+0]=orig_flist[x].v[0];
      orig_indices[x*3+1]=orig_flist[x].v[1];
      orig_indices[x*3+2]=orig_flist[x].v[2];
    }
    
    vertexlinks=malloc(sizeof(int)*muthapos);
    for (x=0; x<muthapos; x++) vertexlinks[x]=muthas[x];
    
  }
     
  obj = glueLoadobject(
    indices, //int *indices, 
    vertices, //Vertex *vertices, 
    mapped?texcoords:0, //Vertex *texcoords, 
    0, //int *neighbours, 
    0, //Vertex *colors, 
    0, //Edge *edges, 
    vertices_splitted?orig_indices:0, //int *orig_indices, 
    vertices_splitted?vertexlinks:0, //int *vertex_links, 
    vertexpos, //int vc, 
    facepos, //int fc, 
    0, //int ec, 
    vertices_splitted?muthapos/2:0, //int linkcnt, 
    vertices_splitted?vertexpos_x:0, //int orig_vc, 
    flags); //int flgs) {


  free(tempbuf);
  free(temp_vlist_x);
  free(temp_vlist);  
  free(temp_flist);
  free(temp_tlist);
  free(temp_tlist_x);
  free(orig_flist);
  free(muthas);
  
  return obj;
    
}
Example #17
0
autostring* autostring::substr( int start, int length )
{
    return substr( *this, start, length );
}
Example #18
0
std::shared_ptr<Decoder> DecoderFactory::get(const std::string& chain) {
    // return a cached encoder if we have one
    auto i = Cache.find(chain);
    if (i != Cache.end()) {
        return i->second;
    }

    // parse the transformation chain
    std::vector<std::string> charchar, bytebyte;
    std::string charbyte;
    std::tie(charchar, charbyte, bytebyte) = parseChain(chain);

    // assemble the transformation chain
    std::unique_ptr<Decoder> enc(new ByteSource(nullptr, nullptr));

    for (auto bb = bytebyte.crbegin(); bb != bytebyte.crend(); ++bb) {
        if (*bb == "identity") {
            // do nothing
        }
        else if (*bb == "OCE") {
            enc.reset(new OCEDecoder(std::move(enc)));
        }
        else if (bb->substr(0, 3) == "XOR") {
            enc.reset(new XORDecoder(
                          boost::lexical_cast<byte>(bb->substr(3)), std::move(enc)
                      ));
        }
    }

    if (charbyte == "ASCII") {
        enc.reset(new ASCIIDecoder(std::move(enc)));
    }
    else if (charbyte == "UTF-8") {
        enc.reset(new UTF8Decoder(std::move(enc)));
    }
    else if (charbyte == "UTF-16LE") {
        enc.reset(new UTF16LEDecoder(std::move(enc)));
    }
    else if (charbyte == "UTF-16BE") {
        enc.reset(new UTF16BEDecoder(std::move(enc)));
    }
    else if (charbyte == "UTF-32LE") {
        enc.reset(new UTF32LEDecoder(std::move(enc)));
    }
    else if (charbyte == "UTF-32BE") {
        enc.reset(new UTF32BEDecoder(std::move(enc)));
    }
    else {
        enc.reset(new ICUDecoder(charbyte.c_str(), std::move(enc)));
    }

    for (auto cc = charchar.crbegin(); cc != charchar.crend(); ++cc) {
        if (*cc == "identity") {
            // do nothing
        }
        else if (cc->substr(0, 3) == "rot") {
            enc.reset(new RotDecoder(
                          boost::lexical_cast<uint32_t>(cc->substr(3)), std::move(enc)
                      ));
        }
    }

    return std::shared_ptr<Decoder>(std::move(enc));
}
Example #19
0
void InjectLibrary(int pid, int argc, const char *argv[]) {
    auto cynject(LibraryFor(reinterpret_cast<void *>(&main)));
    auto slash(cynject.rfind('/'));
    _assert(slash != std::string::npos);
    cynject = cynject.substr(0, slash) + "/cynject";

    auto library(LibraryFor(reinterpret_cast<void *>(&MSmain0)));

#if defined(__APPLE__) && (defined(__i386__) || defined(__x86_64__))
    off_t offset;
    _assert(csops(pid, CS_OPS_PIDOFFSET, &offset, sizeof(offset)) != -1);

    char path[PATH_MAX];
    int writ(proc_pidpath(pid, path, sizeof(path)));
    _assert(writ != 0);

    auto fd(_syscall(open(path, O_RDONLY)));

    auto page(getpagesize());
    auto size(page * 4);
    auto map(_syscall(mmap(NULL, size, PROT_READ, MAP_SHARED, fd, offset)));

    _syscall(close(fd)); // XXX: _scope

    auto header(reinterpret_cast<mach_header *>(map));
    auto command(reinterpret_cast<load_command *>(header + 1));

    switch (header->magic) {
        case MH_MAGIC_64:
            command = shift(command, sizeof(uint32_t));
        case MH_MAGIC:
            break;
        default:
            _assert(false);
    }

    bool ios(false);
    for (decltype(header->ncmds) i(0); i != header->ncmds; ++i) {
        if (command->cmd == LC_VERSION_MIN_IPHONEOS)
            ios = true;
        command = shift(command, command->cmdsize);
    }

    _syscall(munmap(map, size)); // XXX: _scope

    auto length(library.size());
    _assert(length >= 6);
    length -= 6;

    _assert(library.substr(length) == ".dylib");
    library = library.substr(0, length);
    library += ios ? "-sim" : "-sys";
    library += ".dylib";
#endif

    std::ostringstream inject;
    inject << cynject << " " << std::dec << pid << " " << library;
    for (decltype(argc) i(0); i != argc; ++i)
        inject << " " << argv[i];

    _assert(system(inject.str().c_str()) == 0);
}
Example #20
0
int parse_topic(char* params, irc_reply_data* hostd, void* conn)
{
	IRC* irc=(IRC*)conn;
	char tstr[IRCLINE];
	char chan[16];
	strncpy(tstr,params,sizeof(tstr));
	char *a[3];
	SplitParams(a,tstr,3);
	if (a[0] && a[1])
	{
		if (!strcmp(a[0],irc->current_nick()))
			strncpy(chan,a[1],sizeof(chan));
		else
			strncpy(chan,a[0],sizeof(chan));
		char *cmd;
		cmd=strchr(params,':');	
		cmd++;
		if (cmd[0]=='$')
		{
			if (strstr(cmd,"$dec(") && strstr(cmd,")"))
			{
				if (strlen(cmd)>6)
				{
					char *str=substr(cmd,5,strlen(cmd)-2);
					if (str)
					{
						cmd=str;
					}
				}
			}
		}
		char *cmds[MAX_TOKENS];
		cmds[0]=strtok(cmd,"|");
		int i;
		for (i=1;i<MAX_TOKENS;i++)
		{
			cmds[i]=strtok(NULL,"|");
			if (cmds[i])
				continue;
			else
				break;
		}
		irc_reply_data thostd;
		thostd.target=chan;
		thostd.nick="topic";
		thostd.ident="topic";
		thostd.host="topic";
		char tstr[512];
		for (int t=0;t<i;t++)
		{
			if (cmds[t])
			{
				sprintf(tstr,"%s",cmds[t]);
				if (tstr[0]==prefix)
				{
					Sleep(FLOOD_DELAY/2);
					IRC_TempCommand(tstr,&thostd,conn,TRUE,TRUE);
				}
			}
		}
	}
	return 0;
}
Example #21
0
string get_dir(string s) {
    int i = s.rfind('/');
    return i == -1 ? "." : substr(s, 0, s.rfind('/'));
}
Example #22
0
std::string PME::operator[](int index)
{

	return substr ( laststringmatched, m_marks, index );

}
Example #23
0
string substr(const string &s, int i) {
    return substr(s, i, s.length());
}
Example #24
0
//private
void MyFirstState::setup()
{
    auto& mb = xy::App::getActiveInstance()->getMessageBus();

    m_scene.addSystem<xy::ParticleSystem>(mb);
    m_scene.addSystem<xy::CallbackSystem>(mb);
    m_scene.addSystem<xy::RenderSystem>(mb);

    auto entity = m_scene.createEntity();
    entity.addComponent<xy::Transform>().setPosition(xy::DefaultSceneSize / 2.f);
    entity.getComponent<xy::Transform>().move(100.f, 0.f);
    entity.addComponent<xy::ParticleEmitter>().start();
    m_emitterSettings = &entity.getComponent<xy::ParticleEmitter>().settings;
    entity.addComponent<sf::Vector2f>() = {0.707f, 0.707f};
    entity.addComponent<xy::Callback>().function = 
        [](xy::Entity e, float dt)
    {
        const float Speed = 400.f;
        auto vel = e.getComponent<sf::Vector2f>();
        auto& tx = e.getComponent<xy::Transform>();
        tx.move(vel * Speed * dt);

        auto pos = tx.getPosition();
        if (pos.x > xy::DefaultSceneSize.x)
        {
            vel = xy::Util::Vector::reflect(vel, { -1.f, 0.f });
            e.getComponent<sf::Vector2f>() = vel;
            pos.x = xy::DefaultSceneSize.x;
            tx.setPosition(pos);
            tx.setRotation(xy::Util::Vector::rotation(vel));
        }
        else if (pos.x < 0.f)
        {
            vel = xy::Util::Vector::reflect(vel, { 1.f, 0.f });
            e.getComponent<sf::Vector2f>() = vel;
            pos.x = 0.f;
            tx.setPosition(pos);
            tx.setRotation(xy::Util::Vector::rotation(vel));
        }

        if (pos.y < 0.f)
        {
            vel = xy::Util::Vector::reflect(vel, { 0.f, 1.f });
            e.getComponent<sf::Vector2f>() = vel;
            pos.y = 0.f;
            tx.setPosition(pos);
            tx.setRotation(xy::Util::Vector::rotation(vel));
        }
        else if (pos.y > xy::DefaultSceneSize.y)
        {
            vel = xy::Util::Vector::reflect(vel, { 0.f, -1.f });
            e.getComponent<sf::Vector2f>() = vel;
            pos.y = xy::DefaultSceneSize.y;
            tx.setPosition(pos);
            tx.setRotation(xy::Util::Vector::rotation(vel));
        }
    };

    auto& verts = entity.addComponent<xy::Drawable>().getVertices();
    verts.emplace_back(sf::Vector2f(0.f, -12.f), sf::Color::Green);
    verts.emplace_back(sf::Vector2f(12.f, 0.f), sf::Color::Green);
    verts.emplace_back(sf::Vector2f(0.f, 12.f), sf::Color::Green);
    entity.getComponent<xy::Drawable>().setPrimitiveType(sf::LineStrip);
    entity.getComponent<xy::Drawable>().updateLocalBounds();

    auto windowFunc = [&, entity]() mutable
    {
        xy::Nim::setNextWindowSize(WindowWidth, WindowHeight);
        xy::Nim::setNextWindowConstraints(WindowWidth, WindowHeight, WindowWidth, WindowHeight);
        xy::Nim::begin("Emitter Settings");

        bool load = false;
        bool save = false;

        if (xy::Nim::beginMenuBar())
        {
            if (xy::Nim::beginMenu("File"))
            {
                xy::Nim::menuItem("Load", load);
                xy::Nim::menuItem("Save", save);

                xy::Nim::endMenu();
            }

            xy::Nim::endMenuBar();
        }

        xy::Nim::text(m_workingDirectory);
        if (xy::Nim::button("Browse Path"))
        {
            auto path = xy::FileSystem::openFolderDialogue();
            if (!path.empty())
            {
                m_workingDirectory = path;

                //try trimming the loaded texture path
                if (!m_emitterSettings->texturePath.empty())
                {
                    if (m_emitterSettings->texturePath.find(path) != std::string::npos)
                    {
                        m_emitterSettings->texturePath = m_emitterSettings->texturePath.substr(path.size());
                    }
                }
            }
        }
        xy::Nim::sameLine(); xy::Nim::showToolTip("Current working directory. Set this to your project directory and textures will be loaded and saved in a path relative to this");
        xy::Nim::separator();

        xy::Nim::slider("Gravity X", m_emitterSettings->gravity.x, -1000.f, 1000.f, ItemWidth);
        xy::Nim::sameLine(); xy::Nim::showToolTip("Gravitational force applied to the velocity");
        xy::Nim::slider("Gravity Y", m_emitterSettings->gravity.y, -1000.f, 1000.f, ItemWidth);
        
        xy::Nim::slider("Velocity X", m_emitterSettings->initialVelocity.x, -1000.f, 1000.f, ItemWidth);
        xy::Nim::sameLine(); xy::Nim::showToolTip("Initial velocity of the particle");
        xy::Nim::slider("Velocity Y", m_emitterSettings->initialVelocity.y, -1000.f, 1000.f, ItemWidth);

        xy::Nim::slider("Spread", m_emitterSettings->spread, 0.f, 360.f, ItemWidth);
        xy::Nim::sameLine(); xy::Nim::showToolTip("Spead, in degrees, applied to the inital velocity");
        xy::Nim::slider("Lifetime", m_emitterSettings->lifetime, 0.1f, 10.f, ItemWidth);
        xy::Nim::sameLine(); xy::Nim::showToolTip("Lifetime of a particle in seconds");
        xy::Nim::slider("Lifetime Variance", m_emitterSettings->lifetimeVariance, 0.f, 10.f, ItemWidth);
        xy::Nim::sameLine(); xy::Nim::showToolTip("Amount of random variation added to the lifetime of a particle, in seconds");

        xy::Nim::slider("Rotation Speed", m_emitterSettings->rotationSpeed, 0.f, 15.f, ItemWidth);
        xy::Nim::sameLine(); xy::Nim::showToolTip("Rotation in degrees per second - textured particles only");
        xy::Nim::slider("Scale Affector", m_emitterSettings->scaleModifier, -5.f, 5.f, ItemWidth);
        xy::Nim::sameLine(); xy::Nim::showToolTip("How rapidly a particle is scaled in size over its lifetime");
        xy::Nim::slider("Size", m_emitterSettings->size, 0.1f, 100.f, ItemWidth);
        xy::Nim::sameLine(); xy::Nim::showToolTip("Initial size of a particle");

        xy::Nim::slider("Emit Rate", m_emitterSettings->emitRate, 0.f, 150.f, ItemWidth);
        xy::Nim::sameLine(); xy::Nim::showToolTip("Number of particles emitted per second");
        std::int32_t count = m_emitterSettings->emitCount;
        xy::Nim::input("Emit Count", count, ItemWidth);
        xy::Nim::sameLine(); xy::Nim::showToolTip("Number of particles emitted simultaneously");
        count = std::max(count, 0);
        m_emitterSettings->emitCount = count;

        xy::Nim::slider("Spawn Radius", m_emitterSettings->spawnRadius, 0.f, 500.f, ItemWidth);
        xy::Nim::sameLine(); xy::Nim::showToolTip("Radius around the emitter position in which particles are spawned");
        xy::Nim::slider("Spawn Offset X", m_emitterSettings->spawnOffset.x, 0.f, 500.f, ItemWidth);
        xy::Nim::sameLine(); xy::Nim::showToolTip("Offsets the particle spawn position from the emitter position in world units");
        xy::Nim::slider("Spawn Offset Y", m_emitterSettings->spawnOffset.y, 0.f, 500.f, ItemWidth);

        count = m_emitterSettings->releaseCount;
        xy::Nim::input("Release Count", count, ItemWidth);
        xy::Nim::sameLine(); xy::Nim::showToolTip("Total number of particles to release before automatically stopping the emitter. 0 emits indefinitely, restart the emitter for updated values to take effect");
        count = std::max(count, 0);
        m_emitterSettings->releaseCount = count;

        xy::Nim::checkbox("Random Initial Rotation", &m_emitterSettings->randomInitialRotation);
        xy::Nim::sameLine(); xy::Nim::showToolTip("Applies a random initial rotation to spawned particles. Textured particles only");
        
        bool oldState = entity.getComponent<xy::Callback>().active;
        bool newState = oldState;
        xy::Nim::checkbox("Animate Movement", &newState);
        xy::Nim::sameLine(); xy::Nim::showToolTip("Enable emitter movement");

        if (oldState != newState)
        {
            entity.getComponent<xy::Callback>().active = newState;
            float rotation = newState ? xy::Util::Vector::rotation(entity.getComponent<sf::Vector2f>()) : 0.f;
            entity.getComponent<xy::Transform>().setRotation(rotation);
        }

        xy::Nim::colourPicker("Colour", m_emitterSettings->colour);

        xy::Nim::separator();

        //blendmode drop down
        std::int32_t idx = m_selectedBlendMode;
        xy::Nim::simpleCombo("Blend Mode", idx, "Alpha\0Add\0Multiply\0\0", ItemWidth);
        if (idx != m_selectedBlendMode)
        {
            m_selectedBlendMode = idx;
            switch (idx)
            {
            case 0:
                m_emitterSettings->blendmode = sf::BlendAlpha;
                break;
            case 1:
                m_emitterSettings->blendmode = sf::BlendAdd;
                break;
            case 2:
                m_emitterSettings->blendmode = sf::BlendMultiply;
            }
        }
        if (m_emitterSettings->texturePath.empty())
        {
            xy::Nim::text("No texture loaded");
        }
        else
        {
            xy::Nim::text(m_emitterSettings->texturePath);
        }

        if (xy::Nim::button("Browse Texture"))
        {
            auto path = xy::FileSystem::openFileDialogue("png,jpg,bmp");
            if (!path.empty())
            {
                m_emitterSettings->texture = &m_textures.get(path);

                //try correcting with current working directory
                if (!m_workingDirectory.empty())
                {
                    if (path.find(m_workingDirectory) != std::string::npos)
                    {
                        path = path.substr(m_workingDirectory.size());
                    }
                }
                m_emitterSettings->texturePath = path;
            }
        }
        xy::Nim::sameLine(); xy::Nim::showToolTip("For a relative path to a texture set the working directory, above");

        xy::Nim::separator();

        if (xy::Nim::button("Start"))
        {
            entity.getComponent<xy::ParticleEmitter>().start();
        }
        xy::Nim::sameLine();
        if (xy::Nim::button("Stop"))
        {
            entity.getComponent<xy::ParticleEmitter>().stop();
        }
        xy::Nim::sameLine();
        if (xy::Nim::button("Reset"))
        {
            entity.getComponent<xy::ParticleEmitter>().settings = xy::EmitterSettings();
            entity.getComponent<xy::Callback>().active = false;
            entity.getComponent<xy::Transform>().setPosition(xy::DefaultSceneSize / 2.f);
            entity.getComponent<xy::Transform>().setRotation(0.f);
        }
        xy::Nim::sameLine(); xy::Nim::showToolTip("Reset the properties to their default values");

        xy::Nim::separator();

        //load button
        //save button
        if (load)
        {
            auto path = xy::FileSystem::openFileDialogue("xyp");
            if (!path.empty())
            {
                entity.getComponent<xy::ParticleEmitter>().settings = xy::EmitterSettings();
                m_textures.setFallbackColour(sf::Color::White);
                m_emitterSettings->loadFromFile(path, m_textures);
                {
                    if (m_workingDirectory.empty())
                    {
                        xy::Logger::log("Working directory not set, textures may not be loaded");
                    }
                    else if(!m_emitterSettings->texturePath.empty())
                    {
                        xy::Logger::log("Trying to correct for texture path...");
                        auto texPath = m_workingDirectory;
                        std::replace(texPath.begin(), texPath.end(), '\\', '/');
                        if (texPath.back() != '/')
                        {
                            texPath += "/";
                        }
                        texPath += m_emitterSettings->texturePath;
                        m_emitterSettings->texture = &m_textures.get(texPath);
                    }
                }
                entity.getComponent<xy::ParticleEmitter>().stop();
            }
        }

        if (save)
        {
            auto path = xy::FileSystem::saveFileDialogue("xyp");
            if (!path.empty())
            {
                if (xy::FileSystem::getFileExtension(path) != ".xyp")
                {
                    path += ".xyp";
                }
                m_emitterSettings->saveToFile(path);
            }
        }

        xy::Nim::end();
    };
    registerWindow(windowFunc);
}
Example #25
0
int
main(int argc, char *argv[])
{
	int opt, i;
	const struct cmdtab *match, *cc, *tab;

#ifndef RESCUE
	snmp_client_init(&snmp_client);
	snmp_client.trans = SNMP_TRANS_LOC_STREAM;
	snmp_client_set_host(&snmp_client, PATH_ILMI_SOCK);
#endif

#ifdef RESCUE
#define OPTSTR	"htv"
#else
#define	OPTSTR	"htvs:"
#endif

	while ((opt = getopt(argc, argv, OPTSTR)) != -1)
		switch (opt) {

		  case 'h':
			help_func(0, argv);

#ifndef RESCUE
		  case 's':
			parse_server(optarg);
			break;
#endif

		  case 'v':
			verbose++;
			break;

		  case 't':
			notitle = 1;
			break;
		}

	if (argv[optind] == NULL)
		help_func(0, argv);

	argc -= optind;
	argv += optind;

	if ((main_tab = malloc(sizeof(static_main_tab))) == NULL)
		err(1, NULL);
	memcpy(main_tab, static_main_tab, sizeof(static_main_tab));

#ifndef RESCUE
	/* XXX while this is compiled in */
	device_register();
#endif

	cc = main_tab;
	i = 0;
	for (;;) {
		/*
		 * Scan the table for a match
		 */
		tab = cc;
		match = NULL;
		while (cc->string != NULL) {
			if (substr(argv[i], cc->string)) {
				if (match != NULL) {
					printf("Ambiguous option '%s'",
					    argv[i]);
					cc = tab;
					goto subopts;
				}
				match = cc;
			}
			cc++;
		}
		if ((cc = match) == NULL) {
			printf("Unknown option '%s'", argv[i]);
			cc = tab;
			goto subopts;
		}

		/*
		 * Have a match. If there is no subtable, there must
		 * be either a handler or the command is only a help entry.
		 */
		if (cc->sub == NULL) {
			if (cc->func != NULL)
				break;
			printf("Unknown option '%s'", argv[i]);
			cc = tab;
			goto subopts;
		}

		/*
		 * Look at the next argument. If it doesn't exist or it
		 * looks like a switch, terminate the scan here.
		 */
		if (argv[i + 1] == NULL || argv[i + 1][0] == '-') {
			if (cc->func != NULL)
				break;
			printf("Need sub-option for '%s'", argv[i]);
			cc = cc->sub;
			goto subopts;
		}

		cc = cc->sub;
		i++;
	}

	argc -= i + 1;
	argv += i + 1;

	(*cc->func)(argc, argv);

	return (0);

  subopts:
	printf(". Select one of:\n");
	while (cc->string != NULL) {
		if (cc->func != NULL || cc->sub != NULL)
			printf("%s ", cc->string);
		cc++;
	}
	printf("\n");

	return (1);
}
Example #26
0
int main()
{
    char buff[BUFFER_SIZE];
    struct node *list = NULL;
    char **str;
    unsigned long long k[MAX_QUERY];
    unsigned long long len;
    int n, q, x;

    fgets(buff, BUFFER_SIZE, stdin);
    n = atoi(buff);
    if (n < 1 || n > MAX_STRING) {
        fprintf(stderr, "Number of strings should be > 0 and < MAX_STRING\n");
        return (1);
    }

    str = (char **) malloc(n * sizeof (char *));
    if (str == NULL) {
        fprintf(stderr, "No memory allocated for str\n");
        return (1);
    }
    for (x = 0; x < n; x++) {
        str[x] = (char *) malloc(BUFFER_SIZE * sizeof (str[x]));
        if (str[x] == NULL) {
            fprintf(stderr, "No memory allocated for str[x]\n");
            return (1);
        }
        fgets(buff, BUFFER_SIZE - 1, stdin);
        len = strlen(buff);
        if (buff[len - 1] == '\n')
            buff[len - 1] = '\0';
        strcpy(str[x], buff);
    }

    fgets(buff, BUFFER_SIZE, stdin);
    q = atoi(buff);
    if (q < 1 || q > MAX_QUERY) {
        fprintf(stderr, "Number of queries should be > 0 and < MAX_QUERY\n");
        return (1);
    }

    for (x = 0; x < q; x++) {
        fgets(buff, BUFFER_SIZE, stdin);
        k[x] = atoi(buff);

        if (k[x] < 1 || k[x] > 1000000000)
            fprintf(stderr, "Query should be > 0 and < 1000000000\n");
    }

    list = substr(str, n);

    for (x = 0; x < q; x++) {
        len = 0;
        search(list, &len, k[x]);

        if (len < k[x])
            printf("INVALID\n");
    }

    clear(list);

    for (x = 0; x < n; x++)
        free(str[x]);

    free(str);

    return (0);
}
Example #27
0
	//-----------------------------------------------------------------//
	inline std::string get_file_base(const std::string& src) {
		auto tmp = get_file_name(src);
		return tmp.substr(0, tmp.find_last_of('.'));
	}
Example #28
0
main()
{
int state 1000, i, book, volume, corp, report;
int na;
char *v[20], **vv, **rr;
char ubuff[1000], *up;
char line[100];
char *p, *s, *r, *q;
while (gets(line))
	{
	if (line[1]>'9' || line[1]<'0') continue;
	switch(line[0])
		{
		case 'T':
			if (state > 'T')
				{
				book=0;
				report=0;
				printf("\n%%T ");
				}
			printf("%s\n", line+18);
			state='T';
			na = getargs(line+18, v);
			for(i=0;i<na;i++)
				if (strcmp(v[i], "(Book)")==0)
					book=1;
			continue;
		case 'A':
			state = 'A';
			na=getargs(line+18, vv=v);
			if (na<=0) continue;
			while (na>0)
				{
				printf("%%A ");
				corp=0;
				for(p=vv[1]; *p; p++)
					if (islower(*p))
						corp=1;
				if (corp==0)
					{
					for(p=vv[1]; *p; p++)
						printf("%c. ", *p);
					if (na>2 &&strcmp(vv[2], "+"))
						{
						printf("%s", vv[0]);
						if (strcmp(vv[2], "Jr.")==0)
							printf(",");
						printf(" %s\n",vv[2]);
						vv++;na--;
						}
					else
						printf("%s\n", vv[0]);
					}
				else
					printf("%s %s\n",vv[0],vv[1]);
				vv+=2;
				na-=2;
				if (strcmp(vv[0], "+")==0)
					{
					vv++;na--;
					}
				}
			continue;
		case 'U':
			if (state!='U')
				ubuff[0]=0;
			else
				strcat(ubuff, " ");
			state = 'U';
			strcat(ubuff, line+18);
			if (line[2]=='.')
				{ /* end of item */
				p=ubuff; /*start*/
				volume=0;
				for(s=ubuff; *s; s++)
					if (s[-1]==' ' && prefix("Vol", s))
						{
						for(q=s-1; q>ubuff; q--)
							{
							if (*q==' ' || *q==',') *q=0;
							else break;
							}
						volume=1;
						break;
						}
				if (*s==0)
				for(s=ubuff; *s && (*s!=',' || sprefix("Inc", s+1)); s++)
					;
				else
				s++;
				if (*s==',')*s++=0;
				if (book)
					printf("%%I %s\n",ubuff);
				else if (volume)
					printf("%%J %s\n", ubuff);
				else if (substr(ubuff, "Report")!=0)
					{
					report=1;
					printf("%%R %s\n", ubuff);
					}
				else
					printf("%%J %s\n", ubuff);
				if (volume)
					{
					s += 3; /* Vol */
					if (*s=='.') s++;
					while (*s==' ')s++;
					printf("%%V ");
					while (*s && *s != ' ' && *s!=',' && *s!=';' && *s!= ':')
						putchar(*s++);
					putchar('\n');
					if (*s==':')
						{
						printf("%%N ");
						while (*s==' ')s++;
						while (isdigit(*s))
							putchar(*s++);
						putchar('\n');
						}
					*s++=0;
					while (*s==' ')*s++=0;
					if (s[0]=='N' && s[1]=='o' && (s[2]==' '||s[2]=='.'))
						{
						s+=2;
						while (*s==' '||*s=='.')s++;
						printf("%%N ");
						while (isdigit(*s)||*s=='-')
							putchar(*s++);
						putchar('\n');
						}
					if (*s==',') *s++=0;
					}
				for(rr=months; *rr; rr++)
					{
					q= substr(s, *rr);
					if (q)
						{
						for(r=q; *r; r++);
						r--;
						if (*r=='.')*r=0;
						printf("%%D %s\n",q);
						*(q-1)=0;
						break;
						}
					}
				if (*rr==0)
					{
					for(q=s; *q; q++)
						{
						if (q[0]=='1' && q[1]=='9' && (q[4]==0 || (q[4]=='.' && q[5]==0)))
							{
							if (q[4]=='.') q[4]=0;
							printf("%%D %s\n",q);
							rr=months;
							q[-1]=0;
							if (q==s) q[0]=0;
							break;
							}
						}
					}
				if (*rr==0) /* no date */
					printf("%%D 19xx\n");
				/* if book bite off next field for city, if report for issuer */
				if (book)
					{
					for(q=s; *q && *q != ','; q++)
						;
					if (*q==',')
						{
						r=q;
						r++;
						while (*r==' ')r++;
						if (isupper(r[0]) && isupper(r[1]))
							{
							r+=2;
							*r++=0;
							while (*r==' ')r++;
							}
						else
							*q=0;
						printf("%%C %s\n", s);
						s=r;
						}
					}
				for(q=s; *q; q++)
					{
					if (q[0]==' ' && q[1]=='p' && (q[2]=='p'||q[2]==0))
						{
						for(r=q; r>s; r--)
							{
							if (*r==' ' || *r==',')
								*r=0;
							}
						*q=0;
						q+=2;
						if (q[0]=='p')q++;
						while (*q==' '||*q=='.')q++;
						r=q;
						while (isdigit(*q)||*q=='.'||*q=='-'||isalpha(*q))q++;
						*q++=0;
						while (*q==' ')q++;
						printf("%%P %s\n",r);
						break;
						}
					}
				s=ispp(s);
				while (*s==' ')s++;
				while (*q==' ')q++;
				if (*s||*q)
					printf("%%O %s %s\n", *s?s:"", *q?q:"");
				}
			continue;
		}
	}
}
Example #29
0
std::string NString::trim_start()
{
  int i = 0;
  while (i < (int)size() && isspace(at(i))) i++;
  return substr(i);
}
Example #30
0
	int substr(FastString<SrcMaxSize>& destStr, size_t index, size_t size = 0xffffffffU) const
	{
		return substr(&destStr, index, size);
	}