Пример #1
0
soulB::checks_returns soulCH::prob_match(char *acl) {
	
	/* Check probablity of bad URL */

	// REDO ERRORS

	const char *file_path; pack *package; float score=12.0; 
	float total_value=0; float score_add=0; int field_len=0; 
	fstream *probab_file = new fstream; char line_buffer[_1K];
	
	if((db_io->get_config(file_path,prob_file,0,acl,NULL)) != TRUE) return CHECKS_ERROR; 
	if(open_file(file_path,probab_file)) return CHECKS_ERROR;
	
	while(read_line(probab_file,line_buffer)) {
	
		char *temp_string = line_buffer; char *temp_token = line_buffer; int second_token=0;
		if(!(field_len=search_string(temp_string,'='))) { db_io->log(ERR,"The field %s was invalid.",package->data); return CONTINUE; }
		
		int third_token = (field_len-1); temp_token+=field_len;
		
		if(!isdigit(*temp_token)) { db_io->log(ERR,"The field %s had no contents or invalid contents",package->data); return CONTINUE; }
		score_add = atof(temp_token); 
		
		if(!strncmp(temp_string,"SCORE",5)) {
			if (!score_add || score_add <0) { db_io->log(ERR,"The score check in file %s was invalid, continuing but keeping default score of %d",file_path,(double)score);
				} else { score = score_add; }
		}
		
		second_token=search_string(temp_string,'_'); 
		if(!strncmp(temp_string,"WORD",4)) { 
	 	
	 		char word_store[_1K]={0}; 
			if(!second_token) { db_io->log(ERR,"The field %s was invalid.",package->data); return CONTINUE; }
			if((third_token-second_token)>=_1K) return CHECKS_ERROR;
			
			temp_string+=second_token; strncpy(word_store,temp_string,third_token-second_token);
			int how_many = find_in_line(word_store,input->url);
			total_value+=(score_add*how_many);
		}
		
		if(!strncmp(temp_string,"LETTER",6)) {
			
			char letter_store='\0';
			if(!second_token) { db_io->log(ERR,"The field %s was invalid.",package->data); return CONTINUE; }
				
			if(((third_token-second_token))!=1) { db_io->log(ERR,"Need a letter between LETTER_ and = in line %s. Skipping.",package->data); break; }
			letter_store = temp_string[second_token]; 
		
			int how_many = find_char_in_line(letter_store,input->url);
			total_value+=(score_add*how_many);
		}
	}
	
	if(DEBUG_STATE) db_io->log(DEBUG,"Prob check returned value of %d",total_value);
	
	close_file(probab_file);

	if(total_value >= score) return RETURN_DENIED;
	return CONTINUE;
}
Пример #2
0
GList* get_kanji_by_key(const gchar *srchkey, GList *list, GjitenDicfile *dicfile)  {
  gint srch_resp = 0, roff = 0, rlen = 0;
  gchar repstr[1024];
  guint32 respos, oldrespos; 
  gint loopnum = 0;
  gint srchpos = 0;

  srch_resp = search_string(SRCH_START, dicfile, srchkey, &respos, &roff, &rlen, repstr);

  if (srch_resp != SRCH_OK) return NULL;
  oldrespos = srchpos = respos;
  
  char *repstr2 = strdup(repstr);
  kanjifile_entry* entry = do_kdicline(repstr2);
  list = g_list_prepend(list, entry->kanji);
  
  while (roff != 0) {
    oldrespos = respos;
    srchpos++;
    loopnum++;
    srch_resp = search_string(SRCH_CONT, dicfile, srchkey, &respos, &roff, &rlen, repstr);

    if (srch_resp != SRCH_OK) break;
    if (oldrespos == respos) continue;

    char *repstr2 = strdup(repstr);
    kanjifile_entry* entry = do_kdicline(repstr2);
    list = g_list_prepend(list, entry->kanji);
  }

  return list;
}
Пример #3
0
static const char *
help_follow_link (const char *start, const char *lc_selected_item)
{
    const char *p;

    if (lc_selected_item == NULL)
        return start;

    for (p = lc_selected_item; *p && *p != CHAR_NODE_END && *p != CHAR_LINK_POINTER; p++)
        ;
    if (*p == CHAR_LINK_POINTER)
    {
        int i;
        char link_name[MAXLINKNAME];

        link_name[0] = '[';
        for (i = 1; *p != CHAR_LINK_END && *p && *p != CHAR_NODE_END && i < MAXLINKNAME - 3;)
            link_name[i++] = *++p;
        link_name[i - 1] = ']';
        link_name[i] = '\0';
        p = search_string (fdata, link_name);
        if (p != NULL)
        {
            p += 1;             /* Skip the newline following the start of the node */
            return p;
        }
    }

    /* Create a replacement page with the error message */
    return _("Help file format error\n");
}
Пример #4
0
extern void make_rotation_groups(t_rot *rot, char **rotgnames, t_blocka *grps, char **gnames)
{
    int       g, ig = -1, i;
    t_rotgrp *rotg;


    for (g = 0; g < rot->ngrp; g++)
    {
        rotg      = &rot->grp[g];
        ig        = search_string(rotgnames[g], grps->nr, gnames);
        rotg->nat = grps->index[ig+1] - grps->index[ig];

        if (rotg->nat > 0)
        {
            fprintf(stderr, "Rotation group %d '%s' has %d atoms\n", g, rotgnames[g], rotg->nat);
            snew(rotg->ind, rotg->nat);
            for (i = 0; i < rotg->nat; i++)
            {
                rotg->ind[i] = grps->a[grps->index[ig]+i];
            }
        }
        else
        {
            gmx_fatal(FARGS, "Rotation group %d '%s' is empty", g, rotgnames[g]);
        }
    }
}
Пример #5
0
int		main(int argc, char **argv)
{
	char	str[1000];
	int		i;
	int		j;
	int		k;

	i = 1;
	while (i < argc)
	{
		j = 0;
		k = 0;
		while (argv[i][j])
		{
			if (argv[i][j] != ' ')
			{
				str[k] = argv[i][j];
				k++;
			}
			j++;
		}
		str[j] = '\0';
		ft_strlowcase(str);
		search_string(str);
		i++;
	}
	return (0);
}
Пример #6
0
void check_input(char buf[],int n, int *id,char *retbuf){
	int i,di,st,en;
	i=search_string(buf,"\"id\"",n,4);
	if(i>=0){
		di=search_char(&(buf[i]),':',n-i);
		if(di>=0){
			i+=di+1;
			sscanf(&(buf[i]),"%d",id);
		}
	}
	i=search_string(buf,"\"params\"",n,8);
	if(i>=0){
		di=search_char(&(buf[i]),':',n-i);
		if(di==-1) {
			retbuf[0]=0;
			return;
		}
		i+=di+1;
		di=search_char(&(buf[i]),'[',n-i);
		if(di==-1) {
			retbuf[0]=0;
			return;
		}
		i+=di+1;
		di=search_char(&(buf[i]),'"',n-i);
		if(di==-1) {
			retbuf[0]=0;
			return;
		}
		i+=di+1;
		st=i;
		di=search_char(&(buf[i]),'"',n-i);
		if(di==-1) {
			retbuf[0]=0;
			return;
		}
		i+=di;
		en=i;
		for(i=0;i<en-st;i++){
			retbuf[i]=buf[st+i];
		}
		retbuf[i]=0;
	}
}
Пример #7
0
void load_config(struct config_t *config)
{
	FILE *fp;
	unsigned int port;
	char buf[1024];

	fp = open_file(CONFIG_FILE, "r");
	fgets(buf, 1024, fp);
	if (search_string(buf, "port") >= 0)
		sscanf(buf + strlen("port: "), "%u", &port);
	config->port = port;
	fclose(fp);
}
Пример #8
0
static void
help_help (WDialog * h)
{
    const char *p;

    history_ptr = (history_ptr + 1) % HISTORY_SIZE;
    history[history_ptr].page = currentpoint;
    history[history_ptr].link = selected_item;

    p = search_string (fdata, "[How to use help]");
    if (p != NULL)
    {
        currentpoint = p + 1;   /* Skip the newline following the start of the node */
        selected_item = NULL;
        send_message (h, NULL, MSG_DRAW, 0, NULL);
    }
}
Пример #9
0
int main(void) {
    char word[11];
    int i, n, m;
    root = create_empty_trie();
    scanf("%d", &n);
    for(i = 0; i < n; i++) {
        scanf("%s", word);
        add_string(root, word);
    }
    scanf("%d", &m);
    for(i = 0; i < m; i++) {
        scanf("%s", word);
        printf("%d\n", search_string(root, word));
    }
    free_trie(root);
    return 0;
}
Пример #10
0
BOOL WorkClass::ProcessVcprojFile( CString& strFileContent )
{
	std::wstring search_string(strFileContent);
	std::tr1::wregex reg(TEXT("Version=(\"\\d\\.\\d{2}\")"));
	std::tr1::wsmatch results;

	if (std::tr1::regex_search(search_string,results,reg))
	{
		std::wstring replace = TEXT("Version=\"9.00\"");
		search_string = std::tr1::regex_replace(search_string,reg,replace);

	}else
	{	
		return SetLastError(ERR_INVALIDFORMAT),FALSE;
	}
	strFileContent.Format(TEXT("%s"),search_string.c_str());
	return  SetLastError(ERR_NONE),TRUE;
}
Пример #11
0
/*******************************************************************************
函数名称:				WorkClass::ProcessSlnFile	处理sln文件
================================================================================
参数说明:				CString & strFileContent	sln文件内容
--------------------------------------------------------------------------------
返回值:					BOOL
--------------------------------------------------------------------------------
文件作者:				King.Sollyu					QQ:191067617
*******************************************************************************/
BOOL WorkClass::ProcessSlnFile( CString& strFileContent )
{
	std::wstring search_string(strFileContent);
	std::tr1::wregex reg(TEXT("Version \\d+\\.\\d{2}"));
	std::tr1::wsmatch results;

	try
	{
		// 寻找当前版本信息 一般为:Version X.00
		// 没有找到则说明格式错误
		if (std::tr1::regex_search(search_string,results,reg))
		{
			// 将找到的格式替换为 10.00
			std::wstring replace = TEXT("Version 10.00");
			search_string = std::tr1::regex_replace(search_string,reg,replace); 

			// 查找版本格式后是否跟随 # Visual Studio 2008 
			// 不跟随就添加
			std::tr1::wregex reg2 (TEXT("Version 10.00\r\n# Visual Studio \\d{4}"));
			if (!std::tr1::regex_search(search_string,results,reg2))
			{
				replace = TEXT("Version 10.00\r\n# Visual Studio 2008");
				search_string = std::tr1::regex_replace(search_string,reg,replace);
			}else
			{
				std::tr1::wregex reg3 (TEXT("# Visual Studio \\d{4}"));
				if (std::tr1::regex_search(search_string,results,reg3) != NULL)
				{
					replace = TEXT("# Visual Studio 2008");
					search_string = std::tr1::regex_replace(search_string,reg3,replace);
				}
			}

		}else
		{	
			return SetLastError(ERR_INVALIDFORMAT),FALSE;
		}
	}
	catch (...){ return SetLastError(ERR_UNKNOW),FALSE; }

	strFileContent.Format(TEXT("%s"),search_string.c_str());
	return  SetLastError(ERR_NONE),TRUE;

}
Пример #12
0
int replace_string(char* data)
{
    int pos, i=0, j=0, start[100], end[100],n_o_occur=0, maxchars=size;
    char string[500], *replace_with, ch='a';
	replace_with=malloc(500*sizeof(char)); 
     move(32, 0);deleteln();
     printw("Enter String to replace: ");          // take the string to replace
     while(ch!='\n')
     {
	ch=getch();
	addch(ch);
	if(ch!='\n'){string[i]=ch;i++;}
	if(ch==27 )//escape key)
	{
		move(33,0); deleteln();	
		return 0;
	}
     }
     string[i]='\0';
	ch='a';
     move(33, 0);
     i=0;printw("Enter replacement string: ");           // take the string to replace with
     while(ch!='\n')
     {
	ch=getch();
	addch(ch);
	if(ch!='\n')
	{replace_with[i]=ch;i++;}
	if(ch==27 )//escape key)
	{
		move(33,0); deleteln();	
		return 0;
	}
     }
	deleteln();
     replace_with[i]='\0';
    while((pos=search_string(string, data))!=-1)  // now search the string to be replaced and get its position
    {		
	    delete_string(pos, strlen(string), data);	 // delete the searched string dfrom its position
            insert_string(pos, replace_with, data);	 // insert the replacement string at that position
    }
	free(replace_with);
    return 0;
}
Пример #13
0
static void
help_index (WDialog * h)
{
    const char *new_item;

    new_item = search_string (fdata, "[Contents]");

    if (new_item == NULL)
        message (D_ERROR, MSG_ERROR, _("Cannot find node %s in help file"), "[Contents]");
    else
    {
        history_ptr = (history_ptr + 1) % HISTORY_SIZE;
        history[history_ptr].page = currentpoint;
        history[history_ptr].link = selected_item;

        currentpoint = new_item + 1;    /* Skip the newline following the start of the node */
        selected_item = NULL;
        send_message (h, NULL, MSG_DRAW, 0, NULL);
    }
}
Пример #14
0
/*************************************************************************
 * <Function-name="main"                                                 *
 *                                                                       *
 *  Description:Searches for a Particualr String and prints the function *
 *              in which the string is found and the Function path       *
 *                                                                       *
 *  Parameters:argc and argv                                             *
 *                                                                       *
 *  Returns:nothing                                                      *
 *                                                                       *
 *  Added By:SANDEEP                                                   *
 *                                                                       *
 *                                                                       *
 ************************************************************************/
int main(int argc,char **argv)
{
int i;
for(i=0;i<argc-4;i++)
{
fun_names(argc,argv,i);
search_string(argc,argv,i);
path(argc,argv,i);

if(occur>0)
{
printf("\n\n*************Total number of occurences are %d***************",occur);
}
else
printf("\n No Match Found");
s=0;
occur=0;
}
print_path(argc,argv);
return 0;
}
Пример #15
0
void pal::readdir(const string_t& path, const string_t& pattern, std::vector<pal::string_t>* list)
{
    assert(list != nullptr);

    std::vector<string_t>& files = *list;

    string_t search_string(path);
    append_path(&search_string, pattern.c_str());

    WIN32_FIND_DATAW data = { 0 };
    auto handle = ::FindFirstFileExW(search_string.c_str(), FindExInfoStandard, &data, FindExSearchNameMatch, NULL, 0);
    if (handle == INVALID_HANDLE_VALUE)
    {
        return;
    }
    do
    {
        string_t filepath(data.cFileName);
        files.push_back(filepath);
    } while (::FindNextFileW(handle, &data));
    ::FindClose(handle);
}
Пример #16
0
int 
main(int argc, char **argv) {
   
    u_int8_t *buffer;
    u_int16_t bufflen;
    u_int8_t *new_buf;    
    search_str *pattern;

    buffer = strdup("ANANANANANAPANAMNANAMPANAMANPANAMANPANANPANMANPANMANAPMANPAMNPAMNAPAMAN");
 
    pattern = make_search_str("ANPANMAN", sizeof("ANPANMAN")-1 );   

    bufflen = strlen(buffer);

    if((new_buf = search_string(buffer, &bufflen, pattern))) {
	fprintf(stdout, "Substring Found!\n");	
	#ifdef PRINTDEBUG

	    printf("[");
	    new_buf -= pattern->ptrn_len;
	    u_int16_t len_ctr = 0;
	    while(len_ctr < pattern->ptrn_len) {
		printf("%c", *new_buf);
		new_buf++;
		len_ctr++;
	    }
	    printf("]\n");
	#endif
    } else {
	fprintf(stdout, "Substring not found!\n");
    }
    
    free(buffer);
    destroy_search_str(pattern);
 
    return(0);

}
Пример #17
0
 //static
 BOOL LLPanelMainInventory::incrementalFind(LLFolderViewItem* first_item, const char *find_text, BOOL backward)
 {
 	LLPanelMainInventory* active_view = NULL;
	
	LLFloaterReg::const_instance_list_t& inst_list = LLFloaterReg::getFloaterList("inventory");
	for (LLFloaterReg::const_instance_list_t::const_iterator iter = inst_list.begin(); iter != inst_list.end(); ++iter)
	{
		LLPanelMainInventory* iv = dynamic_cast<LLPanelMainInventory*>(*iter);
		if (iv)
		{
			if (gFocusMgr.childHasKeyboardFocus(iv))
			{
				active_view = iv;
				break;
			}
 		}
 	}

 	if (!active_view)
 	{
 		return FALSE;
 	}

 	std::string search_string(find_text);

 	if (search_string.empty())
 	{
 		return FALSE;
 	}

 	if (active_view->getPanel() &&
 		active_view->getPanel()->getRootFolder()->search(first_item, search_string, backward))
 	{
 		return TRUE;
 	}

 	return FALSE;
 }
Пример #18
0
static void readdir(const pal::string_t& path, const pal::string_t& pattern, bool onlydirectories, std::vector<pal::string_t>* list)
{
    assert(list != nullptr);

    std::vector<pal::string_t>& files = *list;
    pal::string_t normalized_path(path);

    if (LongFile::ShouldNormalize(normalized_path))
    {
        if (!pal::realpath(&normalized_path))
        {
            return;
        }
    }

    pal::string_t search_string(normalized_path);
    append_path(&search_string, pattern.c_str());

    WIN32_FIND_DATAW data = { 0 };

    auto handle = ::FindFirstFileExW(search_string.c_str(), FindExInfoStandard, &data, FindExSearchNameMatch, NULL, 0);
    if (handle == INVALID_HANDLE_VALUE)
    {
        return;
    }
    do
    {
        if (!onlydirectories || (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
        {
            pal::string_t filepath(data.cFileName);
            if (filepath != _X(".") && filepath != _X(".."))
            {
                files.push_back(filepath);
            }
        }
    } while (::FindNextFileW(handle, &data));
    ::FindClose(handle);
}
Пример #19
0
static int
alias_rtsp_out(struct libalias *la, struct ip *pip,
               struct alias_link *lnk,
               char *data,
               const char *port_str)
{
    int hlen, tlen, dlen;
    struct tcphdr *tc;
    int i, j, pos, state, port_dlen, new_dlen, delta;
    u_short p[2], new_len;
    u_short sport, eport, base_port;
    u_short salias = 0, ealias = 0, base_alias = 0;
    const char *transport_str = "transport:";
    char newdata[2048], *port_data, *port_newdata, stemp[80];
    int links_created = 0, pkt_updated = 0;
    struct alias_link *rtsp_lnk = NULL;
    struct in_addr null_addr;

    /* Calculate data length of TCP packet */
    tc = (struct tcphdr *)ip_next(pip);
    hlen = (pip->ip_hl + tc->th_off) << 2;
    tlen = ntohs(pip->ip_len);
    dlen = tlen - hlen;

    /* Find keyword, "Transport: " */
    pos = search_string(data, dlen, transport_str);
    if (pos < 0) {
        return (-1);
    }
    port_data = data + pos;
    port_dlen = dlen - pos;

    memcpy(newdata, data, pos);
    port_newdata = newdata + pos;

    while (port_dlen > (int)strlen(port_str)) {
        /* Find keyword, appropriate port string */
        pos = search_string(port_data, port_dlen, port_str);
        if (pos < 0) {
            break;
        }
        memcpy(port_newdata, port_data, pos + 1);
        port_newdata += (pos + 1);

        p[0] = p[1] = 0;
        sport = eport = 0;
        state = 0;
        for (i = pos; i < port_dlen; i++) {
            switch (state) {
            case 0:
                if (port_data[i] == '=') {
                    state++;
                }
                break;
            case 1:
                if (ISDIGIT(port_data[i])) {
                    p[0] = p[0] * 10 + port_data[i] - '0';
                } else {
                    if (port_data[i] == ';') {
                        state = 3;
                    }
                    if (port_data[i] == '-') {
                        state++;
                    }
                }
                break;
            case 2:
                if (ISDIGIT(port_data[i])) {
                    p[1] = p[1] * 10 + port_data[i] - '0';
                } else {
                    state++;
                }
                break;
            case 3:
                base_port = p[0];
                sport = htons(p[0]);
                eport = htons(p[1]);

                if (!links_created) {

                    links_created = 1;
                    /*
                     * Find an even numbered port
                     * number base that satisfies the
                     * contiguous number of ports we
                     * need
                     */
                    null_addr.s_addr = 0;
                    if (0 == (salias = FindNewPortGroup(la, null_addr,
                                                        FindAliasAddress(la, pip->ip_src),
                                                        sport, 0,
                                                        RTSP_PORT_GROUP,
                                                        IPPROTO_UDP, 1))) {
#ifdef LIBALIAS_DEBUG
                        fprintf(stderr,
                                "PacketAlias/RTSP: Cannot find contiguous RTSP data ports\n");
#endif
                    } else {

                        base_alias = ntohs(salias);
                        for (j = 0; j < RTSP_PORT_GROUP; j++) {
                            /*
                             * Establish link
                             * to port found in
                             * RTSP packet
                             */
                            rtsp_lnk = FindRtspOut(la, GetOriginalAddress(lnk), null_addr,
                                                   htons(base_port + j), htons(base_alias + j),
                                                   IPPROTO_UDP);
                            if (rtsp_lnk != NULL) {
#ifndef NO_FW_PUNCH
                                /*
                                 * Punch
                                 * hole in
                                 * firewall
                                 */
                                PunchFWHole(rtsp_lnk);
#endif
                            } else {
#ifdef LIBALIAS_DEBUG
                                fprintf(stderr,
                                        "PacketAlias/RTSP: Cannot allocate RTSP data ports\n");
#endif
                                break;
                            }
                        }
                    }
                    ealias = htons(base_alias + (RTSP_PORT_GROUP - 1));
                }
                if (salias && rtsp_lnk) {

                    pkt_updated = 1;

                    /* Copy into IP packet */
                    sprintf(stemp, "%d", ntohs(salias));
                    memcpy(port_newdata, stemp, strlen(stemp));
                    port_newdata += strlen(stemp);

                    if (eport != 0) {
                        *port_newdata = '-';
                        port_newdata++;

                        /* Copy into IP packet */
                        sprintf(stemp, "%d", ntohs(ealias));
                        memcpy(port_newdata, stemp, strlen(stemp));
                        port_newdata += strlen(stemp);
                    }
                    *port_newdata = ';';
                    port_newdata++;
                }
                state++;
                break;
            }
            if (state > 3) {
                break;
            }
        }
        port_data += i;
        port_dlen -= i;
    }

    if (!pkt_updated)
        return (-1);

    memcpy(port_newdata, port_data, port_dlen);
    port_newdata += port_dlen;
    *port_newdata = '\0';

    /* Create new packet */
    new_dlen = port_newdata - newdata;
    memcpy(data, newdata, new_dlen);

    SetAckModified(lnk);
    tc = (struct tcphdr *)ip_next(pip);
    delta = GetDeltaSeqOut(tc->th_seq, lnk);
    AddSeq(lnk, delta + new_dlen - dlen, pip->ip_hl, pip->ip_len,
           tc->th_seq, tc->th_off);

    new_len = htons(hlen + new_dlen);
    DifferentialChecksum(&pip->ip_sum,
                         &new_len,
                         &pip->ip_len,
                         1);
    pip->ip_len = new_len;

    tc->th_sum = 0;
#ifdef _KERNEL
    tc->th_x2 = 1;
#else
    tc->th_sum = TcpChecksum(pip);
#endif
    return (0);
}
Пример #20
0
char *MPlex::get(char *word)
{
	char	buff[BUF_SIZE], *s, *e;
	int	i;

	// See if the word is closed

	strcpy(buff, "^");
	strcat(buff, word);
	strcat(buff, sTAGSEP);

	compact_numbers(buff);

	if (EXISTS(tree, buff))
	{
		e = REC(char *, tree);
#if 0
		printf("word %s, lex entry %s is %s\n", word, buff, e);
#endif
		return e;
	}

	// Try the lower case version

	for (i = 0; buff[i]; ++i) buff[i] = tolower(buff[i]);

	if (EXISTS(tree, buff))
	{
		e = REC(char *, tree);
#if 0
		printf("word %s, lex entry %s is %s\n", word, buff, e);
#endif
		return e;
	}


	// Get the search string corresponding to the word

	if (use_codes)
		search_string(buff, word);
	else
		strcpy(buff, word);
	strcat(buff, sTAGSEP);

	for (s = &buff[0]; strlen(s) > 0; s++)
	{
		if (strlen(s) > ntail + 1) continue;

#if 0
		printf("looking for word '%s', search string is '%s'\n", word, s);
#endif

		if (EXISTS(tree, s))
		{
			e = REC(char *, tree);
#if 0
			printf("word '%s', lex entry %s is %s\n", word, s, e);
#endif
			return e;
		}
	}

#if 0
	printf("word %s, lex entry not found\n", word);
#endif
	return NULL;
}
Пример #21
0
int texteditor(char *text, int maxchars, const int startrow, const int startcol,int maxrows,const int maxcols,const int displayrows,const int returnhandler,const char *permitted, bool ins, const bool allowcr)
{
	int ky,position=0,row,col,scrollstart=0, x=0, y=0;   //ky is most of the time the input user gives, position(it stays in sync with cursor) points to text row and col keep track of row or column being managed, scroll start keeps track of position from where scroll starts, x and y are xy coordinates on screen
	char *where, *original, *savetext,**display, *last_undo;  // where keeps the line of text for a while, original is the text as copied from text file
	bool exitflag=false;                                      // save text is used to keep a backup of our text so we may get previous text bac if something unusuall happens
                                                                  // last undo is useless // display is 2 dimensional array to keep enough text in it to fill the diplay window
	if (!maxchars)                                      // if user has not specified maxchars
		maxchars=maxrows*maxcols+1;

	if (!maxrows || maxrows > maxchars-1)              // if maxrows are not specified or maxchars are less then number of rows possible then make sure max rows are less then maxchars
		maxrows=maxchars-1;

	if (ins)                                         // if ins variable is set  
		curs_set(2);								//then set cursor to high visibility mode
	else											//else keep it normal
		curs_set(1);
     /* below we will allocate memory to our above declared arrays and assign data to them*/
	if ((display = malloc(maxrows * sizeof(char *))) ==NULL) /*assign memory equal to number of maxrows to display*/
		malloc_error();	//call the function to check if memory was successfully allocated
	for(ky = 0; ky < maxrows; ky++)		//now traverse all rows in display and allocated and assign memory equal to maxcols to each row of display
		if ((display[ky] = malloc((maxcols+1) * sizeof(char)))==NULL)
		        malloc_error();

	if ((original=malloc(maxchars*sizeof(char)))==NULL)	//allocated memory to original 
		malloc_error();
	strcpy(original,text);//copy text taken from file to original variable

	if ((savetext=malloc(maxchars*sizeof(char)))==NULL)// allocate memory to savetext 
		malloc_error();
	strcpy(savetext,text);//copy text to savetext
  /*finished assigning**/

	while (!exitflag) // our loop to stay in unless user presses a button to turn exit flag true initially it is set false
	{
		int counter; //counter to count
		do	//start of do while loop
		{
		        counter=0;
		        where=text;	//temporarily copy all text taken from file to where

		        for (row=0; row < maxrows; row++) // initialize display vriable making sure every row has a null in the start
		        {
		                display[row][0]=127; //assign a backspace character to first column of every row
		                display[row][1]='\0'; //assign a null character to second column of every row indicating that the row ends here
		        }

		        row=0;    // set row to zero
		        while ((strlen(where) > maxcols || strchr(where,'\n') != NULL) &&  (display[maxrows-1][0]==127 || display[maxrows-1][0]=='\n')) //while loop
				//keep traversing if both of following conditions are met successfully				
				//1. length of text(where) is more than number of columns which means there are more than one rows
				//   "OR" if a new row exist
				//2. if first column of last row has a backspace OR an end of line character(means we haev not reached last row yet)
		        {
		                strncpy(display[row],where,maxcols); //copy text from where to current row of display from where specifyint he maximum columns it can have
		                display[row][maxcols]='\0';          // insert a null at the end of a row indicating that the row ends here
		                if (strchr(display[row],'\n') != NULL)  // if there s a new line character in this row
		                        left(display[row],strchr(display[row],'\n')-display[row]);//end the row where a new line character is found
		                else									//in case there is no newline character in this row
		                        left(display[row],strrchr(display[row],' ')-display[row]);//mark end of row at next white space charcter
		                if (display[maxrows-1][0]==127 || display[maxrows-1][0]=='\n')//if first column of last row has a backspace OR an end of line character
		                {
		                        where+=strlen(display[row]);       // move where pointer to the address before which text is already dealt with
		                        if (where[0]=='\n' || where[0]==' ' || where[0]=='\0')    //in case where points to and of newline characters
		                                where++;	 //move one step forward
		                        row++;	 //current is dealt with now we move to next row
		                 }
		        }// while loop ends here text is assigned to display datas tructure properly
		        if (row == maxrows-1 && strlen(where) > maxcols) // if we have reached last row and remaining text is more than number of characters last row can have
		        {
		                strcpy(text,savetext);	//copy the savetext to text
		                if (ky==127/*KEY_BACKSPACE*/)	//if ky is KEY_BACKSPACE
		                        position++;	//increase position variable
		                counter=1;			//set counter to be one since there is text remaining to be copied
		        }
		}while (counter);//do while loop ends here
		strcpy(display[row],where);//now copy remaining text from where to display row

		ky=0;				//set ky to be 0
		if (strchr(display[maxrows-1],'\n') != NULL)	//if first character of last row is a newline character
		        if (strchr(display[maxrows-1],'\n')[1] != '\0')	//and second charcter is a newline character
		                ky=127/*KEY_BACKSPACE*/;						//then set ky to be equal to backspace

		col=position;		//set current column to be equal to position of cursor we are at
		row=0;				// set row to pont to fisrt row
		counter=0;			//set counter to be 0
		while (col > strlen(display[row]))	//keep traversing if column is greator than number of columsn in current row
		{
		        col-=strlen(display[row]);	//set column= column - number of columns of current row
		        counter+=strlen(display[row]);		//set counter to point at the end of current row
		        if (text[counter] ==' ' || text[counter]=='\n' || text[counter]=='\0')	//in case text at current cursor position is a newline character
		        {
		                col--;	//decrease col by one
		                counter++;	//point to text charcter in text
		        }
		        row++;	//increase row by one since current row has been properly taken care of
		}
		if (col > maxcols-1)	//in case col is greator than total number of columns a row can hev
		{
		        row++;	//move to next row means increment row variable
		        col=0;	//set col = 0 means point to first colunmn in next row
		}

		if (!ky) // otherwise  ky==KEY_BACKSPACE and we're getting rid of the last character we entered to avoid pushing text into the last line +1
		{
		        if (row < scrollstart)	// in case current row is lower than scroll start
		                scrollstart--;  // then decrease scroll start
		        if (row > scrollstart+displayrows-1) //in case current row is greator than scroll start plus number of displayrows
		                scrollstart++;	//then increase scroll start
		        for (counter=0;counter < displayrows; counter++)	//traverse all the display rows
		        {
		                mvhline(counter+startrow,startcol,' ',maxcols);	//move to position counter+startrow on y coordinate and startcol on x coordinate and print spaces on all columns onwards from counter of this row
		                if (display[counter+scrollstart][0] != 127)		//if current position has a backspace in it then
		                        mvprintw(counter+startrow,startcol,"%s",display[counter+scrollstart]);//move to position counter+startrow on y and startcol on x and display text in display area
		        }
		        move(row+startrow-scrollstart,col+startcol);     // move to end of text

		        ky=getch(); // text has been displayed  now wait for user to press a key
		}

		switch(ky)     // take actions based on pressed key
		{
			case 27: //escape
				exitflag=true;	//set exitflag to be true
				break;			
		        case KEY_F(2):  //f2 key to delete all file contents
				memset(text,'\0',maxchars);	//make all the contens of file to be null
		                position=0;	//set postion to be zero
		                scrollstart=0;	//set scroll start to be zero
		                break;
			case KEY_F(3):   //f3 key to search for strings
				getyx(stdscr,y,x);//get current coordinates of cursor
				remove_search_marks(text);//remove searchmarks from text
				search_string(NULL,text);	//goto search function
				clr_bottom();				//clear the interactive area below menu
				move(y,x);					//move back to textbox
				break;
 			case KEY_F(4):    //f4 to replace strings
				getyx(stdscr,y,x);	//get current coordinates of cursor
				replace_string(text);//call the function to replace string
				clr_bottom();	
				move(y,x);
				break;
			case KEY_F(5):  //f5 key to save file
				getyx(stdscr,y,x);
				save_file(text);	//call the function save file
				clr_bottom();
				move(y,x);
				break;
			case KEY_F(6):   //f6 key to count number of words
				clr_bottom();
				count_words_chars(text); //call the function to count words and chars in text
			case KEY_F(7):   //f7 key to remove search marks
				remove_search_marks(text); //remove search marks
		        case KEY_HOME:	//move to start of current row
		                if (col)	//if current column is not the first column
		                {
		                        position=0;//set position to be zero
		                        for (col=0; col < row; col++)//traverse until col is less then row
		                        {
		                                position += strlen(display[col]);//move cursor to end of current row in display array
		                                if ((strchr(display[row],'\n') != NULL) || (strchr(display[row],' ') != NULL))//if there is a escape character ' ' or '\n' in current row
		                                        position++;		// increment position and move to start of the row
		                        }
		                }
		                break;
		        case KEY_END:	//move to end of current row
		                if (col < strlen(display[row]))	//if col is less than number of columns in current row
		                {
		                        position=-1;	//set potiion to -1
		                        for (col=0; col <=row; col++)	//traverse until col is less than or equal to row (row is position of current row)
		                        {
									position+=strlen(display[col]);//set position to be the end of curent row
									if ((strchr(display[row],'\n') != NULL) || (strchr(display[row],' ') != NULL)) //if we haev reached enf of row
											position++;	//increment position so it may move to end of current row
		                        }
		                }
		                break;
		        case KEY_PPAGE:	//move to start of text
		                position=0;	//set position to be zero 
		                scrollstart=0;	//set scroll start to be zero
		                break;
		        case KEY_NPAGE:	//move to end of text
		                position=strlen(text);	//set postion to be end of text
		                for (counter=0; counter < maxrows; counter++)	//traverse until counter is less than total number of rows
		                        if(display[counter][0]==127)	//if the row at position counter's first character is backspace
		                                break;	//then break from loop
		                scrollstart=counter-displayrows;	//else set scroll start to equal counter-displayrows
		                if (scrollstart < 0)	//in case scroll start has decreased to become negative
		                        scrollstart=0;	//set it to be zero again
		                break;
		        case KEY_LEFT:	//move cursor left
		                if (position)	//if position is not zero
		                        position--;	//decrease by one
		                break;
		        case KEY_RIGHT:	//move cursor right
		                if (position < strlen(text) && (row != maxrows-1 || col < maxcols-1))//if cursor is not already at end or far from end
		                        position++;		//increase position by one
		                break;
		        case KEY_UP:	//move cursor up
		                if (row)	//in case we are not on first row
		                {
		                        if (col > strlen(display[row-1]))//if current column is greater then length of previous row
		                                position=strlen(display[row-1]);	//then set cursor at the end of above row
		                        else
		                                position=col;	//else set position to col
		                        ky=0;	//set ky=0
		                        for (col=0; col < row-1; col++)	//traverse for col less than row above current row
		                        {
		                                position+=strlen(display[col]);	//move cursor to end of column
		                                ky+=strlen(display[col]);	//move ky to next row
		                                if ((strlen(display[col]) < maxcols) || (text[ky]==' ' && strlen(display[col])==maxcols))//if we are not already at end of row
		                                {
		                                        position++;	//increment position
		                                        ky++;	//move to next row
		                                }
		                        }
		                }
		                break;
		        case KEY_DOWN:// move cursor to below row
		                if (row < maxrows-1)	//if it's not last row
		                        if (display[row+1][0] !=127)	//if next row is not empty
		                        {
		                                if (col < strlen(display[row+1]))	//if col is less than length of next row
		                                        position=col;	//set position to be col
		                                else
		                                        position=strlen(display[row+1]);//set position to be end of above row
		                                ky=0;//set ky=0;
		                                for (col=0; col <= row; col++)//traverse until we reach the current row
		                                {
		                                        position+=strlen(display[col]);//move to next row
		                                        ky+=strlen(display[col]);//move to next row
		                                        if ((strlen(display[col]) < maxcols) || (text[ky]==' ' && strlen(display[col])==maxcols))//if we are not already at end of row
		                                        {
		                                                position++;
		                                                ky++;
		                                        }
		                                }

		                        }
		                break;
		        case KEY_IC: // insert key
		                ins=!ins;//invert the insert mode, turn it on if it's on or vice versa
		                if (ins)
		                        curs_set(2);
		                else
		                        curs_set(1);
		                break;
		        case 330://KEY_DC:  // delete key
		                if (strlen(text))//if text exist
		                {
		                        strcpy(savetext,text);//save text 
		                        memmove(&text[position],&text[position+1],maxchars-position);//move text to left by one character meanwhile eating the one character, search google for function memove and read about it...
		                }
		                break;
		        case KEY_BACKSPACE:// remove text				
		                if (strlen(text) && position)//if text exist and cursor is already not at begiing of text
		                {
		                        strcpy(savetext,text);//save text 
		                        position--;//decrease poition by one basically making cursor go back
		                        memmove(&text[position],&text[position+1],maxchars-position);//move text to left by one character meanwhile eating the one character
		                }
		                break;
		        case 25: // ctrl-y delete entire line
				if (display[1][0] != 127)//if there's text on first row
		                {
		                        position-=col;//move cursor to start of first row
		                        ky=0;//set ky=0
		                        do
		                        {
		                                memmove(&text[position],&text[position+1],maxchars-position);//move text right by one
		                                ky++;//increase ky
		                        }
		                        while (ky < strlen(display[row]));//keep doing it until ky is less than number of columns in current row
		                }
		                else
		                        memset(text,'\0',maxchars);//other wise it's already empty
		                break;
		        case 10: // return        // insert a line by pressing return button
				switch (returnhandler)//see what do we want enter to do
		                {
		                        case 1:// in case return handler==1
		                                if (display[maxrows-1][0] == 127 || display[maxrows-1][0] == '\n')// if display area is not empty
		                                 {
		                                        memmove(&text[position+1],&text[position],maxchars-position);//move text to right by one, emptying the space for one charectre at potiions
		                                        text[position]='\n';	//insert a new row character at position in text
		                                        position++;//increase poition
		                                 }
		                                break;
		                        case 2:
		                                ky=' ';//insert a space
		                                ungetch(ky);//
		                                break;
		                        case 3:
		                                exitflag=true;//exit
		                }
		                break;
		        default: //in case of any other characters than specified above
					if (((permitted==NULL && ky > 31 && ky < 127) || (permitted != NULL && strchr(permitted,ky))) && strlen(text) < maxchars-1 && (row !=maxrows-1 || (strlen(display[maxrows-1]) < maxcols || (ins && (row!=maxrows-1 && col < maxcols )))))
					{
						if (ins || text[position+1]=='\n' || text[position]== '\n')    //in ase insert mode is on or there is no text after this in current row
								memmove(&text[position+1],&text[position],maxchars-position);//move text to right by one and add characters
						text[position]=ky;//insert current key in text
						if (row != maxrows-1 || col < maxcols-1)//in case insert mode is off and we're not at the end of row
								position++;//increment position(move cursor to right)
		            }
		        }
				if(!allowcr)//if isnert mode is allowed
		        if (text[0]=='\n') //if first char in text is a newline
		        {
		                memmove(&text[0],&text[1],maxchars-1);//movetext to left by one
		                if (position)//if position is not zero
		                        position--;//decrease position
		         }
		}//switch ends here
/*user decided to exit free all assigned memory    */
	free(original);//free memory of original
	free(savetext);//free memory of savetext
	free(last_undo);//free memory of last undo, it's not used at all so no need for it
	for(scrollstart = 0; scrollstart < maxrows; scrollstart++)//traverse all rows of siplay and free their memory
		free(display[scrollstart]);
	free(display);//free dispay
	/************************/

	
	return 0; 
}
Пример #22
0
void init_membed(FILE *fplog, gmx_membed_t *membed, int nfile, const t_filenm fnm[], gmx_mtop_t *mtop, t_inputrec *inputrec, t_state *state, t_commrec *cr,real *cpt)
{
        char                    *ins;
        int                     i,rm_bonded_at,fr_id,fr_i=0,tmp_id,warn=0;
        int                     ng,j,max_lip_rm,ins_grp_id,ins_nat,mem_nat,ntype,lip_rm,tpr_version;
        real                    prot_area;
        rvec                    *r_ins=NULL;
        t_block                 *ins_at,*rest_at;
        pos_ins_t               *pos_ins;
        mem_t                   *mem_p;
        rm_t                    *rm_p;
        gmx_groups_t            *groups;
        gmx_bool                    bExcl=FALSE;
        t_atoms                 atoms;
        t_pbc                   *pbc;
        char                    **piecename=NULL;
    
        /* input variables */
	const char *membed_input;
        real xy_fac = 0.5;
        real xy_max = 1.0;
        real z_fac = 1.0;
        real z_max = 1.0;
        int it_xy = 1000;
        int it_z = 0;
        real probe_rad = 0.22;
        int low_up_rm = 0;
        int maxwarn=0;
        int pieces=1;
        gmx_bool bALLOW_ASYMMETRY=FALSE;

	snew(ins_at,1);
	snew(pos_ins,1);

	if(MASTER(cr))
	{
                /* get input data out membed file */
		membed_input = opt2fn("-membed",nfile,fnm);
		get_input(membed_input,&xy_fac,&xy_max,&z_fac,&z_max,&it_xy,&it_z,&probe_rad,&low_up_rm,&maxwarn,&pieces,&bALLOW_ASYMMETRY);

		tpr_version = get_tpr_version(ftp2fn(efTPX,nfile,fnm));
		if (tpr_version<58)
			gmx_fatal(FARGS,"Version of *.tpr file to old (%d). Rerun grompp with gromacs VERSION 4.0.3 or newer.\n",tpr_version);

		if( !EI_DYNAMICS(inputrec->eI) )
			gmx_input("Change integrator to a dynamics integrator in mdp file (e.g. md or sd).");

		if(PAR(cr))
			gmx_input("Sorry, parallel g_membed is not yet fully functional.");
     
#ifdef GMX_OPENMM
			gmx_input("Sorry, g_membed does not work with openmm.");
#endif

		if(*cpt>=0)
		{
			fprintf(stderr,"\nSetting -cpt to -1, because embedding cannot be restarted from cpt-files.\n");
 			*cpt=-1;
		}
		groups=&(mtop->groups);

		atoms=gmx_mtop_global_atoms(mtop);
		snew(mem_p,1);
		fprintf(stderr,"\nSelect a group to embed in the membrane:\n");
		get_index(&atoms,opt2fn_null("-mn",nfile,fnm),1,&(ins_at->nr),&(ins_at->index),&ins);
		ins_grp_id = search_string(ins,groups->ngrpname,(groups->grpname));
		fprintf(stderr,"\nSelect a group to embed %s into (e.g. the membrane):\n",ins);
		get_index(&atoms,opt2fn_null("-mn",nfile,fnm),1,&(mem_p->mem_at.nr),&(mem_p->mem_at.index),&(mem_p->name));

		pos_ins->pieces=pieces;
		snew(pos_ins->nidx,pieces);
		snew(pos_ins->subindex,pieces);
		snew(piecename,pieces);	
		if (pieces>1)
		{
			fprintf(stderr,"\nSelect pieces to embed:\n");
			get_index(&atoms,opt2fn_null("-mn",nfile,fnm),pieces,pos_ins->nidx,pos_ins->subindex,piecename);
		}
		else
		{	
			/*use whole embedded group*/
			snew(pos_ins->nidx,1);
			snew(pos_ins->subindex,1);
			pos_ins->nidx[0]=ins_at->nr;
			pos_ins->subindex[0]=ins_at->index;
		}

		if(probe_rad<0.2199999)
		{
			warn++;
			fprintf(stderr,"\nWarning %d:\nA probe radius (-rad) smaller than 0.2 can result in overlap between waters "
					"and the group to embed, which will result in Lincs errors etc.\nIf you are sure, you can increase maxwarn.\n\n",warn);
		}

		if(xy_fac<0.09999999)
		{
			warn++;
			fprintf(stderr,"\nWarning %d:\nThe initial size of %s is probably too smal.\n"
					"If you are sure, you can increase maxwarn.\n\n",warn,ins);
		}

		if(it_xy<1000)
		{
			warn++;
			fprintf(stderr,"\nWarning %d;\nThe number of steps used to grow the xy-coordinates of %s (%d) is probably too small.\n"
					"Increase -nxy or, if you are sure, you can increase maxwarn.\n\n",warn,ins,it_xy);
		}

		if( (it_z<100) && ( z_fac<0.99999999 || z_fac>1.0000001) )
                {
                        warn++;
                        fprintf(stderr,"\nWarning %d;\nThe number of steps used to grow the z-coordinate of %s (%d) is probably too small.\n"
                                       "Increase -nz or, if you are sure, you can increase maxwarn.\n\n",warn,ins,it_z);
                }

		if(it_xy+it_z>inputrec->nsteps)
		{
			warn++;
			fprintf(stderr,"\nWarning %d:\nThe number of growth steps (-nxy + -nz) is larger than the number of steps in the tpr.\n"
					"If you are sure, you can increase maxwarn.\n\n",warn);
		}

		fr_id=-1;
		if( inputrec->opts.ngfrz==1)
			gmx_fatal(FARGS,"You did not specify \"%s\" as a freezegroup.",ins);
		for(i=0;i<inputrec->opts.ngfrz;i++)
		{
			tmp_id = mtop->groups.grps[egcFREEZE].nm_ind[i];
			if(ins_grp_id==tmp_id)
			{
				fr_id=tmp_id;
				fr_i=i;
			}
		}
		if (fr_id == -1 )
			gmx_fatal(FARGS,"\"%s\" not as freezegroup defined in the mdp-file.",ins);

		for(i=0;i<DIM;i++)
			if( inputrec->opts.nFreeze[fr_i][i] != 1)
				gmx_fatal(FARGS,"freeze dimensions for %s are not Y Y Y\n",ins);

		ng = groups->grps[egcENER].nr;
		if (ng == 1)
			gmx_input("No energy groups defined. This is necessary for energy exclusion in the freeze group");

		for(i=0;i<ng;i++)
		{
			for(j=0;j<ng;j++)
			{
				if (inputrec->opts.egp_flags[ng*i+j] == EGP_EXCL)
				{
					bExcl = TRUE;
					if ( (groups->grps[egcENER].nm_ind[i] != ins_grp_id) || (groups->grps[egcENER].nm_ind[j] != ins_grp_id) )
						gmx_fatal(FARGS,"Energy exclusions \"%s\" and  \"%s\" do not match the group to embed \"%s\"",
								*groups->grpname[groups->grps[egcENER].nm_ind[i]],
								*groups->grpname[groups->grps[egcENER].nm_ind[j]],ins);
				}
			}
		}
		if (!bExcl)
			gmx_input("No energy exclusion groups defined. This is necessary for energy exclusion in the freeze group");

		/* Guess the area the protein will occupy in the membrane plane	 Calculate area per lipid*/
		snew(rest_at,1);
		ins_nat = init_ins_at(ins_at,rest_at,state,pos_ins,groups,ins_grp_id,xy_max);
		/* Check moleculetypes in insertion group */
		check_types(ins_at,rest_at,mtop);

		mem_nat = init_mem_at(mem_p,mtop,state->x,state->box,pos_ins);

		prot_area = est_prot_area(pos_ins,state->x,ins_at,mem_p);
		if ( (prot_area>7.5) && ( (state->box[XX][XX]*state->box[YY][YY]-state->box[XX][YY]*state->box[YY][XX])<50) )
		{
			warn++;
			fprintf(stderr,"\nWarning %d:\nThe xy-area is very small compared to the area of the protein.\n"
					"This might cause pressure problems during the growth phase. Just try with\n"
					"current setup (-maxwarn + 1), but if pressure problems occur, lower the\n"
					"compressibility in the mdp-file or use no pressure coupling at all.\n\n",warn);
		}
		if(warn>maxwarn)
					gmx_fatal(FARGS,"Too many warnings.\n");

		printf("The estimated area of the protein in the membrane is %.3f nm^2\n",prot_area);
		printf("\nThere are %d lipids in the membrane part that overlaps the protein.\nThe area per lipid is %.4f nm^2.\n",mem_p->nmol,mem_p->lip_area);

		/* Maximum number of lipids to be removed*/
		max_lip_rm=(int)(2*prot_area/mem_p->lip_area);
		printf("Maximum number of lipids that will be removed is %d.\n",max_lip_rm);

		printf("\nWill resize the protein by a factor of %.3f in the xy plane and %.3f in the z direction.\n"
				"This resizing will be done with respect to the geometrical center of all protein atoms\n"
				"that span the membrane region, i.e. z between %.3f and %.3f\n\n",xy_fac,z_fac,mem_p->zmin,mem_p->zmax);

		/* resize the protein by xy and by z if necessary*/
		snew(r_ins,ins_at->nr);
		init_resize(ins_at,r_ins,pos_ins,mem_p,state->x,bALLOW_ASYMMETRY);
		membed->fac[0]=membed->fac[1]=xy_fac;
		membed->fac[2]=z_fac;

		membed->xy_step =(xy_max-xy_fac)/(double)(it_xy);
		membed->z_step  =(z_max-z_fac)/(double)(it_z-1);

		resize(r_ins,state->x,pos_ins,membed->fac);

		/* remove overlapping lipids and water from the membrane box*/
		/*mark molecules to be removed*/
		snew(pbc,1);
		set_pbc(pbc,inputrec->ePBC,state->box);

		snew(rm_p,1);
		lip_rm = gen_rm_list(rm_p,ins_at,rest_at,pbc,mtop,state->x, r_ins, mem_p,pos_ins,probe_rad,low_up_rm,bALLOW_ASYMMETRY);
	        lip_rm -= low_up_rm;

		if(fplog)
			for(i=0;i<rm_p->nr;i++)
				fprintf(fplog,"rm mol %d\n",rm_p->mol[i]);

		for(i=0;i<mtop->nmolblock;i++)
		{
			ntype=0;
			for(j=0;j<rm_p->nr;j++)
				if(rm_p->block[j]==i)
					ntype++;
			printf("Will remove %d %s molecules\n",ntype,*(mtop->moltype[mtop->molblock[i].type].name));
		}

		if(lip_rm>max_lip_rm)
		{
			warn++;
			fprintf(stderr,"\nWarning %d:\nTrying to remove a larger lipid area than the estimated protein area\n"
					"Try making the -xyinit resize factor smaller.\n\n",warn);
		}

		/*remove all lipids and waters overlapping and update all important structures*/
		rm_group(inputrec,groups,mtop,rm_p,state,ins_at,pos_ins);

		rm_bonded_at = rm_bonded(ins_at,mtop);
		if (rm_bonded_at != ins_at->nr)
		{
			fprintf(stderr,"Warning: The number of atoms for which the bonded interactions are removed is %d, "
					"while %d atoms are embedded. Make sure that the atoms to be embedded are not in the same"
					"molecule type as atoms that are not to be embedded.\n",rm_bonded_at,ins_at->nr);
		}

		if(warn>maxwarn)
			gmx_fatal(FARGS,"Too many warnings.\nIf you are sure these warnings are harmless, you can increase -maxwarn");

		if (ftp2bSet(efTOP,nfile,fnm))
			top_update(opt2fn("-mp",nfile,fnm),ins,rm_p,mtop);

		sfree(pbc);
		sfree(rest_at);
    		if (pieces>1) { 	sfree(piecename); }

                membed->it_xy=it_xy;
                membed->it_z=it_z;
                membed->pos_ins=pos_ins;
                membed->r_ins=r_ins;
	}
}
Пример #23
0
void make_pull_groups(t_pull *pull, char **pgnames, t_blocka *grps, char **gnames)
{
    int        d, nchar, g, ig = -1, i;
    char      *ptr, pulldim1[STRLEN];
    t_pullgrp *pgrp;

    ptr = pulldim;
    i   = 0;
    for (d = 0; d < DIM; d++)
    {
        if (sscanf(ptr, "%s%n", pulldim1, &nchar) != 1)
        {
            gmx_fatal(FARGS, "Less than 3 pull dimensions given in pull_dim: '%s'",
                      pulldim);
        }

        if (gmx_strncasecmp(pulldim1, "N", 1) == 0)
        {
            pull->dim[d] = 0;
        }
        else if (gmx_strncasecmp(pulldim1, "Y", 1) == 0)
        {
            pull->dim[d] = 1;
            i++;
        }
        else
        {
            gmx_fatal(FARGS, "Please use Y(ES) or N(O) for pull_dim only (not %s)",
                      pulldim1);
        }
        ptr += nchar;
    }
    if (i == 0)
    {
        gmx_fatal(FARGS, "All entries in pull_dim are N");
    }

    for (g = 0; g < pull->ngrp+1; g++)
    {
        pgrp = &pull->grp[g];
        if (g == 0 && strcmp(pgnames[g], "") == 0)
        {
            pgrp->nat = 0;
        }
        else
        {
            ig        = search_string(pgnames[g], grps->nr, gnames);
            pgrp->nat = grps->index[ig+1] - grps->index[ig];
        }
        if (pgrp->nat > 0)
        {
            fprintf(stderr, "Pull group %d '%s' has %d atoms\n",
                    g, pgnames[g], pgrp->nat);
            snew(pgrp->ind, pgrp->nat);
            for (i = 0; i < pgrp->nat; i++)
            {
                pgrp->ind[i] = grps->a[grps->index[ig]+i];
            }

            if (pull->eGeom == epullgCYL && g == 0 && pgrp->nweight > 0)
            {
                gmx_fatal(FARGS, "Weights are not supported for the reference group with cylinder pulling");
            }
            if (pgrp->nweight > 0 && pgrp->nweight != pgrp->nat)
            {
                gmx_fatal(FARGS, "Number of weights (%d) for pull group %d '%s' does not match the number of atoms (%d)",
                          pgrp->nweight, g, pgnames[g], pgrp->nat);
            }

            if (pgrp->nat == 1)
            {
                /* No pbc is required for this group */
                pgrp->pbcatom = -1;
            }
            else
            {
                if (pgrp->pbcatom > 0)
                {
                    pgrp->pbcatom -= 1;
                }
                else if (pgrp->pbcatom == 0)
                {
                    pgrp->pbcatom = pgrp->ind[(pgrp->nat-1)/2];
                }
                else
                {
                    /* Use cosine weighting */
                    pgrp->pbcatom = -1;
                }
            }

            if (g > 0 && pull->eGeom != epullgDIST)
            {
                for (d = 0; d < DIM; d++)
                {
                    if (pgrp->vec[d] != 0 && pull->dim[d] == 0)
                    {
                        gmx_fatal(FARGS, "ERROR: pull_vec%d has non-zero %c-component while pull_dim in N\n", g, 'x'+d);
                    }
                }
            }

            if ((pull->eGeom == epullgDIR || pull->eGeom == epullgCYL) &&
                g > 0 && norm2(pgrp->vec) == 0)
            {
                gmx_fatal(FARGS, "pull_vec%d can not be zero with geometry %s",
                          g, EPULLGEOM(pull->eGeom));
            }
            if ((pull->eGeom == epullgPOS) && pgrp->rate != 0 &&
                g > 0 && norm2(pgrp->vec) == 0)
            {
                gmx_fatal(FARGS, "pull_vec%d can not be zero with geometry %s and non-zero rate",
                          g, EPULLGEOM(pull->eGeom));
            }
        }
        else
        {
            if (g == 0)
            {
                if (pull->eGeom == epullgCYL)
                {
                    gmx_fatal(FARGS, "Absolute reference groups are not supported with geometry %s", EPULLGEOM(pull->eGeom));
                }
            }
            else
            {
                gmx_fatal(FARGS, "Pull group %d '%s' is empty", g, pgnames[g]);
            }
            pgrp->pbcatom = -1;
        }
    }
}
Пример #24
0
int main(void)
{
	int choice;
	char buf[15] = { 0 };
	struct sigaction sa;
	struct addr_info info = { 0 };

	memset(&sa, 0, sizeof(sa));

	sa.sa_handler = timer_handler;
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = SA_RESTART;

	if (sigaction(SIGALRM, &sa, NULL) == -1) {
		perror("sigaction()");
		exit(EXIT_FAILURE);
	}

	alarm(60);

	setbuf(stdin, NULL);
	setbuf(stdout, NULL);
	setbuf(stderr, NULL);

	dl_iterate_phdr(callback, &info);

	for (;;) {
		printf("ROP helper 13.37\n");
		printf("1. print libc address\n");
		printf("2. print function address\n");
		printf("3. insert ROP chain\n");
		printf("4. search for string\n");
		printf("5. quit\n");
		printf("Choice: ");

		if (!fgets(buf, sizeof(buf), stdin))
			break;

		choice = atoi(buf);

		switch (choice) {
		case 1:
			printf("[+] libc start address: %p\n", info.base);
			break;
		case 2:
			print_func_addr();
			break;
		case 3:
			insert_rop();
			break;
		case 4:
			search_string(info.base, info.size);
			break;
		case 5:
			printf("Bye!\n");
			goto out;
		default:
			printf("Invalid option!\n");
		}

		printf("\n");
	}

out:
	return 0;
}
Пример #25
0
	uintptr_t basic_searcher::search_string(const char* str) const
	{
		return search_string(str, strlen(str)+1);
	}
Пример #26
0
/* event callback */
gboolean
help_interactive_display (const gchar * event_group_name, const gchar * event_name,
                          gpointer init_data, gpointer data)
{
    const dlg_colors_t help_colors = {
        HELP_NORMAL_COLOR,      /* common text color */
        0,                      /* unused in help */
        HELP_BOLD_COLOR,        /* bold text color */
        0,                      /* unused in help */
        HELP_TITLE_COLOR        /* title color */
    };

    WButtonBar *help_bar;
    Widget *md;
    char *hlpfile = NULL;
    char *filedata;
    ev_help_t *event_data = (ev_help_t *) data;

    (void) event_group_name;
    (void) event_name;
    (void) init_data;

    if (event_data->filename != NULL)
        g_file_get_contents (event_data->filename, &filedata, NULL, NULL);
    else
        filedata = load_mc_home_file (mc_global.share_data_dir, MC_HELP, &hlpfile);

    if (filedata == NULL)
        message (D_ERROR, MSG_ERROR, _("Cannot open file %s\n%s"),
                 event_data->filename ? event_data->filename : hlpfile, unix_error_string (errno));

    g_free (hlpfile);

    if (filedata == NULL)
        return TRUE;

    translate_file (filedata);

    g_free (filedata);

    if (fdata == NULL)
        return TRUE;

    if ((event_data->node == NULL) || (*event_data->node == '\0'))
        event_data->node = "[main]";

    main_node = search_string (fdata, event_data->node);

    if (main_node == NULL)
    {
        message (D_ERROR, MSG_ERROR, _("Cannot find node %s in help file"), event_data->node);

        /* Fallback to [main], return if it also cannot be found */
        main_node = search_string (fdata, "[main]");
        if (main_node == NULL)
        {
            interactive_display_finish ();
            return TRUE;
        }
    }

    help_lines = min (LINES - 4, max (2 * LINES / 3, 18));

    whelp =
        dlg_create (TRUE, 0, 0, help_lines + 4, HELP_WINDOW_WIDTH + 4,
                    help_colors, help_callback, NULL, "[Help]", _("Help"),
                    DLG_TRYUP | DLG_CENTER | DLG_WANT_TAB);

    selected_item = search_string_node (main_node, STRING_LINK_START) - 1;
    currentpoint = main_node + 1;       /* Skip the newline following the start of the node */

    for (history_ptr = HISTORY_SIZE; history_ptr;)
    {
        history_ptr--;
        history[history_ptr].page = currentpoint;
        history[history_ptr].link = selected_item;
    }

    help_bar = buttonbar_new (TRUE);
    WIDGET (help_bar)->y -= WIDGET (whelp)->y;
    WIDGET (help_bar)->x -= WIDGET (whelp)->x;

    md = mousedispatch_new (1, 1, help_lines, HELP_WINDOW_WIDTH - 2);

    add_widget (whelp, md);
    add_widget (whelp, help_bar);

    buttonbar_set_label (help_bar, 1, Q_ ("ButtonBar|Help"), help_map, NULL);
    buttonbar_set_label (help_bar, 2, Q_ ("ButtonBar|Index"), help_map, NULL);
    buttonbar_set_label (help_bar, 3, Q_ ("ButtonBar|Prev"), help_map, NULL);
    buttonbar_set_label (help_bar, 4, "", help_map, NULL);
    buttonbar_set_label (help_bar, 5, "", help_map, NULL);
    buttonbar_set_label (help_bar, 6, "", help_map, NULL);
    buttonbar_set_label (help_bar, 7, "", help_map, NULL);
    buttonbar_set_label (help_bar, 8, "", help_map, NULL);
    buttonbar_set_label (help_bar, 9, "", help_map, NULL);
    buttonbar_set_label (help_bar, 10, Q_ ("ButtonBar|Quit"), help_map, NULL);

    dlg_run (whelp);
    interactive_display_finish ();
    dlg_destroy (whelp);
    return TRUE;
}
Пример #27
0
void make_pull_groups(pull_params_t *pull,
                      char **pgnames,
                      const t_blocka *grps, char **gnames)
{
    int           g, ig = -1, i;
    t_pull_group *pgrp;

    /* Absolute reference group (might not be used) is special */
    pgrp                = &pull->group[0];
    pgrp->nat           = 0;
    pgrp->pbcatom       = -1;
    pgrp->pbcatom_input = -1;

    for (g = 1; g < pull->ngroup; g++)
    {
        pgrp                = &pull->group[g];
        pgrp->pbcatom_input = pgrp->pbcatom;

        if (strcmp(pgnames[g], "") == 0)
        {
            gmx_fatal(FARGS, "Pull option pull_group%d required by grompp has not been set.", g);
        }

        ig        = search_string(pgnames[g], grps->nr, gnames);
        pgrp->nat = grps->index[ig+1] - grps->index[ig];

        fprintf(stderr, "Pull group %d '%s' has %d atoms\n",
                g, pgnames[g], pgrp->nat);

        if (pgrp->nat == 0)
        {
            gmx_fatal(FARGS, "Pull group %d '%s' is empty", g, pgnames[g]);
        }

        snew(pgrp->ind, pgrp->nat);
        for (i = 0; i < pgrp->nat; i++)
        {
            pgrp->ind[i] = grps->a[grps->index[ig]+i];
        }

        if (pgrp->nweight > 0 && pgrp->nweight != pgrp->nat)
        {
            gmx_fatal(FARGS, "Number of weights (%d) for pull group %d '%s' does not match the number of atoms (%d)",
                      pgrp->nweight, g, pgnames[g], pgrp->nat);
        }

        if (pgrp->nat == 1)
        {
            /* No pbc is required for this group */
            pgrp->pbcatom = -1;
        }
        else
        {
            if (pgrp->pbcatom > 0)
            {
                pgrp->pbcatom -= 1;
            }
            else if (pgrp->pbcatom == 0)
            {
                pgrp->pbcatom = pgrp->ind[(pgrp->nat-1)/2];
            }
            else
            {
                /* Use cosine weighting */
                pgrp->pbcatom = -1;
            }
        }
    }
}
Пример #28
0
//Read the string and execute instructions
 void GcodeProcessor::process_string(char instruction[])
{ 
  //the character / means delete block... used for comments and stuff.
  if (instruction[0] == '/' 
	|| instruction[0] == ';'
	|| instruction[0] == '#'){
    return; 
  }

//  float  currentPosition[] ={getUnitsX(), getUnitsY(), getUnitsZ() };
Point currentPosition = getMachine().getCurrentPosition();
  Point target ;


int code = 0;

   //Get Target
    
		target.x = currentPosition.x ;
		target.y = currentPosition.y ;
		target.z = currentPosition.z ;
        if (has_command('X', instruction)) target.x = search_string('X', instruction);
        if (has_command('Y', instruction)) target.y = search_string('Y', instruction);
        if (has_command('Z', instruction)) target.z = search_string('Z', instruction);
     
	 if(!abs_mode){
		target.x = currentPosition.x + search_string('X', instruction);
        target.y =  currentPosition.y + search_string('Y', instruction);;
        target.z =  currentPosition.z + search_string('X', instruction);;
      }
	//set our target.
//	 getMachine().set_target(target);
  
	double feedrate = search_string('F', instruction);
    if (feedrate > 0)  nominalFeedRate = feedrate;
  
  
  
  // handle no G code but has Coordinates remember the last feed rate
  if( ( has_command('X', instruction) ||
		has_command('Y', instruction) ||
		has_command('Z', instruction))&&
		! has_command('G', instruction)){
		//	setFeedRate(nominalFeedRate);
	  getMachine().goTo(target);

	}		
  
  
  if (    has_command('G', instruction)     )
  {
    //which one?
    code = (int)search_string('G', instruction);
    switch (code)
    {
      //Rapid Positioning
    case 0:
    	getMachine().setMaxFeedRate();
    	getMachine().goTo(target);
	break;
	
	//Linear Interpolation
    case 1:
    	getMachine().setFeedRate(nominalFeedRate);
    	getMachine().goTo(target);
      break;


      //Clockwise arc
    case 2:
      //Counterclockwise arc
    case 3:


      // Centre coordinates are always relative
      centr.x = search_string('I', instruction) + currentPosition.x;
      centr.y = search_string('J', instruction) + currentPosition.y;
      centr.z = target.z;
      bool clockwise;
	 clockwise	  = (code==2);

	 getMachine().moveAlongCurve( centr,  target, clockwise);
      break;

    case 4:
//      delay(1000*(int)search_string('P', instruction, size));
      break;

      //Inches for Units
    case 20:
    	getMachine().setInches();
      break;

      //mm for Units
    case 21:
    	getMachine().setMillimeters();
      break;

      //go home.
    case 28:
    	getMachine().goToOrigin();
      break;

      //go home via an intermediate point.
    case 30:
    	getMachine().setMaxFeedRate();
    	getMachine().goTo(target);
      //go home.
		getMachine().goToOrigin();
      break;

      //Absolute Positioning
    case 90:
      abs_mode = true; 
      break;

      //Incremental Positioning
    case 91:
	
      abs_mode = false;
      break;

      //Set as home
    case 92:
    	getMachine().setPosition(Point());
      break;

      /*
			//Inverse Time Feed Mode
       			case 93:
       
       			break;  //TODO: add this
       
       			//Feed per Minute Mode
       			case 94:
       
       			break;  //TODO: add this
       */

    default:
    	break;
//      Serial.print("huh? G");
//      Serial.println(code,DEC);
    }
  }

  if (has_command('F', instruction))
  {
		double rate = search_string('F', instruction);
		getMachine().setFeedRate(rate);
		 nominalFeedRate = rate;
		
  }
  //find us an m code.
  if (has_command('M', instruction))
  {
    code = search_string('M', instruction);
    switch (code)
    {
      //TODO: this is a bug because search_string returns 0.  gotta fix that.
    case 0:
      true;
      break;
      /*
			case 0:
       				//todo: stop program
       			break;
       
       			case 1:
       				//todo: optional stop
       			break;
       
       			case 2:
       				//todo: program end
       			break;
       	*/
      //set max extruder speed, 0-255 PWM
//    case 100:
//      extruder_speed = (int)(search_string('P', instruction, size));
//      break;
//
//      //turn extruder on, forward
//    case 101:
//      extruder_set_direction(1);
//      extruder_set_speed(extruder_speed);
//      break;
//
//      //turn extruder on, reverse
//    case 102:
//      extruder_set_direction(0);
//      extruder_set_speed(extruder_speed);
//      break;
//
//      //turn extruder off
//    case 103:
//      extruder_set_speed(0);
//      break;
//
//      //custom code for temperature control
//    case 104:
//      extruder_set_temperature((int)search_string('P', instruction, size));
//
//      //warmup if we're too cold.
//      while (extruder_get_temperature() < extruder_target_celsius)
//      {
//        extruder_manage_temperature();
//        Serial.print("T:");
//        Serial.println(extruder_get_temperature());
//        delay(1000);
//      }
//
//      break;
//
//      //custom code for temperature reading
//    case 105:
//      Serial.print("T:");
//      Serial.println(extruder_get_temperature());
//      break;
//
//      //turn fan on
//    case 106:
//      extruder_set_cooler(255);
//      break;
//
//      //turn fan off
//    case 107:
//      extruder_set_cooler(0);
//      break;

    default:
    	break;
//      Serial.print("Huh? M");
//      Serial.println(code);
    }		
  }

  //tell our host we're done.
//  Serial.println("ok");
  //	Serial.println(line, DEC);
}