コード例 #1
0
void	ManiWarmupTimer::SetRandomItem(ConVar *cvar_ptr, int item_number)
{
	item_t	*item_list = NULL;
	int	item_list_size = 0;

	const char *item_string = cvar_ptr->GetString();

	if (FStrEq(item_string,""))
	{
		item_name[item_number][0] = '\0';
		return;
	}

	int i = 0;
	int j = 0;
	char	tmp_item_name[80] = "";

	for (;;)
	{
		if (item_string[i] == ':' || item_string[i] == '\0')
		{
			tmp_item_name[j] = '\0';
			if (i != 0)
			{
				AddToList((void **) &item_list, sizeof(ManiWarmupTimer::item_t), &item_list_size);
				Q_strcpy(item_list[item_list_size - 1].item_name, tmp_item_name);

				j = 0;
				if (item_string[i] == '\0')
				{
					break;
				}
				else
				{
					i++;
					j = 0;
					continue;
				}
			}
			else
			{
				break;
			}
		}

		tmp_item_name[j] = item_string[i];
		j++;
		i++;
	}

	if (item_list_size == 0)
	{
		item_name[item_number][0] = '\0';
	}
	else if (item_list_size == 1)
	{
		strcpy(item_name[item_number], item_list[0].item_name);
	}
	else
	{
		int choice = rand() % item_list_size;
		strcpy(item_name[item_number], item_list[choice].item_name);
	}

	FreeList((void **) &item_list, &item_list_size);
	return;
}
コード例 #2
0
static char *GetModuleName(Tcl_Interp *interp, char *path, char *prefix,
						   char *modulename)
{
    struct stat	  stats;		/** Buffer for the stat() systemcall **/
    char	 *fullpath = NULL;	/** Buffer for creating path names   **/
    char	 *Result = NULL;	/** Our return value		     **/
    char	**filelist = NULL;	/** Buffer for a list of possible
								 ** module files		     **/
    int		  numlist;		/** Size of this list		     **/
    int		  i, slen, is_def;
    char	 *s, *t;		/** Private string buffer	     **/
    char	 *mod, *ver;		/** Pointer to module and version    **/
    char	 *mod1, *ver1;		/** Temp pointer		     **/

#if WITH_DEBUGGING_LOCATE_1
    ErrorLogger(NO_ERR_START, LOC, _proc_GetModuleName, NULL);
#endif /* WITH_DEBUGGING_LOCATE_1 */
    /**
     **  Split the modulename into module and version. Use a private buffer
     **  for this
     **/
    if ((char *)NULL == (s = stringer(NULL, 0,  modulename, NULL))) {
		ErrorLogger(ERR_ALLOC, LOC, NULL);
		goto unwind0;
    }
    slen = (int)(strlen(s) + 1);
    mod = s;
	/* assume that the '=' here is correct, because otherwise 'ver' would not
	 * be initialized here yet (I think): */
    if ((ver = strrchr(mod, '/'))) {
		*ver++ = '\0';
	}
    /**
     **  Allocate a buffer for full pathname building:
     **/
    if ((char *)NULL == (fullpath = stringer(NULL, MOD_BUFSIZE, NULL))) {
		if (OK != ErrorLogger(ERR_STRING, LOC, NULL)) {
			goto unwind1;
		}
    }
    /**
     **  Check whether $path/$prefix/$modulename is a directory.
     **/
    if (prefix) {
		if ((char *)NULL == stringer(fullpath, MOD_BUFSIZE, path, "/", prefix,
									 "/", modulename, NULL)) {
			goto unwind1;
		}
    } else {
		if ((char *)NULL == stringer(fullpath, MOD_BUFSIZE, path, "/",
									 modulename, NULL)) {
			goto unwind1;
		}
    }
    if (!stat(fullpath, &stats) && S_ISDIR(stats.st_mode)) {
		/**
		 ** So the full modulename is $modulename/default.  Recurse on that.
		 **/
		if ((char *)NULL == (t = stringer(NULL, 0, modulename, "/",
										  _default, NULL))) {
			goto unwind1;
		}
		Result = GetModuleName(interp, path, prefix, t);
		null_free((void *)&t);
		null_free((void *)&fullpath);
		null_free((void *)&s);
		return (Result);
    }

    /**
     **  Check whether $path/$prefix/$mod is a directory:
     **/
    if (prefix) {
		if ((char *)NULL == stringer(fullpath, MOD_BUFSIZE, path, "/", prefix,
									 "/", mod, NULL)) {
			goto unwind1;
		}
    } else {
		if ((char *)NULL == stringer(fullpath, MOD_BUFSIZE, path, "/",
									 mod, NULL)) {
			goto unwind1;
		}
    }
    is_def = !strcmp(mod, _default);

    if (is_def || !stat(fullpath, &stats)) {
		/**
		 **  If it is a directory, then do this:
		 **/
    	if (!is_def && S_ISDIR( stats.st_mode)) {
			/**
			 **  Source the ".modulerc" file if it exists.
			 **  For compatibility source the .version file, too.
			 **/
			if (prefix) {
				if ((char *)NULL == stringer(modfil_buf, MOD_BUFSIZE,
											 prefix, "/", mod, NULL)) {
					goto unwind2;
				}
			} else {
				if ((char *)NULL == stringer(modfil_buf, MOD_BUFSIZE,
											 mod, NULL)) {
					goto unwind2;
				}
			}

			if ((char *)NULL == stringer(fullpath, MOD_BUFSIZE, path, "/",
										 modfil_buf, NULL)) {
				goto unwind2;
			}
			g_current_module = modfil_buf;

			if ((TCL_ERROR == SourceRC(interp, fullpath, modulerc_file)) ||
				(TCL_ERROR == SourceVers(interp, fullpath, modfil_buf))) {
				/* flags = save_flags; */
				goto unwind2;
			}
			/**
			 **  After sourcing the RC files, we have to look up the
			 **  versions again:
			 **/
			if (VersionLookup(modulename, &mod1, &ver1)) {
				int len = (int)(strlen(mod1) + strlen(ver1) + 2);
				/**
				 **  Maybe we have to enlarge s:
				 **/
				if (len > slen) {
					null_free((void *)&s);
					if((char *)NULL == (s = stringer( NULL, len, NULL))) {
						ErrorLogger( ERR_STRING, LOC, NULL);
						goto unwind2;
					}
					slen = len;
					/* dummy condition to use 'slen': */
					if (slen == 0) {
						;
					}
				}
				/**
				 **  Print the new module/version in the buffer:
				 **/
				if ((char *)NULL == stringer(s, len, mod1, "/", ver1, NULL)) {
					ErrorLogger(ERR_STRING, LOC, NULL);
					goto unwind2;
				}
				mod = s;
				if (ver = strchr(s, (int)'/')) {
					*ver++ = '\0';
				}
			}
			/**
			 **  recursively delve into subdirectories (until ver == NULL).
			 **/
	    if (ver) {
			int len;
			len = (int)(strlen(mod) + 1);

			if (prefix) {
				len += (strlen(prefix) + 1);
			}
		/**
		 **  Build the new prefix
		 **/
		if((char *) NULL == (t = stringer(NULL, len, NULL))) {
		    ErrorLogger( ERR_STRING, LOC, NULL);
		    goto unwind2;
		}

		if( prefix) {
		    if((char *) NULL == stringer(t, len, prefix,"/",mod, NULL)){
			ErrorLogger( ERR_STRING, LOC, NULL);
			goto unwindt;
		    }
		} else {
		    if((char *) NULL == stringer(t, len, mod, NULL)){
			ErrorLogger( ERR_STRING, LOC, NULL);
			goto unwindt;
		    }
		}
		/**
		 **  This is the recursion
		 **/
		Result = GetModuleName( interp, path, t, ver);

		/**
		 **  Free our temporary prefix buffer
		 **/
		null_free((void *) &t);
		if (0) {	/* an error occurred */
unwindt:
		    null_free((void *) &t);
		    goto unwind2;
		}
	    }
	} else {     /** if ($path/$prefix/$mod is a directory) **/
	    /**
	     **  Now 'mod' should be either a file or the word 'default'
	     **  In case of default get the file with the highest version number
	     **  in the current directory
	     **/
	    if( is_def) {
		if( !prefix)
		    prefix = ".";
		if( NULL == (filelist = SortedDirList( interp, path, prefix,
		&numlist)))
		    goto unwind1;

		prefix = (char *)NULL;
		/**
		 **  Select the first one on the list which is either a
		 **  modulefile or another directory. We start at the highest
		 **  lexicographical name in the directory since the filelist
		 **  is reverse sorted.
		 **  If it is a directory, then we delve into it.
		 **/
		for( i=0; i<numlist && Result==NULL; i++) {
		    /**
		     **  Build the full path name and check if it is a
		     **  directory. If it is, recursively try to find there what
		     **  we are/were seeking for
		     **/
		    if ((char *)NULL == stringer(fullpath, MOD_BUFSIZE,
			path, "/", filelist[i], NULL))
			    goto unwind2;

		    if( !stat( fullpath, &stats) && S_ISDIR( stats.st_mode)) {
			Result = GetModuleName( interp, path, prefix,
			    filelist[ i]);
		    } else {
			/**
			 **  Otherwise check the file for a magic cookie ...
			 **/
			if( check_magic( fullpath, MODULES_MAGIC_COOKIE,
			    MODULES_MAGIC_COOKIE_LENGTH))
			    Result = filelist[ i];
		    } /** end "if (!stat)" **/
		} /** end for-loop **/
	    } else {  /** default **/
		/**
		 **  If mod names a file, we have to check wheter it exists and
		 **  is a valid module file
		 **/
		if( check_magic( fullpath, MODULES_MAGIC_COOKIE,
		    MODULES_MAGIC_COOKIE_LENGTH))
		    Result = mod;
		else {
		    ErrorLogger( ERR_MAGIC, LOC, fullpath, NULL);
		    Result = NULL;
		}
	    } /** if( mod is a filename) **/
	    /**
	     **  Build the full filename (using prefix and Result) if
	     **  Result is defined
	     **/
	    if (Result) {
			int len;
			len = (int)(strlen(Result) + 1);

			if (prefix) {
				len += (strlen(prefix) + 1);
			}

		if((char *) NULL == (t = stringer(NULL, len, NULL))) {
		   ErrorLogger( ERR_STRING, LOC, NULL);
		   goto unwind2;
		}
		if( prefix) {
		    if((char *) NULL == stringer(t,len, prefix,"/",Result,NULL))
			goto unwindt2;
		} else {
		    if((char *) NULL == stringer(t,len, Result,NULL))
			goto unwindt2;
		}
		Result = t;
		if (0) {	/* an error occurred */
unwindt2:
		    null_free((void *) &t);
		    goto unwind2;
		}
	    }
	} /** mod is a file **/
    } /** mod exists **/
    /**
     **  Free up temporary values and return what we've found
     **/
    null_free((void*) &fullpath);
    null_free((void*) &s);
    FreeList(filelist, numlist);

#if WITH_DEBUGGING_LOCATE_1
    ErrorLogger(NO_ERR_END, LOC, _proc_GetModuleName, NULL);
#endif /* WITH_DEBUGGING_LOCATE_1 */
    return (Result);			/** -------- EXIT (SUCCESS) -------> **/

unwind2:
    null_free((void *)&fullpath);
unwind1:
    null_free((void *)&s);
unwind0:
    return(NULL);			/** -------- EXIT (FAILURE) -------> **/

} /** End of 'GetModuleName' (that was a lengthy function...) **/
コード例 #3
0
static void
FreeConfig(void)
{
    FreeList(&builtinConfig, &builtinLines);
}
コード例 #4
0
ファイル: MAIN.C プロジェクト: jskripsky/ancient
VOID _cdecl Main( WORD NumArgs, CHAR *Args[], CHAR *EnvStrings[] )
    {
    MSG     Msg;
    WORD    Key;

    CHAR FileName[65];
    CHAR PrinterPort[65];

    HFILE TMSBegrFile;
    HFILE TMSAbtFile;
    HFILE TMSZKontFile;

    DWORD EffTime;

    WinInitialize( MAXNUMWINDOWS );
    WinCreateWindow( Desktop, &Desktop, NULL, 0, 0, 0, 0, 0, 0 );

    WinHideCursor();
    WinColor( Desktop, NORMAL, 0, 0, WinGetx2( Desktop ), WinGety2( Desktop ) );

    WinCreateWindow( Desktop, &Bottomline, BottomlineProc, 0, 0, BOTTOMLINEX1, BOTTOMLINEY1, BOTTOMLINEX2, BOTTOMLINEY2 );

    if( !ReadConfigData() )
	{
	static struct HelpKey HelpKeys[NUMLAUFWERKHELPKEYS] =
	    { {	0,   0, "</>    Wert erh�hen/erniedrigen" },
	      { 0,   1, "<Enter>  Wert akzeptieren" },
	      { 40,  1, "<Esc>    Programm verlassen" } };

	HWND TMSLaufwerk;
	BOOL LaufwerkOK;

	WinFill( Desktop, '�',	0, 22, 79, 22 );
	InitConfigData();

	WinString( Desktop, "TMS Laufwerk", CENTER, 0, 7 );
	WinString( Desktop, "������������", CENTER, 0, 8 );
	WinColor( Desktop, HIGHLIGHT, 33, 7, 46, 7 );
	WinCreateWindow( Desktop, &TMSLaufwerk, TMSLaufWerkProc, 0, 0, 37, 10, 40, 10 );
	WinString( Desktop, "Geben Sie bitte an, in welchem Laufwerk sich TMS befindet.", CENTER, 0, 14 );

	WinSendMsg( Bottomline, WM_HELP, (WORD)&HelpKeys, NUMLAUFWERKHELPKEYS );

	WinSendMsg( TMSLaufwerk, WM_SHOW, 0, 0 );
	WinSendMsg( TMSLaufwerk, WM_SETFOCUS, 0, 0 );

	do
	    {
	    LaufwerkOK = TRUE;
	    do
		{
		Key = BiosGetKey();
		Msg = WinSendMsg( TMSLaufwerk, WM_CHAR, (MPARAM)Key, 0 );
		}
	    while( (WORD)Msg != KBENTER && (WORD)Msg != KBESC );

	    if( (WORD)Msg == KBESC )
		{
		DosFreeFarMem( ConfigData );

		WinDestroyWindow( TMSLaufwerk );
		WinDestroyWindow( Bottomline );
		WinDestroyWindow( Desktop );
		return;
		}

	    if( !OpenPathFile() )
		{
		LaufwerkOK = FALSE;
		}
	    }
	while( !LaufwerkOK );

	ClosePathFile();
	WinDestroyWindow( TMSLaufwerk );
	WinColor( Desktop, NORMAL, 0, 0, WinGetx2( Desktop ), 21 );
	WinFill( Desktop, SPACECHAR, 0, 0, WinGetx2( Desktop ), WinGety2( Desktop ) );
	}

    switch( NumArgs )
	{
	case 2:
	    StdStrLwr( Args[1] );
	    if( StdStrCmp( Args[1], "exportfile" ) == 0 ||
		StdStrCmp( Args[1], "export" ) == 0 )
		{
		WinFill( Desktop, '�',	0, 22, 79, 22 );
		ExportFileConversion();
		}
	    else
		{
		; // Debug!!!!
		}
	    break;

	case 1:
	    if( !OpenPathFile() )
		; // Debug!!!!!

	    ReadPathFileEntry( TMSBEGRUENDNO, FileName, FALSE );

	    DosOpen( FileName, &TMSBegrFile, OPEN_RDONLY );
	    DosLastModTime( TMSBegrFile, &EffTime );
	    if( ConfigData->TMSBegruendungsDatum != EffTime )
		{
		if( !CreateList( TMSBegrFile, BEGRUENDUNGEN ) )
		    {
		    WinString( Desktop, "In TMS sind 0 Begr�ndungen verzeichnet!", LEFT, 0, 0 );
		    return; // Debug-Version!!!!!
		    }

		SortList( BEGRUENDUNGEN );
		ConfigData->TMSBegruendungsDatum = EffTime;
		StdFarMemSet( ConfigData->BegrCheckListe, TRUE, sizeof( ConfigData->BegrCheckListe ) );
		}
	    DosClose( TMSBegrFile );

	    ReadPathFileEntry( TMSABTEILNO, FileName, FALSE );

	    DosOpen( FileName, &TMSAbtFile, OPEN_RDONLY );
	    DosLastModTime( TMSAbtFile, &EffTime );
	    if( ConfigData->TMSAbteilungsDatum != EffTime )
		{
		if( !CreateList( TMSAbtFile, ABTEILUNGEN ) )
		    {
		    WinString( Desktop, "In TMS sind 0 Abteilungen verzeichnet!", LEFT, 0, 0 );
		    return; // Debug-Version!!!!!
		    }
		SortList( ABTEILUNGEN );
		ConfigData->TMSAbteilungsDatum = EffTime;
		StdFarMemSet( ConfigData->AbtCheckListe, TRUE, sizeof( ConfigData->AbtCheckListe ) );
		}
	    DosClose( TMSAbtFile );

	    ReadPathFileEntry( TMSZEITKNO, FileName, FALSE );

	    DosOpen( FileName, &TMSZKontFile, OPEN_RDONLY );
	    DosLastModTime( TMSZKontFile, &EffTime );
	    if( ConfigData->TMSZeitKontiDatum != EffTime )
		{
		if( !CreateList( TMSZKontFile, ZEITKONTI ) )
		    {
		    WinString( Desktop, "In TMS sind 0 Zeitkonti verzeichnet!", LEFT, 0, 0 );
		    return; // Debug-Version!!!!!
		    }
		// SortList( ZEITKONTI );
		ConfigData->TMSZeitKontiDatum = EffTime;
		StdFarMemSet( ConfigData->ZKontCheckListe, TRUE, sizeof( ConfigData->ZKontCheckListe ) );
		}
	    DosClose( TMSZKontFile );

	    ReadPathFileEntry( TMSPRINTERINFONO, FileName, FALSE );
	    ReadPathFileEntry( TMSPRINTERPORTNO, PrinterPort, TRUE );
	    GetPrinterInfo( FileName, PrinterPort );

	    ClosePathFile();

	    LoadList( BEGRUENDUNGEN );
	    LoadList( ABTEILUNGEN );
	    LoadList( ZEITKONTI );

	    WinString( Desktop, "������������������������������������Ŀ", CENTER, 0,  3 );
	    WinString( Desktop, "�                                    �", CENTER, 0,  4 );
	    WinString( Desktop, "�      Statistik - Generierung       �", CENTER, 0,  5 );
	    WinString( Desktop, "�      �����������������������       �", CENTER, 0,  6 );
	    WinString( Desktop, "�                und                 �", CENTER, 0,  7 );
	    WinString( Desktop, "�                ���                 �", CENTER, 0,  8 );
	    WinString( Desktop, "�     Verwaltung der Exportdaten     �", CENTER, 0,  9 );
	    WinString( Desktop, "�     ��������������������������     �", CENTER, 0, 10 );
	    WinString( Desktop, "�                                    �", CENTER, 0, 11 );
	    WinString( Desktop, "�              von TMS               �", CENTER, 0, 12 );
	    WinString( Desktop, "�                                    �", CENTER, 0, 13 );
	    WinString( Desktop, "��������������������������������������", CENTER, 0, 14 );

	    WinString( Desktop, " (c) Copyright 1992, 1993 J.Skripsky  ", CENTER, 0, 16 );

	    WinString( Desktop, "      Designed and Developed by       ", CENTER, 0, 18 );
	    WinString( Desktop, "           Juraj Skripsky             ", CENTER, 0, 19 );
	    WinString( Desktop, "         CH-8952 Schlieren            ", CENTER, 0, 20 );

	    BiosGetKey();
	    WinFill( Desktop, SPACECHAR, 0, 0, WinGetx2( Desktop ), WinGety2( Desktop ) );

	    WinFill( Desktop, '�', 0, 22, 79, 22 );

	    WinFill( Desktop, '�', 27,	0, 27, 21 );
	    WinFill( Desktop, '�',  0, 22, 79, 22 );
	    WinCreateWindow( Desktop, &Menu, MenuProc, 0, 0, 1, 1, 25, 20 );

	    WinSendMsg( Menu, WM_SHOW, 0, 0 );
	    WinSendMsg( Menu, WM_SETFOCUS, 0, 0 );

	    do
		{
		Key = BiosGetKey();
		Msg = WinSendMsg( Menu, WM_CHAR, (MPARAM)Key, 0 );
		}
	    while( (WORD)Msg != KBESC );


	    FreeList( BEGRUENDUNGEN );
	    FreeList( ABTEILUNGEN );
	    FreeList( ZEITKONTI );

	    FreePrinterInfo();

	    WinDestroyWindow( Menu );
	    break;
	 }

    if( !WriteConfigData() )
	; // Debug!!!!!

    WinDestroyWindow( Bottomline );
    WinDestroyWindow( Desktop );
    WinTerminate();
    }
コード例 #5
0
ファイル: list.c プロジェクト: ignacioespinoso/MC202
// Completely deletes the list.
void FreeList(List Node) {
    if(Node) {
        FreeList(Node->next);
        free(Node);
    }
}
コード例 #6
0
ファイル: query.c プロジェクト: cjunmokim/Search-Engine
void And(char *word, HashTable *Index) {

	unsigned long index = JenkinsHash(word, MAX_HASH_SLOT); // Get the hash code.
	
	// Declare variables for traversal.
	WordNode *current;
	DocumentNode *ptr, *ptr2, *runner, *no_need;
	int num;
	
	// Get matching WordNode of word if it is in the InvertedIndex.
	if ((num = InHashTable(word, Index))) {
		current = Index->table[index]->data;
		// Loop until we get the matching WordNode.
		for (int i=1; i < num; i++) {
			current = current->next;
		}
		ptr2 = current->page; // Set to start of the list of document nodes for the current word.
	}
	else {
		ptr2 = NULL;
	}
	
	// Initialize variables. 
	ptr = temp_list;
	
	while (ptr != NULL) {
	
		// Check that the word is in the InvertedIndex.
		if (num) {
			ptr2 = current->page; // Set to start of the list of document nodes for the current word.
			
			// Loop until the end of the new list of matching DocumentNodes.
			while (ptr2 != NULL) {
				// Check for a match in doc_id.
				if (ptr->doc_id == ptr2->doc_id) {
					ptr->freq += ptr2->freq; // Add the frequencies.
					break;
				}
				ptr2 = ptr2->next;
			}
			
			// Case of no match.
			if (ptr2 == NULL) {
			
				// Check if we need to delete the first node of temp_list.
				if (ptr == temp_list) { 
					temp_list = temp_list->next;
				}
				else { // All other cases.
					runner->next = runner->next->next;
				}
				no_need = ptr;
				ptr = ptr->next;
				
				// Free the node to be deleted.
				no_need->next = NULL;
				free(no_need);
				no_need = NULL;
				
			}
			else { // Case of match.
				runner = ptr;
				ptr = ptr->next;
			}
		}
		else { // Word is not in the InvertedIndex.
			ptr = NULL;
			FreeList(0);
		}
	}
}
コード例 #7
0
//---------------------------------------------------------------------------------
// Purpose: Init stuff for plugin load
//---------------------------------------------------------------------------------
void ManiReservedSlot::CleanUp(void)
{
	FreeList((void **) &reserve_slot_list, &reserve_slot_list_size);
	FreeList((void **) &active_player_list, &active_player_list_size);
}
コード例 #8
0
ファイル: skype_contacts.cpp プロジェクト: Seldom/miranda-ng
void CSkypeProto::LoadContactList(const NETLIBHTTPREQUEST *response)
{
	if (response == NULL)
		return;

	JSONNode root = JSONNode::parse(response->pData);
	if (!root)
		return;

	LIST<char> skypenames(1);
	bool loadAll = getBool("LoadAllContacts", false);
	const JSONNode &items = root["contacts"].as_array();
	for (size_t i = 0; i < items.size(); i++)
	{
		const JSONNode &item = items.at(i);
		if (!item)
			break;

		const JSONNode &name = item["name"];
		const JSONNode &phones = item["phones"];

		std::string skypename = item["id"].as_string();
		CMString display_name = item["display_name"].as_mstring();
		CMString first_name = name["first"].as_mstring();
		CMString last_name = name["surname"].as_mstring();
		CMString avatar_url = item["avatar_url"].as_mstring();
		std::string type = item["type"].as_string();
		
		if (type == "skype" || loadAll)
		{
			MCONTACT hContact = AddContact(skypename.c_str());
			if (hContact)
			{
				if (item["authorized"].as_bool())
				{
					delSetting(hContact, "Auth");
					delSetting(hContact, "Grant");
				}
				else setByte(hContact, "Grant", 1);

				if (item["blocked"].as_bool())
				{
					db_set_dw(hContact, "Ignore", "Mask1", 127);
					db_set_b(hContact, "CList", "Hidden", 1);
					setByte(hContact, "IsBlocked", 1);
				}
				else
				{
					if (db_get_b(hContact, m_szModuleName, "IsBlocked", 0))
					{
						db_set_dw(hContact, "Ignore", "Mask1", 0);
						db_set_b(hContact, "CList", "Hidden", 0);
						setByte(hContact, "IsBlocked", 0);
					}
				}

				setString(hContact, "Type", type.c_str());

				if (display_name) 
					setTString(hContact, "Nick", display_name); 
				if (first_name) 
					setTString(hContact, "FirstName", first_name); 
				if (last_name)
					setTString(hContact, "LastName", last_name); 

				SetAvatarUrl(hContact, avatar_url);
				ReloadAvatarInfo(hContact);

				for (size_t j = 0; j < phones.size(); j++)
				{
					const JSONNode &phone = phones.at(j);
					if (!phone)
						break;

					CMString number = phone["number"].as_mstring();

					switch (phone["type"].as_int())
					{
					case 0:
						setTString(hContact, "Phone", number);
						break;
					case 2:
						setTString(hContact, "Cellular", number);
						break;
					}
				}

				if (type == "skype") skypenames.insert(mir_strdup(skypename.c_str()));
			}
		}
	}

	if (skypenames.getCount() > 0)
	{
		int i = 0;
		do
		{
			LIST<char> users(1);
			for (; i < skypenames.getCount() && users.getCount() <= 50; i++)
				users.insert(skypenames[i]);
			PushRequest(new GetContactsInfoRequest(li, users), &CSkypeProto::LoadContactsInfo);
		}
		while(i < skypenames.getCount());

		FreeList(skypenames);
		skypenames.destroy();
	}
	PushRequest(new GetContactsAuthRequest(li), &CSkypeProto::LoadContactsAuth);
}
コード例 #9
0
int	cmdSetPath(ClientData client_data, Tcl_Interp *interp, int argc,
			   CONST84 char *argv[])
{
    Tcl_RegExp chkexpPtr;	/** Regular expression for
							 * marker checking	 **/
    char *oldpath,			/** Old value of 'var'	     **/
		 *newpath,			/** New value of 'var'	     **/
		 *sw_marker = APP_SW_MARKER,	/** arbitrary default	     **/
		 *startp = NULL, *endp = NULL,	/** regexp match endpts	     **/
		 *qualifiedpath,	/** List of dirs which
						     * are NOT already in path   **/
		**pathlist;			/** List of dirs	     **/
    const char *delim = _colon;		/** path delimiter	     **/
    int		append = 1,			/** append or prepend	     **/
			numpaths,			/** number of dirs in path   **/
			qpathlen,			/** qualifiedpath length     **/
			arg1 = 1,			/** arg start		     **/
			x;				/** loop index		     **/
    Tcl_Obj	 *np_obj;			/** new path Tcl Obj	     **/

#if WITH_DEBUGGING_CALLBACK
    ErrorLogger(NO_ERR_START, LOC, _proc_cmdSetPath, NULL);
#endif /* WITH_DEBUGGING_CALLBACK */

    /**
     **  Whatis mode?
     **/
    if (g_flags & (M_WHATIS | M_HELP)) {
        goto success0;
	}

    /**
     **   Check arguments. There should be at least 3 args:
     **     argv[0]  -  prepend/append
     **     ...
     **     argv[n-1]-  varname
     **     argv[n]  -  value
     **/
    if(argc < 3) {
		if (OK != ErrorLogger(ERR_USAGE, LOC, argv[0],
							  " path-variable directory", NULL)) {
			goto unwind0;
		}
	}

    /**
     **  Should this guy be removed from the variable(?)... If yes, then do so!
     **/
    if (g_flags & M_REMOVE) {
		return (cmdRemovePath(client_data, interp, argc, argv));   /** ----> **/
	}

    /**
     **  prepend or append. The default is append.
     **/
    if (!(append = !!strncmp(argv[0], "pre", 3))) {
		sw_marker = PRE_SW_MARKER;
	}

    /**
     **  Non-persist mode?
     **/

    if (g_flags & M_NONPERSIST) {
		return (TCL_OK);
    }

    /**
     **  Display only ... ok, let us do so!
     **/
    if (g_flags & M_DISPLAY) {
	fprintf(stderr, "%s\t ", argv[0]);
		while (--argc) {
			fprintf( stderr, "%s ", *++argv);
		}
		fprintf(stderr, "\n");
        goto success0;
    }

    /**
     **  Check for the delimiter option
     **/
    if (*(argv[arg1]) == '-') {
		if (!strcmp(argv[arg1], "-d")) {
			delim = argv[(arg1 + 1)];
			arg1 += 2;
		} else if (!strcmp(argv[arg1], "--delim")) {
			delim = argv[(arg1 + 1)];
			arg1 += 2;
		} else if (!strncmp(argv[arg1], "--delim=", 8)) {
			delim = (argv[arg1] + 8);
			arg1++;
		}
    }

    /**
     **  Get the old value of the variable. MANPATH defaults to a configure
     **  generated value.
     **  Put a \ in front of each '.' and '+'.
     **  (this is an intentional memory leak)
     **/
    oldpath = EMGetEnv(interp, argv[arg1]);
    _TCLCHK(interp)

    if(!oldpath || !*oldpath) {
		null_free((void *) &oldpath);
		oldpath = ((!strcmp(argv[arg1], "MANPATH"))
				   ? stringer(NULL, 0, DEFAULTMANPATH, NULL)
				   : stringer(NULL, 0, "", NULL));
    }

    /**
     **  Split the new path into its components directories so each
     **  directory can be checked to see whether it is already in the
     **  existing path.
     **/
    if (!(pathlist = SplitIntoList(interp, (char *)argv[(arg1 + 1)],
								   &numpaths, delim))) {
		goto unwind0;
	}

    /**
     **  Some space for the list of paths which
     **  are not already in the existing path.
     **/
    if((char *) NULL == (qualifiedpath = stringer(NULL, 0, argv[(arg1 + 1)],
												  delim, NULL))) {
		if (OK != ErrorLogger(ERR_STRING, LOC, NULL)) {
			goto unwind1;
		}
	}

    qpathlen = (int)(strlen(qualifiedpath) + 1);
    *qualifiedpath = '\0';		/** make sure null for later	     **/

    for ((x = 0); (x < numpaths); x++) {

		regex_quote(pathlist[x], buffer, PATH_BUFLEN);

		/**
		 **  Check to see if path is already in this path variable.
		 **  It could be at the
		 **     beginning ... ^path:
		 **     middle    ... :path:
		 **     end       ... :path$
		 **     only one  ... ^path$
		 **/
		if ((char *)NULL == (newpath = stringer(NULL, 0, "(^", buffer, delim,
												")|(", delim, buffer, delim,
												")|(", delim, buffer, "$)|(^",
												buffer, "$)", NULL))) {
			if (OK != ErrorLogger( ERR_STRING, LOC, NULL)) {
				goto unwind2;
			}
		}

		np_obj = Tcl_NewStringObj(newpath, (int)strlen(newpath));
		chkexpPtr = Tcl_GetRegExpFromObj(interp, np_obj, TCL_REG_ADVANCED);
		_TCLCHK(interp)
		null_free((void *)&newpath);

		/**
		 **  If the directory is not already in the path,
		 **  add it to the qualified path.
		 **/
		if (!Tcl_RegExpExec(interp, chkexpPtr, oldpath, oldpath)) {
			if (!stringer((qualifiedpath + strlen(qualifiedpath)),
						  (int)((unsigned long)qpathlen - strlen(qualifiedpath)),
						  pathlist[x], delim, NULL)) {
				if (OK != ErrorLogger(ERR_STRING, LOC, NULL)) {
					goto unwind2;
				}
			}
		}
    }	/** End of loop that checks for
		 ** already existent path
		 **/
    /**
     **  If all of the directories in the new path already exist,
     **  exit doing nothing.
     **/
    if (! *qualifiedpath) {
		goto success1;
	}

    /* remove trailing delimiter */
    qualifiedpath[(strlen(qualifiedpath) - 1)] = '\0';

    /**
     **  Some space for our newly created path.
     **  We size at the oldpath plus the addition.
     **/
    if (!(newpath = stringer(NULL, (int)(strlen(oldpath) + strlen(qualifiedpath) + 2), NULL))) {
		if (OK != ErrorLogger(ERR_STRING, LOC, NULL)) {
			goto unwind2;
		}
	}
    *newpath = '\0';

    /**
     **  Easy job to do, if the old path has not been set up so far ...
     **/
    if (!strcmp(oldpath, "")) {
		strcpy(newpath, qualifiedpath);

		/**
		 **  Otherwise we have to take care on prepending vs. appending ...
		 **  If there is a append or prepend marker within the variable (see
		 **  modules_def.h) the changes are made according to this markers. Other-
		 **  wise append and prepend will be relative to the strings begin or end.
		 **/
    } else {
		Tcl_Obj *sw_obj = Tcl_NewStringObj(sw_marker, (int)strlen(sw_marker));
		Tcl_RegExp markexpPtr = Tcl_GetRegExpFromObj(interp,
													 sw_obj,
													 TCL_REG_ADVANCED);
		_TCLCHK(interp)

		strcpy(newpath, oldpath);

		if (Tcl_RegExpExec(interp, markexpPtr, oldpath, oldpath)) {
			_TCLCHK(interp)
			Tcl_RegExpRange(markexpPtr, 0,
							(CONST84 char **)&startp, (CONST84 char **)&endp);

			/**
			 **  Append/Prepend marker found
			 **/
			if (append) {
				char ch = *startp;
				*startp = '\0';
				strcpy(newpath, oldpath);
                /**
                 ** check that newpath has a value before adding delim
                 **/
				if ((strlen(newpath) > 0) &&
					(newpath[(strlen(newpath) - 1)] != *delim)) {
					strcat(newpath, delim);
				}
				strcat(newpath, qualifiedpath);
				if (newpath[strlen(newpath)-1] != *delim) {
					strcat(newpath, delim);
				}
				*startp = ch;
				strcat(newpath, startp);
			} else {
                char ch = *endp;
				*endp = '\0';
				strcpy(newpath, oldpath);
				if (newpath[strlen(newpath)-1] != *delim) {
					strcat(newpath, delim);
				}
				strcat(newpath, qualifiedpath);
				*endp = ch;
				strcat(newpath, endp);
			}
		} else {
			/**
			 **  No marker set
			 **/
			if (append) {
				strcpy(newpath, oldpath);
				if (newpath[strlen(newpath)-1] != *delim) {
					strcat(newpath, delim);
				}
				strcat(newpath, qualifiedpath);
			} else {
				strcpy(newpath, qualifiedpath);
				if (*oldpath != *delim)	{
					strcat(newpath, delim);
				}
				strcat(newpath, oldpath);
			} /* end "if (append)" */
		} /** end "if (marker)" **/
    } /** end "if (strcmp)" **/

    /**
     **  Now the new value to be set resides in 'newpath'. Set it up.
     **/
    moduleSetenv(interp, (char *)argv[arg1], newpath, 1);
    _TCLCHK(interp)

#if WITH_DEBUGGING_CALLBACK
    ErrorLogger(NO_ERR_END, LOC, _proc_cmdSetPath, NULL);
#endif /* WITH_DEBUGGING_CALLBACK */

    /**
     ** Free resources
     **/
    null_free((void *)&newpath);
success1:
    null_free((void *)&oldpath);
    null_free((void *)&qualifiedpath);
    FreeList(pathlist, numpaths);
success0:
    return (TCL_OK);			/** -------- EXIT (SUCCESS) -------> **/

unwind2:
    null_free((void *)&qualifiedpath);
unwind1:
    FreeList(pathlist, numpaths);
unwind0:
    null_free((void *)&oldpath);
    return (TCL_ERROR);			/** -------- EXIT (FAILURE) -------> **/

} /** End of 'cmdSetPath' **/
コード例 #10
0
//---------------------------------------------------------------------------------
// Purpose: Load and pre-cache the sounds used
//---------------------------------------------------------------------------------
void	LoadSounds(void)
{
	FileHandle_t file_handle;
	char	sound_id[512];
	char	sound_name[512];
	char	alias_command[512];

	char	base_filename[256];

	if (!esounds) return;

	FreeList((void **) &sound_list, &sound_list_size);

	snprintf(base_filename, sizeof (base_filename), "./cfg/%s/soundlist.txt", mani_path.GetString());
	file_handle = filesystem->Open (base_filename, "rt", NULL);
	if (file_handle == NULL)
	{
//		MMsg("Failed to load soundlist.txt\n");
	}
	else
	{
//		MMsg("Sound list\n");
		while (filesystem->ReadLine (sound_id, 512, file_handle) != NULL)
		{
			if (!ParseAliasLine(sound_id, alias_command, true, false))
			{
				// String is empty after parsing
				continue;
			}

			char	exists_string[512];

			// Check file exists on server
			snprintf(exists_string, sizeof(exists_string), "./sound/%s", sound_id);
			if (!filesystem->FileExists(exists_string)) continue;

			AddToList((void **) &sound_list, sizeof(sound_t), &sound_list_size);
			Q_strcpy(sound_list[sound_list_size-1].sound_name, sound_id);
			Q_strcpy(sound_list[sound_list_size-1].alias, alias_command);
			if (esounds)
			{
				// esounds->PrecacheSound(sound_id, true);
			}

//			MMsg("Alias [%s] Sound File [%s]\n", alias_command, sound_id); 
		}

		filesystem->Close(file_handle);
	}

	SetupSoundAutoDownloads();

	// Reset list
	for (int i = 0; i < MANI_MAX_ACTION_SOUNDS; i++)
	{
		action_sound_list[i].in_use = false;
		Q_strcpy(action_sound_list[i].sound_file,"");
	}

	//Get action sound list
	snprintf(base_filename, sizeof (base_filename), "./cfg/%s/actionsoundlist.txt", mani_path.GetString());
	file_handle = filesystem->Open(base_filename, "rt", NULL);
	if (file_handle == NULL)
	{
//		MMsg("Failed to load actionsoundlist.txt\n");
	}
	else
	{
//		MMsg("Action Sound list\n");
		while (filesystem->ReadLine (sound_id, sizeof(sound_id), file_handle) != NULL)
		{
			if (!ParseAliasLine(sound_id, sound_name, true, false))
			{
				// String is empty after parsing
				continue;
			}

			bool found_id = false;

			for (int i = 0; i < MANI_MAX_ACTION_SOUNDS; i++)
			{
				if (FStrEq(sound_name, action_sound_list[i].alias))
				{
					char	exists_string[512];

					// Check file exists on server
					snprintf(exists_string, sizeof(exists_string), "./sound/%s", sound_id);
					if (filesystem->FileExists(exists_string))
					{
						Q_strcpy(action_sound_list[i].sound_file, sound_id);
						action_sound_list[i].in_use = true;
						found_id = true;
						if (esounds)
						{
							// esounds->PrecacheSound(sound_id, true);
						}
						break;
					}
				}
			}

			if (!found_id)
			{
//				MMsg("WARNING Action Sound Name [%s] for sound file [%s] is not valid !!\n",
//								sound_name,
//								sound_id);
			}
			else
			{
//				MMsg("Loaded Action Sound Name [%s] for file [%s]\n", 
//								sound_name,
//								sound_id);
			}
		}

		filesystem->Close(file_handle);
	}

	SetupActionAutoDownloads();
}
コード例 #11
0
//---------------------------------------------------------------------------------
// Purpose: Free the sounds used
//---------------------------------------------------------------------------------
void	FreeSounds(void)
{
	FreeList((void **) &sound_list, &sound_list_size);
}
コード例 #12
0
/**
 * Perform an action on a variable
 *
 * \param p_this The object that holds the variable
 * \param psz_name The name of the variable
 * \param i_action The action to perform. Must be one of \ref var_action
 * \param p_val First action parameter
 * \param p_val2 Second action parameter
 */
int __var_Change( vlc_object_t *p_this, const char *psz_name,
                  int i_action, vlc_value_t *p_val, vlc_value_t *p_val2 )
{
    int i_var, i;
    variable_t *p_var;
    vlc_value_t oldval;

    vlc_mutex_lock( &p_this->var_lock );

    i_var = Lookup( p_this->p_vars, p_this->i_vars, psz_name );

    if( i_var < 0 )
    {
        vlc_mutex_unlock( &p_this->var_lock );
        return VLC_ENOVAR;
    }

    p_var = &p_this->p_vars[i_var];

    switch( i_action )
    {
        case VLC_VAR_SETMIN:
            if( p_var->i_type & VLC_VAR_HASMIN )
            {
                p_var->pf_free( &p_var->min );
            }
            p_var->i_type |= VLC_VAR_HASMIN;
            p_var->min = *p_val;
            p_var->pf_dup( &p_var->min );
            CheckValue( p_var, &p_var->val );
            break;
        case VLC_VAR_SETMAX:
            if( p_var->i_type & VLC_VAR_HASMAX )
            {
                p_var->pf_free( &p_var->max );
            }
            p_var->i_type |= VLC_VAR_HASMAX;
            p_var->max = *p_val;
            p_var->pf_dup( &p_var->max );
            CheckValue( p_var, &p_var->val );
            break;
        case VLC_VAR_SETSTEP:
            if( p_var->i_type & VLC_VAR_HASSTEP )
            {
                p_var->pf_free( &p_var->step );
            }
            p_var->i_type |= VLC_VAR_HASSTEP;
            p_var->step = *p_val;
            p_var->pf_dup( &p_var->step );
            CheckValue( p_var, &p_var->val );
            break;
        case VLC_VAR_ADDCHOICE:
            /* FIXME: the list is sorted, dude. Use something cleverer. */
            for( i = p_var->choices.i_count ; i-- ; )
            {
                if( p_var->pf_cmp( p_var->choices.p_values[i], *p_val ) < 0 )
                {
                    break;
                }
            }

            /* The new place is i+1 */
            i++;

            if( p_var->i_default >= i )
            {
                p_var->i_default++;
            }

            INSERT_ELEM( p_var->choices.p_values, p_var->choices.i_count,
                         i, *p_val );
            INSERT_ELEM( p_var->choices_text.p_values,
                         p_var->choices_text.i_count, i, *p_val );
            p_var->pf_dup( &p_var->choices.p_values[i] );
            p_var->choices_text.p_values[i].psz_string =
                ( p_val2 && p_val2->psz_string ) ?
                strdup( p_val2->psz_string ) : NULL;

            CheckValue( p_var, &p_var->val );
            break;
        case VLC_VAR_DELCHOICE:
            /* FIXME: the list is sorted, dude. Use something cleverer. */
            for( i = 0 ; i < p_var->choices.i_count ; i++ )
            {
                if( p_var->pf_cmp( p_var->choices.p_values[i], *p_val ) == 0 )
                {
                    break;
                }
            }

            if( i == p_var->choices.i_count )
            {
                /* Not found */
                vlc_mutex_unlock( &p_this->var_lock );
                return VLC_EGENERIC;
            }

            if( p_var->i_default > i )
            {
                p_var->i_default--;
            }
            else if( p_var->i_default == i )
            {
                p_var->i_default = -1;
            }

            p_var->pf_free( &p_var->choices.p_values[i] );
            if( p_var->choices_text.p_values[i].psz_string )
                free( p_var->choices_text.p_values[i].psz_string );
            REMOVE_ELEM( p_var->choices.p_values, p_var->choices.i_count, i );
            REMOVE_ELEM( p_var->choices_text.p_values,
                         p_var->choices_text.i_count, i );

            CheckValue( p_var, &p_var->val );
            break;
        case VLC_VAR_CHOICESCOUNT:
            p_val->i_int = p_var->choices.i_count;
            break;
        case VLC_VAR_CLEARCHOICES:
            for( i = 0 ; i < p_var->choices.i_count ; i++ )
            {
                p_var->pf_free( &p_var->choices.p_values[i] );
            }
            for( i = 0 ; i < p_var->choices_text.i_count ; i++ )
            {
                if( p_var->choices_text.p_values[i].psz_string )
                    free( p_var->choices_text.p_values[i].psz_string );
            }
            if( p_var->choices.i_count ) free( p_var->choices.p_values );
            if( p_var->choices_text.i_count ) free( p_var->choices_text.p_values );

            p_var->choices.i_count = 0;
            p_var->choices.p_values = NULL;
            p_var->choices_text.i_count = 0;
            p_var->choices_text.p_values = NULL;
            p_var->i_default = -1;
            break;
        case VLC_VAR_SETDEFAULT:
            /* FIXME: the list is sorted, dude. Use something cleverer. */
            for( i = 0 ; i < p_var->choices.i_count ; i++ )
            {
                if( p_var->pf_cmp( p_var->choices.p_values[i], *p_val ) == 0 )
                {
                    break;
                }
            }

            if( i == p_var->choices.i_count )
            {
                /* Not found */
                break;
            }

            p_var->i_default = i;
            CheckValue( p_var, &p_var->val );
            break;
        case VLC_VAR_SETVALUE:
            /* Duplicate data if needed */
            p_var->pf_dup( p_val );
            /* Backup needed stuff */
            oldval = p_var->val;
            /* Check boundaries and list */
            CheckValue( p_var, p_val );
            /* Set the variable */
            p_var->val = *p_val;
            /* Free data if needed */
            p_var->pf_free( &oldval );
            break;
        case VLC_VAR_GETCHOICES:
        case VLC_VAR_GETLIST:
            p_val->p_list = malloc( sizeof(vlc_list_t) );
            if( p_val2 ) p_val2->p_list = malloc( sizeof(vlc_list_t) );
            if( p_var->choices.i_count )
            {
                p_val->p_list->p_values = malloc( p_var->choices.i_count
                                                  * sizeof(vlc_value_t) );
                p_val->p_list->pi_types = malloc( p_var->choices.i_count
                                                  * sizeof(int) );
                if( p_val2 )
                {
                    p_val2->p_list->p_values =
                        malloc( p_var->choices.i_count * sizeof(vlc_value_t) );
                    p_val2->p_list->pi_types =
                        malloc( p_var->choices.i_count * sizeof(int) );
                }
            }
            p_val->p_list->i_count = p_var->choices.i_count;
            if( p_val2 ) p_val2->p_list->i_count = p_var->choices.i_count;
            for( i = 0 ; i < p_var->choices.i_count ; i++ )
            {
                p_val->p_list->p_values[i] = p_var->choices.p_values[i];
                p_val->p_list->pi_types[i] = p_var->i_type;
                p_var->pf_dup( &p_val->p_list->p_values[i] );
                if( p_val2 )
                {
                    p_val2->p_list->p_values[i].psz_string =
                        p_var->choices_text.p_values[i].psz_string ?
                    strdup(p_var->choices_text.p_values[i].psz_string) : NULL;
                    p_val2->p_list->pi_types[i] = VLC_VAR_STRING;
                }
            }
            break;
        case VLC_VAR_FREELIST:
            FreeList( p_val );
            if( p_val2 && p_val2->p_list )
            {
                for( i = 0; i < p_val2->p_list->i_count; i++ )
                    if( p_val2->p_list->p_values[i].psz_string )
                        free( p_val2->p_list->p_values[i].psz_string );
                if( p_val2->p_list->i_count )
                {
                    free( p_val2->p_list->p_values );
                    free( p_val2->p_list->pi_types );
                }
                free( p_val2->p_list );
            }
            break;
        case VLC_VAR_SETTEXT:
            if( p_var->psz_text ) free( p_var->psz_text );
            if( p_val && p_val->psz_string )
                p_var->psz_text = strdup( p_val->psz_string );
            break;
        case VLC_VAR_GETTEXT:
            p_val->psz_string = NULL;
            if( p_var->psz_text )
            {
                p_val->psz_string = strdup( p_var->psz_text );
            }
            break;
        case VLC_VAR_INHERITVALUE:
            {
                vlc_value_t val;

                if( InheritValue( p_this, psz_name, &val, p_var->i_type )
                    == VLC_SUCCESS )
                {
                    /* Duplicate already done */

                    /* Backup needed stuff */
                    oldval = p_var->val;
                    /* Check boundaries and list */
                    CheckValue( p_var, &val );
                    /* Set the variable */
                    p_var->val = val;
                    /* Free data if needed */
                    p_var->pf_free( &oldval );
                }

                if( p_val )
                {
                    *p_val = p_var->val;
                    p_var->pf_dup( p_val );
                }
            }
            break;
        case VLC_VAR_TRIGGER_CALLBACKS:
            {
                /* Deal with callbacks. Tell we're in a callback, release the lock,
                 * call stored functions, retake the lock. */
                if( p_var->i_entries )
                {
                    int i_var;
                    int i_entries = p_var->i_entries;
                    callback_entry_t *p_entries = p_var->p_entries;

                    p_var->b_incallback = VLC_TRUE;
                    vlc_mutex_unlock( &p_this->var_lock );

                    /* The real calls */
                    for( ; i_entries-- ; )
                    {
                        p_entries[i_entries].pf_callback( p_this, psz_name, p_var->val, p_var->val,
                                                          p_entries[i_entries].p_data );
                    }

                    vlc_mutex_lock( &p_this->var_lock );

                    i_var = Lookup( p_this->p_vars, p_this->i_vars, psz_name );
                    if( i_var < 0 )
                    {
                        msg_Err( p_this, "variable %s has disappeared", psz_name );
                        vlc_mutex_unlock( &p_this->var_lock );
                        return VLC_ENOVAR;
                    }

                    p_var = &p_this->p_vars[i_var];
                    p_var->b_incallback = VLC_FALSE;
                }
            }
            break;

        default:
            break;
    }

    vlc_mutex_unlock( &p_this->var_lock );

    return VLC_SUCCESS;
}
コード例 #13
0
ファイル: drain.c プロジェクト: gaoshuai/pcraster
/* Determines all lowest neighbors and gives them output.
 * All lowest neighbors from current cell are put at the beginning of 
 * the list (depth-first) and the stream is added to their output value.
 * Returns list if successful, NULL when memory allocation failed.
 */
static NODE *DoNeighbors(MAP_REAL8 *out,          /* read-write output map */
                         NODE *list,              /* read-write list   */
                         const MAP_REAL8 *dem,    /* dem map */
                         const MAP_REAL8 *points, /* points map */
                         int r,                   /* current cell row */
                         int c,                   /* current cell column */
                         REAL8 drainVal)          /* value to drain down */
{
    NODE *list2 = NULL;                   /* list of lowest neighbors */
    REAL8 dropMax = 0;                    /* maximal drop value */
    REAL8 dropVal = 0;                    /* maximal drop value */
    int i, nrPaths = 0;                   /* nr of outgoing paths */
    REAL8 demVal, newDem, outVal, pntVal; /* dem value
                                           * and output value of old and new cell and the
                                           * point value of both to check on MV.
                                           */

    PRECOND(dem->GetGetTest(dem) == GET_MV_TEST);
    PRECOND(points->GetGetTest(points) == GET_MV_TEST);
    PRECOND(out->GetGetTest(out) == GET_MV_TEST);
    PRECOND(dem->Get(&demVal, r, c, dem));
    PRECOND(out->Get(&outVal, r, c, out));

    dem->Get(&demVal, r, c, dem); /* height original cell */
    out->Get(&outVal, r, c, out); /* output original cell */

    for (i = 1; i <= NR_LDD_DIR; i++) { /* check all neighbors */
        int rNext = RNeighbor(r, i);
        int cNext = CNeighbor(c, i);

        if (dem->Get(&newDem, rNext, cNext, dem) &&       /* no MV */
            points->Get(&pntVal, rNext, cNext, points) && /* no MV */
            (i != LDD_PIT) &&                             /* skip cell itself */
            (0 < (demVal - newDem)))                      /* lower than current cell */
        {
            REAL8 dist = (Corner(i) == FALSE) SCALE;

            dropVal = (demVal - newDem) / dist;
            if (dropMax <= dropVal) {
                NODE *tmp;
                if (dropMax < dropVal) {
                    /* all previous found neighbors
                     * were not the lowest -> reset.
                     */
                    list2 = FreeList(list2);
                    POSTCOND(list2 == NULL);
                    nrPaths = 0;
                    dropMax = dropVal;
                }
                nrPaths++;
                tmp = LinkToList(list2, rNext, cNext);
                if (tmp == NULL) {
                    FreeList(list2);
                    FreeList(list);
                    return NULL;
                }
                list2 = tmp;
            }
        }
    }
    drainVal /= nrPaths; /* divide between steepest paths */
    while (list2 != NULL) {
        PRECOND(out->Get(&outVal, list2->rowNr, list2->colNr, out));
        out->Get(&outVal, list2->rowNr, list2->colNr, out);
        outVal += drainVal;
        out->Put(outVal, list2->rowNr, list2->colNr, out);
        list = LinkChkReal(list, list2->rowNr, list2->colNr, drainVal);
        if (list == NULL) {
            FreeList(list2);
            return NULL;
        }
        list2 = RemFromList(list2);
    }
    POSTCOND(list != NULL); /* result HasLowerNeighbor was TRUE */
    return list;
}
コード例 #14
0
ファイル: drain.c プロジェクト: gaoshuai/pcraster
/* Determines for each nonzero point its steepest downhill path.
 * Assumes a spatial REAL8 points map and a spatial REAL8 dem map
 * present. If a cell has a MV in one of these maps,
 * it will get a MV in the output map also.
 * The amount that drains down is determined by the points map.
 * Returns 0 if termination is successful, 1 otherwise.
 */
int Drain(MAP_REAL8 *out,          /* write-only output map  */
          const MAP_REAL8 *dem,    /* dem map */
          const MAP_REAL8 *points) /* points map */
{
    REAL8 pointVal, demVal;
    NODE *pointlist = NULL;
    int r, c, nrRows, nrCols, nrPnts = 0;

    AppProgress("\nnumber of points to do:\n");

    nrRows = dem->NrRows(dem);
    nrCols = dem->NrCols(dem);

    PRECOND(nrRows == points->NrRows(points));
    PRECOND(nrCols == points->NrCols(points));

    /* Fill outBuf with 0, this is the initial value */
    for (r = 0; r < nrRows; r++)
        for (c = 0; c < nrCols; c++)
            out->Put((REAL8)0, r, c, out);

    /* algorithm wants dem->Get() and points->Get() to
     * return FALSE if a value is a missing value
     */
    dem->SetGetTest(GET_MV_TEST, dem);
    points->SetGetTest(GET_MV_TEST, points);
    out->SetGetTest(GET_MV_TEST, out);

    /* For every true point in the points map, put point in list and
     * put point value in output map. The latter is necessary when a
     * defined point streams into another defined point.
     */
    for (r = 0; r < nrRows; r++)
        for (c = 0; c < nrCols; c++) {
            if (dem->Get(&demVal, r, c, dem) && points->Get(&pointVal, r, c, points)) {
                if (pointVal != 0) {
                    NODE *tmp;
                    out->Put(pointVal, r, c, out);
                    tmp = LinkToList(pointlist, r, c);
                    if (tmp == NULL) {
                        FreeList(pointlist);
                        return 1;
                    }
                    pointlist = tmp;
                    nrPnts++;
                }
            } else
                out->PutMV(r, c, out);
        }

    /* For every true point in the points map do the function */
    while (pointlist != NULL) {
        r = pointlist->rowNr;
        c = pointlist->colNr;
        if (DoDrain(out, dem, points, r, c)) {
            FreeList(pointlist);
            return 1;
        }
        pointlist = RemFromList(pointlist);
        nrPnts--;
        AppProgress("\r%d                   ", nrPnts);
    }
    AppEndRowProgress();
    return 0; /* successful terminated */
}
コード例 #15
0
ファイル: ahi.c プロジェクト: BackupTheBerlios/arp2-svn
int main(int argc, char **argv) {
  struct RDArgs *rdargs = NULL;
  int i;
  char pubscreen[32];

  if(argc) {
    rdargs=ReadArgs( TEMPLATE , (LONG *) &args, NULL);
    SaveIcons  = FALSE;
  }
  else {
    struct WBStartup *WBenchMsg = (struct WBStartup *)argv;
    struct WBArg *wbarg;
    BPTR olddir;
    struct DiskObject *dobj;
    STRPTR* toolarray;
    UBYTE *s;

    SaveIcons  = TRUE;

    for(i=0, wbarg=WBenchMsg->sm_ArgList;
      i < WBenchMsg->sm_NumArgs;
      i++, wbarg++) {

      olddir = (BPTR) -1;
      if((wbarg->wa_Lock)&&(*wbarg->wa_Name))
          olddir = CurrentDir(wbarg->wa_Lock);


      if((*wbarg->wa_Name) && (dobj=GetDiskObject(wbarg->wa_Name))) {
        toolarray = dobj->do_ToolTypes;

        s = FindToolType(toolarray,"CREATEICONS");

        if( s != NULL ) {
          if( MatchToolValue(s,"NO") ||
              MatchToolValue(s,"FALSE")) {
            SaveIcons = FALSE;
          }
        }

        s = (char *) FindToolType(toolarray,"PUBSCREEN");

        if( s != NULL ) {
          strncpy(pubscreen, s, sizeof pubscreen);
          args.pubscreen = pubscreen;
        }

        s = (char *) FindToolType(toolarray,"ACTION");

        if( s != NULL ) {
          if(MatchToolValue(s,"EDIT")) {
            args.edit = TRUE;
          }
          else if(MatchToolValue(s,"USE")) {
            args.use = TRUE;
          }
          else if(MatchToolValue(s,"SAVE")) {
            args.save = TRUE;
          }
        }

        FreeDiskObject(dobj);
      }

      if((i>0)&&(*wbarg->wa_Name)) {
        args.from = wbarg->wa_Name;
      }

      if(olddir != (BPTR) -1) {
        CurrentDir(olddir); /* CD back where we were */
      }
    }
  
  }

  if(args.from == NULL) {
    args.from = ENVFILE;
  }

  if(args.edit) {
    args.use  = FALSE;
    args.save = FALSE;
  }

  if((SetSignal(0L,SIGBREAKF_CTRL_C) & SIGBREAKF_CTRL_C) == 0) {
    if(Initialize()) {

      NewSettings(args.from);

      if((!args.use && !args.save) || args.edit) {
        if(BuildGUI(args.pubscreen)) {
          EventLoop();
        }
        CloseGUI();
      }

      if(args.use || args.save) {
        SaveSettings(ENVFILE, UnitList);
      }

      if(args.save) {
        SaveSettings(ENVARCFILE, UnitList);
      }
    }
  }

  if(rdargs) {
    FreeArgs(rdargs);
  }

  FreeVec(Units);
  FreeVec(Modes);
  FreeVec(Outputs);
  FreeVec(Inputs);
  FreeList(ModeList);
  FreeList(UnitList);

  CleanUp();

  return 0;
}
コード例 #16
0
int	cmdRemovePath(	ClientData	 client_data,
	       		Tcl_Interp	*interp,
	       		int		 argc,
	       		CONST84 char	*argv[])
{
    char	 *sw_marker = APP_SW_MARKER,	/** arbitrary default	     **/
		**pathlist;			/** List of dirs	     **/
    const char	 *delim = _colon;		/** path delimiter	     **/
    int		  numpaths,			/** number of dirs in path   **/
		  arg1 = 1,			/** arg start		     **/
		  x;				/** loop index		     **/


#if WITH_DEBUGGING_CALLBACK
    ErrorLogger( NO_ERR_START, LOC, _proc_cmdRemovePath, NULL);
#endif

    /**
     **   Check arguments. There should be give 3 args:
     **     argv[0]  -  prepend/append/remove-path
     **     ...
     **     argv[n-1]-  varname
     **     argv[n]  -  value
     **/
    if(argc < 3)
	if( OK != ErrorLogger(ERR_USAGE,LOC,argv[0],"path-variable directory",
	    NULL))
	    goto unwind0;


    /**
     **  Non-persist mode?
     **/

    if (g_flags & M_NONPERSIST) {
	return (TCL_OK);
    }

    /**
     **  Display only ... ok, let's do so!
     **/
    if(g_flags & M_DISPLAY) {
	fprintf( stderr, "%s\t ", argv[ 0]);
	while( --argc)
	    fprintf( stderr, "%s ", *++argv);
	fprintf( stderr, "\n");
        goto success0;
    }

    /**
     **  prepend or append. The default is append.
     **/
    if( ! strncmp( argv[0], "pre", 3))
	sw_marker = PRE_SW_MARKER;

    /**
     **  Check for the delimiter option
     **/
    if(*(argv[arg1]) == '-') {
	if (!strcmp(argv[arg1], "-d")) {
		delim = argv[arg1+1];
		arg1 += 2;
	} else if (!strcmp(argv[arg1], "--delim")) {
		delim = argv[arg1+1];
		arg1 += 2;
	} else if (!strncmp(argv[arg1], "--delim=", 8)) {
		delim = argv[arg1]+8;
		arg1++;
	}
    }

    /**
     ** For switch state3, we're looking to remove the markers.
     **/
    if( g_flags & M_SWSTATE3)
	argv[arg1+1] = sw_marker;

    /**
     **  Split the path into its components so each item can be removed
     **  individually from the variable.
     **/
    if( !( pathlist = SplitIntoList( interp, (char *) argv[arg1+1], &numpaths,
	delim)))
	goto unwind0;

    /**
     ** Remove each item individually
     **/
    for( x = 0; x < numpaths; x++)
	if(TCL_OK != Remove_Path(interp,(char *) argv[arg1],pathlist[x],
	sw_marker, delim))
	    goto unwind1;

#if WITH_DEBUGGING_CALLBACK
    ErrorLogger( NO_ERR_END, LOC, _proc_cmdRemovePath, NULL);
#endif

    /**
     ** Free resources
     **/
    FreeList(pathlist, numpaths);

success0:
    return( TCL_OK);			/** -------- EXIT (SUCCESS) -------> **/

unwind1:
    FreeList(pathlist, numpaths);
unwind0:
    return( TCL_ERROR);			/** -------- EXIT (FAILURE) -------> **/

} /** End of 'cmdRemovePath' **/
コード例 #17
0
ファイル: ui_demos.c プロジェクト: Bad-ptr/q2pro
static void Pop( menuFrameWork_t *self ) {
    // save previous position
    m_demos.selection = m_demos.list.curvalue;
    FreeList();
}
コード例 #18
0
ファイル: TapeEventQueue.cpp プロジェクト: TomHarte/ElectrEm
void TapeEventQueue::SeedEventList(Uint64 StartTime)
{
	FreeList(Head);
	Start = End = StartTime;
}
コード例 #19
0
ファイル: query.c プロジェクト: cjunmokim/Search-Engine
int main (int argc, char *argv[]) {
	
	// Check arguments
	
	// Check that there are two arguments passed.
	if (argc != 3) {
		printf("Please input exactly two arguments.\n");
		printf("Usage: ./query [INDEX_FILE] [HTML_DIRECTORY]\n");
		return 1;
	}
	
	// Check that the index file exists.
	if (!IsFile(argv[1])) {
		printf("Please input an existing [INDEX_FILE].\n");
		return 1;
	} 
	
	// Since the index file is valid, copy file name to file.
	file = calloc(1, strlen(argv[1]) + 1);
	strcpy(file, argv[1]);
	
	// Check that the html directory exists.
	if (!IsDir(argv[2])) {
		printf("Please input an existing [HTML_DIRECTORY].\n");
		return 1;
	}
	
	// Since the directory is valid, copy path to dir_path.
	dir_path = calloc(1, strlen(argv[2]) + 1);
	strcpy(dir_path, argv[2]);

	
	// Declare variables.
	HashTable Index;
	HashTable *ptr;
	char *query;
	
	// Load and recreate an InvertedIndex from index file.
	InitializeHashTable(&Index);
	ptr = ReadFile(file, &Index);
	
	printf("Query:> ");
	
	// Receive user queries from input.
	while ((query = (char *)calloc(1, MAX)) && fgets(query, MAX, stdin)) {
		
		// Check query line.
		
		// If the query line is empty, ask for input again.
		if (strcmp(query, "\n") == 0) {
			printf("Please input words.\n\n");
			printf("Query:> ");
			free(query);
			continue;
		}
		
		// Check that only ASCII characters, or whitespace in between is passed.
		int i;
		for (i=0; i<strlen(query); i++) {
			if (!isalpha(query[i]) && !isspace(query[i])) {
				break;				
			}
		}
		if (i != strlen(query)) {
			printf("Please input only ASCII characters, whitespace, or logical operators.\n\n");
			printf("Query:> ");
			free(query);
			continue;
		}
		
		// Check that at least one word is passed, ie the query is not just whitespace.
		for (i=0; i<strlen(query); i++) {
			if (!isspace(query[i])) {
				break;
			}
		}
		if (i == strlen(query)) {
			printf("Please input only ASCII characters, whitespace, or logical operators.\n\n");
			printf("Query:> ");
			free(query);
			continue;
		}
		
		// Check that no two successive logical operators are passed.
		if (strstr(query, "AND OR") || strstr(query, "AND AND") || strstr(query, "OR AND") || strstr(query, "OR OR")) {
			printf("Please input a valid query line.\n\n");
			printf("Query:> ");
			free(query);
			continue;
		}
		
		
		// Get the list of DocumentNodes containing the query.
		if (!GetLinks(query, ptr)) {
			printf("Please input a valid query line.\n\n");
			printf("Query:> ");
			
			// Cleanup.
			free(query);
			FreeList(0);
			FreeList(1);
			
			continue;
		}
		
		// Sort only if there are two are more documents in the list.
		if (final_list != NULL && final_list->next != NULL) {
			Sort(); // Sort by rank.
		}
		
		
		// Display results to stdout.
		if (!Display()) {
			printf("Error retrieving url from directory. Please check HTML_DIRECTORY.\n\n");
			// Cleanup.
			FreeList(0);
			FreeList(1);
			break;
		}
		printf("\n\n");
		printf("Query:> ");
		
		// Cleanup.
		FreeList(1);
		free(query);
	}
	
	// Cleanup.
	free(query);
	CleanHashTable(ptr);
	FreeHashTable(ptr);
	free(file);
	free(dir_path);
	
	return 0;
}
コード例 #20
0
//---------------------------------------------------------------------------------
// Purpose: Plugin un-loaded
//---------------------------------------------------------------------------------
void	ManiAutoMap::Unload(void)
{
	set_next_map = false;
	FreeList((void **) &automap_list, &automap_list_size);
}
コード例 #21
0
//---------------------------------------------------------------------------------
// Purpose: Builds up a list of players that are 'kickable'
//---------------------------------------------------------------------------------
void ManiReservedSlot::BuildPlayerKickList( player_t *player_ptr, int *players_on_server )
{
	player_t	temp_player;
	active_player_t active_player;

	FreeList((void **) &active_player_list, &active_player_list_size);

	for (int i = 1; i <= max_players; i ++)
	{
#if defined ( GAME_CSGO )
		edict_t *pEntity = PEntityOfEntIndex(i);
#else
		edict_t *pEntity = engine->PEntityOfEntIndex(i);
#endif
		if( pEntity && !pEntity->IsFree())
		{
			if ( player_ptr && ( pEntity == player_ptr->entity ) )
				continue;

			IPlayerInfo *playerinfo = playerinfomanager->GetPlayerInfo( pEntity );
			if (playerinfo && playerinfo->IsConnected())
			{
				Q_strcpy(active_player.steam_id, playerinfo->GetNetworkIDString());
				if (FStrEq("BOT", active_player.steam_id))
				{
					continue;
				}

				INetChannelInfo *nci = engine->GetPlayerNetInfo(i);
				if (!nci)
				{
					continue;
				}

				active_player.entity = pEntity;

				active_player.ping = nci->GetAvgLatency(0);
				const char * szCmdRate = engine->GetClientConVarValue( i, "cl_cmdrate" );
				int nCmdRate = (20 > Q_atoi( szCmdRate )) ? 20 : Q_atoi(szCmdRate);
				active_player.ping -= (0.5f/nCmdRate) + TICKS_TO_TIME( 1.0f ); // correct latency

				// in GoldSrc we had a different, not fixed tickrate. so we have to adjust
				// Source pings by half a tick to match the old GoldSrc pings.
				active_player.ping -= TICKS_TO_TIME( 0.5f );
				active_player.ping = active_player.ping * 1000.0f; // as msecs
				active_player.ping = ((5 > active_player.ping) ? 5:active_player.ping); // set bounds, dont show pings under 5 msecs

				active_player.time_connected = nci->GetTimeConnected();
				Q_strcpy(active_player.ip_address, nci->GetAddress());
				if (gpManiGameType->IsSpectatorAllowed() &&
					playerinfo->GetTeamIndex () == gpManiGameType->GetSpectatorIndex())
				{
					active_player.is_spectator = true;
				}
				else
				{
					active_player.is_spectator = false;
				}
				active_player.user_id = playerinfo->GetUserID();
				Q_strcpy(active_player.name, playerinfo->GetName());

				if ( players_on_server )
					*players_on_server = *players_on_server + 1;

				active_player.kills = playerinfo->GetFragCount();
				active_player.deaths = playerinfo->GetDeathCount();
				Q_strcpy(temp_player.steam_id, active_player.steam_id);
				Q_strcpy(temp_player.ip_address, active_player.ip_address);
				Q_strcpy(temp_player.name, active_player.name);
				temp_player.is_bot = false;

				if (IsPlayerInReserveList(&temp_player))
				{
					continue;
				}

				active_player.index = i;

				if (mani_reserve_slots_include_admin.GetInt() == 1 &&
					gpManiClient->HasAccess(active_player.index, ADMIN, ADMIN_BASIC_ADMIN))
				{
					continue;
				}

				if (gpManiClient->HasAccess(active_player.index, IMMUNITY, IMMUNITY_RESERVE))
				{
					continue;
				}

				AddToList((void **) &active_player_list, sizeof(active_player_t), &active_player_list_size);
				active_player_list[active_player_list_size - 1] = active_player;
			}
		}
	}
}
コード例 #22
0
ManiAutoMap::~ManiAutoMap()
{
	// Cleanup
	FreeList((void **) &automap_list, &automap_list_size);
}
コード例 #23
0
ファイル: main.c プロジェクト: wtsi-hgi/modules
int main(
	int argc,
	char *argv[],
	char *environ[]
) {

	Tcl_Interp     *interp;
	int             return_val = 0;
	char           *rc_name;
	char           *rc_path;
	Tcl_Obj       **objv;		/** Tcl Object vector **/
	int             objc;		/** Tcl Object vector count **/

#ifdef HAVE_SETLOCALE
	/* set local via LC_ALL */
	setlocale(LC_ALL, "");
#endif

#if ENABLE_NLS
	/* the text message domain. */
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);
#endif
    /**
     ** check if first argument is --version or -V then output the
     ** version to stdout.  This is a special circumstance handled
     ** by the regular options.
     **/
	if (argc > 1 && *argv[1] == '-') {
		if (!strcmp("-V", argv[1]) || !strcmp("--version", argv[1])) {
			version(stdout);
			return 0;
		}
	}
    /**
     **  Initialization. 
     **/
	if (!(ModulePathVec = ModulePathList())) {
		ModulePath = NULL;
		/* goto unwind0; */
	} else {
		ModulePath = uvec_vector(ModulePathVec);
	}

    /**
     **  Check the command line syntax. There will be no return from the
     **  initialization function in case of invalid command line arguments.
     **/
	if (TCL_OK != Initialize_Module(&interp, argc, argv, environ))
		goto unwind1;

	if (TCL_OK != Setup_Environment(interp))
		goto unwind1;

    /**
     **  Check for command line switches
     **/
	if (TCL_OK != Check_Switches(&argc, argv))
		goto unwind1;
    /**
     **  Figure out, which global RC file to use. This depends on the environ-
     **  ment variable 'MODULERCFILE', which can be set to one of the following:
     **
     **		<filename>	-->	SYSCONFDIR/<filename>
     **		<dir>/		-->	<dir>/RC_FILE
     **		<dir>/<file>	-->	<dir>/<file>
     **  Use xgetenv to expand 1 level of env.vars.
     **/
	if ((rc_name = xgetenv("MODULERCFILE"))) {
		/* found something in MODULERCFILE */
		if (!(rc_path = stringer(NULL, 0, rc_name, NULL))) {
			if (OK != ErrorLogger(ERR_STRING, LOC, NULL))
				goto unwind2;
			else
				null_free((void *)&rc_name);
		} else {
			null_free((void *)&rc_name);
			if (!(rc_name = strrchr(rc_path, *psep))) {
				rc_name = rc_path;
				rc_path = etcpath;
			} else
				*rc_name++ = '\0';
			if (!*rc_name) {
				rc_name = rc_file;
			}
		}
	} else {
		rc_path = stringer(NULL,0, etcpath, NULL);
		null_free((void *)&rc_name);
		rc_name = rc_file;
	}
    /**
     **  Source the global and the user defined RC file
     **/
	g_current_module = (char *)NULL;

	if (TCL_ERROR == SourceRC(interp, rc_path, rc_name, Mod_Load) ||
	    TCL_ERROR == SourceRC(interp,getenv("HOME"),modulerc_file,Mod_Load))
		exit(1);

	if (rc_path)
		null_free((void *)&rc_path);
    /**
     **  Invocation of the module command as specified in the command line
     **/
	g_flags = 0;
	Tcl_ArgvToObjv(&objc, &objv, argc - 1, argv + 1);
	return_val = cmdModule((ClientData) 0, interp, objc, objv);
    /**
     **  If we were doing some operation that has already flushed its output,
     **  then we don't need to re-flush the output here.
     **
     **  Also, if we've had an error here, then the whole modulecmd failed
     **  and not just the values for a single modulefile.  So, we'll pass in
     **  a NULL here to indicate that any error message should say that
     **  absolutely NO changes were made to the environment.
     **/
	if (TCL_OK == return_val) {
		Output_Modulefile_Changes(interp);
#ifdef HAS_X11LIBS
		xresourceFinish(1);
#endif
	} else {
		Unwind_Modulefile_Changes(interp, NULL);
#ifdef HAS_X11LIBS
		xresourceFinish(0);
#endif
	}
    /**
     **  Finally clean up. Delete the required hash tables and conditionally
     **  allocated areas.
     **/
	Global_Hash_Tables(GHashDelete, NULL);

	if (line)
		null_free((void *)&line);
	if (error_line)
		null_free((void *)&error_line);
    /**
     **  This return value may be evaluated by the calling shell
     **/
	OutputExit();
	return (return_val ? return_val : g_retval);

/* unwind3:
    null_free((void *) &rc_path); */
unwind2:
	null_free((void *)&rc_name);
unwind1:
	FreeList(&ModulePathVec);
unwind0:
	/* and error occurred of some type */
	g_retval = (g_retval ? g_retval : 1);
	OutputExit();
	return (g_retval);

} /** End of 'main' **/
コード例 #24
0
ファイル: build.c プロジェクト: glycoinfo/eurocarbdb
/* This function copies the structural information of sim to exp. It does not
   copy chemical shifts etc. */
int BU_CopyStructure(struct BU_Struct *exp, struct BU_Struct *sim)
{
  int i, pos, identical=1;
  struct BU_Unit *unit, *eunit;
  /* check that original does exist */
  if (sim->Units.Head.Succ==&sim->Units.Tail)
    Error(PA_ERR_FAIL, "'Simulated' spectrum has no structure");

  if(ListLen(&sim->Units)==ListLen(&exp->Units))
    {
      for(unit=(struct BU_Unit *)sim->Units.Head.Succ,
	    eunit=(struct BU_Unit *)exp->Units.Head.Succ;
	  unit->Node.Succ!=NULL && eunit->Node.Succ!=NULL;
	  unit=(struct BU_Unit *)unit->Node.Succ,
	    eunit=(struct BU_Unit *)eunit->Node.Succ)
	{
	  /* Check that the residues are the same and that they bind to the same
	     position in the next residue. */
	  if(unit->Residue!=eunit->Residue ||
	     unit->Position!=eunit->Position)
	    {
	      identical=0;
	      break;
	    }
	  /* Check the bonds */
	  for(i=0;i<TY_MAX_BONDS;i++)
	    {
	      if(unit->Subst[i]!=0 && eunit->Subst[i]!=0)
		{
		  /* Just compare the names of the substituents since they are just
		     copies (if they are the same) - they are not identical */
		  if(strcmp(unit->Subst[i]->Node.Name,eunit->Subst[i]->Node.Name)!=0)
		    {
		      identical=0;
		      break;
		    }
		}
	      else if((unit->Subst[i]==0 && eunit->Subst[i]!=0) ||
		      (unit->Subst[i]!=0 && eunit->Subst[i]==0))
		{
		  identical=0;
		  break;
		}
	    }
	}
    }
  else
    {
      identical=0;
    }
  if(identical==1)
    {
      return(PA_ERR_OK);
    }

  /* clear experimental structure */
  FreeList(&exp->Units);

  for(i=0;i<3;i++)
    {
      exp->JHH[i]=sim->JHH[i];
      exp->JCH[i]=sim->JCH[i];
    }

  for (unit=(struct BU_Unit *)sim->Units.Head.Succ; unit->Node.Succ!=NULL;
       unit=(struct BU_Unit *)unit->Node.Succ)
    {
      eunit=ME_CreateNode(&UnitMethod, &(exp->Units), unit->Node.Name);
      if (eunit==NULL) Error(PA_ERR_FATAL, "Out of memory");
      eunit->Residue = unit->Residue;
      eunit->Shifts.Type = unit->Shifts.Type;
      for(i=0;i<TY_MAX_CARBON;i++)
	{
	  eunit->Shifts.C[i]=BU_VOID_SHIFT;
	  eunit->Shifts.H[i][0]=BU_VOID_SHIFT;
	  eunit->Shifts.H[i][1]=BU_VOID_SHIFT;
	}
      eunit->CcpnUnitNr = unit->CcpnUnitNr;
    }  

  /* copy linking info */
  for (unit=(struct BU_Unit*)sim->Units.Head.Succ; unit->Node.Succ!=NULL;
       unit=(struct BU_Unit *)unit->Node.Succ)
    {
      eunit=(struct BU_Unit *)FindNode(&(exp->Units.Head), unit->Node.Name);
      eunit->Position=unit->Position;	/* copy position info */
      for (pos=0; pos<TY_MAX_HEAVY; pos++)	/* copy every 'substituent' */
	{
	  if (unit->Subst[pos]==NULL) continue;
	  eunit->Subst[pos]=(struct BU_Unit*)
	    FindNode(&(exp->Units.Head),unit->Subst[pos]->Node.Name);
	}
    }
  return(PA_ERR_OK);
}
コード例 #25
0
int Locate_ModuleFile(	Tcl_Interp	*interp,
                  	char		*modulename,
                  	char		*realname,
                  	char		*filename)
{
    char	*p;			/** Tokenization pointer	     **/
    char	*result = NULL;		/** This functions result	     **/
    char	**pathlist;		/** List of paths to scan	     **/
    int		  numpaths,		/** Size of this list		     **/
    		  i;			/** Loop counter		     **/
    char	*modulespath;		/** Buffer for the contents of the   **/
					/** environment variable MODULEPATH  **/
    char	*mod, *vers;		/** Module and version name for sym- **/
					/** bolic name lookup		     **/
    /**
     **  If it is a full path name, that's the module file to load.
     **/
#if WITH_DEBUGGING_LOCATE
    ErrorLogger( NO_ERR_START, LOC, _proc_Locate_ModuleFile, "modulename = '",
	modulename, "'", NULL);
#endif

    if( !modulename)
	if( OK != ErrorLogger( ERR_PARAM, LOC, "modulename", NULL))
	    goto unwind0;

    if( modulename[0] == '/' || modulename[0] == '.') {

	p = (char*) strrchr( modulename, '/');
        if(p) {
            *p = '\0';
	    /**
	     **  Check, if what has been specified is a valid version of
	     **  the specified module ...
	     **/
            if((char *) NULL ==
		(result = GetModuleName(interp, modulename, NULL,(p+1))))
		goto unwind0;
	    /**
	     **  Reinstall the 'modulefile' which has been corrupted by
	     **   tokenization
	     **/
	    *p = '/';
	    /**
	     **  Reinstall the 'modulefile' which has been corrupted by
	     **  tokenization
	     **/
	    *p = '/';

	    /**
	     **  ... Looks good! Conditionally (if there has been no version
	     **  specified) we have to add the default version
	     **/
            if( !strcmp((p + 1), result)) {
                if ((char *) NULL == stringer( filename, MOD_BUFSIZE,
		modulename, NULL))
		    goto unwind1;
            } else {
                if ((char *) NULL == stringer( filename, MOD_BUFSIZE,
		modulename,"/",result, NULL))
		    goto unwind1;
            }
        } else {
	    /**
	     **  Hmm! There's no backslash in 'modulename'. So it MUST begin
	     **  on '.' and MUST be part of the current directory
	     **/
            if( NULL == (result = GetModuleName( interp, modulename, NULL,
		modulename)))
		goto unwind0;

            if( !strcmp( modulename, result) ||
		(strlen( modulename) + 1 + strlen( result) + 1 > MOD_BUFSIZE)) {
                if ((char *) NULL == stringer( filename, MOD_BUFSIZE,
		modulename, NULL))
		    goto unwind1;
            } else {
                if ((char *) NULL == stringer( filename, MOD_BUFSIZE,
		modulename,"/",result, NULL))
		    goto unwind1;
            }
        }
    /**
     **  So it is not a full path name what has been specified. Scan the
     **  MODULESPATH
     **/
    } else {
	/**
	 **  If I don't find a path in MODULEPATH, there's nothing to search.
	 **/
	if( !( modulespath = (char *) getenv( "MODULEPATH"))) {
	    if( OK != ErrorLogger( ERR_MODULE_PATH, LOC, NULL)) {
		g_current_module = NULL;
		goto unwind0;
	    }
	}
	/**
	 ** strip off any extraneous new lines
	 **/
	{ char *end;
	if ((char *) NULL != (end = strrchr(modulespath, '\n'))) *end = '\0';
	}
	/**
	 **  Expand the module name (in case it is a symbolic one). This must
	 **  be done once here in order to expand any aliases
	 **/
	if( VersionLookup( modulename, &mod, &vers)) {
	    if ((char *) NULL == stringer( buf, MOD_BUFSIZE,
	    mod,"/",vers, NULL))
		goto unwind0;
	    modulename = buf;
	}
	/**
	 **  Split up the MODULEPATH values into multiple directories
	 **/
	if( NULL == (pathlist = SplitIntoList(interp, modulespath, &numpaths,
	_colon)))
	    goto unwind0;
	/**
	 **  Check each directory to see if it contains the module
	 **/
	for(i=0; i<numpaths; i++) {
	    /* skip empty paths */
	    if(*pathlist[i] && (NULL != (result =
		GetModuleName( interp, pathlist[i], NULL, modulename)))) {

		if( strlen( pathlist[i]) + 2 + strlen( result) > MOD_BUFSIZE) {
		    if ((char *) NULL == stringer( filename, MOD_BUFSIZE,
		    pathlist[i], NULL))
			goto unwind1;
		} else {
		    if ((char *) NULL == stringer( filename, MOD_BUFSIZE,
		    pathlist[i],"/",result, NULL))
			goto unwind1;
		}
		break;
	    }
	    /**
	     **  If we havn't found it, we should try to re-expand the module
	     **  name, because some rc file have been sourced
	     **/
	    if( VersionLookup( modulename, &mod, &vers)) {
                if ((char *) NULL == stringer( buf, MOD_BUFSIZE,
		mod,"/",vers, NULL))
		    goto unwind1;
		modulename = buf;
	    }
	} /** for **/
	/**
	 **  Free the memory created from the call to SplitIntoList()
	 **/
	FreeList( pathlist, numpaths);
	/**
	 **  If result still NULL, then we really never found it and we should
	 **  return ERROR and clear the full_path array for cleanliness.
	 **/
	if( !result) {
	    filename[0] = '\0';
	    goto unwind0;
	}
    } /** not a full path name **/
    /**
     **  Free up what has been allocated and pass the result back to
     **  the caller and save the real module file name returned by
     **  GetModuleName
     **/
    strncpy( realname, result, MOD_BUFSIZE);
    if ((char *) NULL == stringer( realname, MOD_BUFSIZE, result, NULL))
	goto unwind1;
    null_free((void *) &result);

#if WITH_DEBUGGING_LOCATE
    ErrorLogger( NO_ERR_END, LOC, _proc_Locate_ModuleFile, NULL);
#endif

    return( TCL_OK);

unwind1:
    null_free((void *) &result);
unwind0:
    return( TCL_ERROR);
}
コード例 #26
0
ファイル: SubmarineManager.c プロジェクト: JeniaBR/EX1
int RadarSession(const TextFileReader* Reader,Submarine** submarine, const char* output_file)
 {
	Vessel* vessel_to_fire = NULL;
	Vessel* FriendList = NULL;
	Vessel* FOEList = NULL;
	Vessel* friends_in_danger = NULL;
	static int LineInd = 0;

	while((*Reader).WordsInLine[LineInd] == 4)
	{
		if(strcmp((*Reader).WordsArr[LineInd][1],"FRIEND")==0)
		{
			PushFromReader(&FriendList,&(*Reader).WordsArr[LineInd]);
		}
		else if(strcmp((*Reader).WordsArr[LineInd][1],"FOE")==0)
		{
			PushFromReader(&FOEList,&(*Reader).WordsArr[LineInd]);
			InSinkDanger(&(*submarine),FOEList);
		}
		LineInd++;
	}

	if(FOEList==NULL)
	{
		DuplicateFriendVesselSearch(submarine,FriendList,FRIEND_FILE_TRACK);
		PrintSubmarineStatus(*submarine);
		WriteSubmarineStatusToFile(*submarine,output_file);
		TrackingFriendlyVessels(FriendList);
	}
	else if(FriendList != NULL)
	{
		
		if(friends_in_danger = FindFriendsInDanger(FriendList,FOEList,&vessel_to_fire))
		{
			OperateAttack(&(*submarine),friends_in_danger,vessel_to_fire,output_file);
			FreeList(&friends_in_danger);
			FreeList(&vessel_to_fire);
		}
		else
		{
			(*submarine)->fire_command = CEASE;
			PrintSubmarineStatus(*submarine);
			WriteSubmarineStatusToFile(*submarine,output_file);
		}

		TrackingFriendlyVessels(FriendList);
	}
	else if(FOEList != NULL && FriendList == NULL)
	{
		(*submarine)->fire_command = CEASE;
		PrintSubmarineStatus(*submarine);
		WriteSubmarineStatusToFile(*submarine,output_file);
	}

	

	
	if((*Reader).WordsInLine[LineInd] == 0||(*Reader).NumOfLines == LineInd)
	{
		AddEndOfLine(output_file);
		FreeList(&FriendList);
		FreeList(&FOEList);
		LineInd++;
	}	
	else
	{
		printf("file is not orginzed");
		exit(1);
	}

	return LineInd;
}
コード例 #27
0
//---------------------------------------------------------------------------------
// Purpose: Load maps into memory
//---------------------------------------------------------------------------------
void	LoadMaps(const char *map_being_loaded)
{	
	FileHandle_t file_handle;
	char	base_filename[512];
	char	map_name[128];
	bool	map_is_in_map_cycle;
	bool	found_match;

	// Don't call FreeMaps() !!!!
	FreeList((void **) &map_list, &map_list_size);
	FreeList((void **) &votemap_list, &votemap_list_size);
	FreeList((void **) &map_in_cycle_list, &map_in_cycle_list_size);
	FreeList((void **) &map_not_in_cycle_list, &map_not_in_cycle_list_size);

	FindMapCVars();

//	MMsg("************ LOADING MAP LISTS *************\n");
	override_changelevel = 0;

//	MMsg("Loading Map [%s]\n", map_being_loaded);
	Q_strcpy(current_map, map_being_loaded);

	// Update last maps list
	last_map_index ++;
	if (last_map_index == MAX_LAST_MAPS)
	{
		last_map_index = 0;
	}


	Q_strcpy(last_map_list[last_map_index].map_name, current_map);

	time_t current_time;
	time(&current_time);
	last_map_list[last_map_index].start_time = current_time;

	SetChangeLevelReason("");

	Q_strcpy(last_map_list[last_map_index].end_reason, "");

	// Reset force map stuff, mani_map_cycle_mode will set these if necessary
	// when server.cfg is run
	Q_strcpy(forced_nextmap,"");
	override_changelevel = 0;
	override_setnextmap = false;

	// Get nextmap on level change
	file_handle = filesystem->Open (mapcyclefile->GetString(),"rt",NULL);
	if (file_handle == NULL)
	{
//		MMsg("Failed to load %s\n", mapcyclefile->GetString());
		Q_strcpy(next_map, map_being_loaded);
		mani_nextmap.SetValue(next_map);
		AddToList((void **) &map_in_cycle_list, sizeof(map_t), &map_in_cycle_list_size);
		Q_strcpy(map_in_cycle_list[map_in_cycle_list_size - 1].map_name, map_being_loaded);
	}
	else
	{
//		MMsg("Mapcycle list [%s]\n", mapcyclefile->GetString());

		while (filesystem->ReadLine (map_name, sizeof(map_name), file_handle) != NULL)
		{
			if (!ParseLine(map_name, true, false))
			{
				continue;
			}

			if (engine->IsMapValid(map_name) == 0) 
			{
//				MMsg("\n*** Map [%s] is not a valid map !!! *****\n", map_name);
				continue;
			}

			AddToList((void **) &map_in_cycle_list, sizeof(map_t), &map_in_cycle_list_size);
			Q_strcpy(map_in_cycle_list[map_in_cycle_list_size - 1].map_name, map_name);
			map_in_cycle_list[map_in_cycle_list_size - 1].selected_for_vote = false;

//			MMsg("[%s] ", map_name);
		}

//		MMsg("\n");
		filesystem->Close(file_handle);
	}
	
	// Check if this map is in the map cycle
	map_is_in_map_cycle = false;
	for (int i = 0; i < map_in_cycle_list_size; i ++)
	{
		if (FStrEq(map_in_cycle_list[i].map_name, current_map))
		{
			map_is_in_map_cycle = true;
			break;
		}
	}

	if (!map_is_in_map_cycle)
	{
		// Map loaded is not in the map cycle list
		// so hl2 will default the next map to 
		// be the first on the map cycle list
		if (map_in_cycle_list_size != 0)
		{
			Q_strcpy(next_map, map_in_cycle_list[0].map_name);
			mani_nextmap.SetValue(next_map);
		}
	}
	else
	{
		// Search map cycle list for nextmap
		for (int i = 0; i < map_in_cycle_list_size; i ++)
		{
			if (FStrEq( map_in_cycle_list[i].map_name, current_map))
			{
				if (i == (map_in_cycle_list_size - 1))
				{
					// End of map list so we must use the first
					// in the list
					Q_strcpy(next_map, map_in_cycle_list[0].map_name);
					mani_nextmap.SetValue(next_map);
				}
				else
				{
					// Set next map
					Q_strcpy(next_map, map_in_cycle_list[i+1].map_name);
					mani_nextmap.SetValue(next_map);
				}

				Q_strcpy(last_map_in_cycle, current_map);

				break;
			}
		}
	}

	//Get Map list
	
       //Default to loading the new location
       if(filesystem->FileExists("cfg/mapcycle.txt",NULL)) { file_handle = filesystem->Open ("cfg/mapcycle.txt","rt",NULL); }
       //If that failed, load the default file from the new location
       else if(filesystem->FileExists("cfg/mapcycle_default.txt",NULL)) { file_handle = filesystem->Open ("cfg/mapcycle_default.txt","rt",NULL); }
       //fall back to the old location
       else { file_handle = filesystem->Open ("maplist.txt","rt",NULL); }
	
	if (file_handle == NULL)
	{
		MMsg("Failed to load maplist.txt/mapcycle.txt YOU MUST HAVE A MAPLIST.TXT FILE!\n");
	}
	else
	{
//		MMsg("Map list\n");

		while (filesystem->ReadLine (map_name, 128, file_handle) != NULL)
		{
			if (!ParseLine(map_name, true, false))
			{
				// String is empty after parsing
				continue;
			}


			if ((!FStrEq( map_name, "test_speakers"))
				&& (!FStrEq( map_name, "test_hardware")))
			{
				if (engine->IsMapValid(map_name) == 0) 
				{
					MMsg("\n*** Map [%s] is not a valid map !!! *****\n", map_name);
					continue;
				}

				AddToList((void **) &map_list, sizeof(map_t), &map_list_size);
				Q_strcpy(map_list[map_list_size-1].map_name, map_name);
				map_list[map_list_size - 1].selected_for_vote = false;
//				MMsg("[%s] ", map_name);
			}
		}

//		MMsg("\n");
		filesystem->Close(file_handle);
	}

//	MMsg("Maps not in [%s]\n", mapcyclefile->GetString());
	// Calculate maps not in mapcycle

	for (int i = 0; i < map_list_size; i ++)
	{
		found_match = false;
		for (int j = 0; j < map_in_cycle_list_size; j++)
		{
			if (FStrEq(map_list[i].map_name, map_in_cycle_list[j].map_name))
			{
				found_match = true;
				break;
			}
		}

		if (!found_match)
		{
			AddToList((void **) &map_not_in_cycle_list, sizeof(map_t), &map_not_in_cycle_list_size);
			Q_strcpy(map_not_in_cycle_list[map_not_in_cycle_list_size - 1].map_name, map_list[i].map_name);
//			MMsg("[%s] ", map_not_in_cycle_list[map_not_in_cycle_list_size - 1].map_name);
		}
	}			

//	MMsg("\n");

	// Check if votemaplist.txt exists, create a new one if it doesn't
	snprintf(base_filename, sizeof (base_filename), "./cfg/%s/votemaplist.txt", mani_path.GetString());
	file_handle = filesystem->Open (base_filename,"rt",NULL);
	if (file_handle == NULL)
	{
		MMsg("Failed to load votemaplist.txt\n");
		MMsg("Attempting to write a new votemaplist.txt file based on maplist.txt\n");

		file_handle = filesystem->Open(base_filename,"wt",NULL);
		if (file_handle == NULL)
		{
//			MMsg("Failed to open votemaplist.txt for writing\n");
		}
		else
		{
			// Write votemaplist.txt in human readable text format
			for (int i = 0; i < map_list_size; i ++)
			{
				char	temp_string[512];
				int		temp_length = snprintf(temp_string, sizeof(temp_string), "%s\n", map_list[i].map_name);

				if (filesystem->Write((void *) temp_string, temp_length, file_handle) == 0)											
				{
					MMsg("Failed to write map [%s] to votemaplist.txt!!\n", map_list[i].map_name);
					filesystem->Close(file_handle);
					break;
				}
			}

			MMsg("Wrote %i maps to votemaplist.txt\n", map_list_size);
			filesystem->Close(file_handle);
		}
	}
	else
	{
		filesystem->Close(file_handle);
	}

	// Read in votemaplist.txt
	file_handle = filesystem->Open (base_filename,"rt",NULL);
	if (file_handle == NULL)
	{
//		MMsg("Failed to load votemaplist.txt\n");
	}
	else
	{
//		MMsg("Votemap list\n");
		while (filesystem->ReadLine (map_name, sizeof(map_name), file_handle) != NULL)
		{
			if (!ParseLine(map_name, true, false))
			{
				// String is empty after parsing
				continue;
			}

			if (engine->IsMapValid(map_name) == 0) 
			{
				MMsg("\n*** Map [%s] is not a valid map !!! *****\n", map_name);
				continue;
			}

			AddToList((void **) &votemap_list, sizeof(map_t), &votemap_list_size);
			Q_strcpy(votemap_list[votemap_list_size - 1].map_name, map_name);
			votemap_list[votemap_list_size - 1].selected_for_vote = false;
//			MMsg("[%s] ", map_name);
		}

//		MMsg("\n");
		filesystem->Close(file_handle);
	}

	// Check if loaded map cycle file is different than
	// the persistent one
	bool	rebuild_proper_map_cycle = false;

	if (map_in_cycle_list_size != proper_map_cycle_mode_list_size)
	{
		rebuild_proper_map_cycle = true;
	}
	else
	{
		// Both cycles the same size so check maps are in same
		// order
		for (int i = 0; i < map_in_cycle_list_size; i ++)
		{
			if (!FStrEq(map_in_cycle_list[i].map_name, 
						proper_map_cycle_mode_list[i].map_name))
			{
				rebuild_proper_map_cycle = true;
				break;
			}
		}
	}

	if (rebuild_proper_map_cycle)
	{
		// Free persistance map cycle and rebuild
		FreeList((void **) &proper_map_cycle_mode_list, &proper_map_cycle_mode_list_size);
		for (int i = 0; i < map_in_cycle_list_size; i++)
		{
			AddToList((void **) &proper_map_cycle_mode_list, sizeof(track_map_t), &proper_map_cycle_mode_list_size);
			Q_strcpy(proper_map_cycle_mode_list[i].map_name, map_in_cycle_list[i].map_name);
			proper_map_cycle_mode_list[i].played = false;
			if (FStrEq(proper_map_cycle_mode_list[i].map_name, current_map))
			{
				proper_map_cycle_mode_list[i].played = true;
			}
		}
	}

//	MMsg("Persistant Map Cycle\n");
	for (int i = 0; i < proper_map_cycle_mode_list_size; i++)
	{
		if (FStrEq(proper_map_cycle_mode_list[i].map_name, current_map))
		{
			proper_map_cycle_mode_list[i].played = true;
		}

		if (proper_map_cycle_mode_list[i].played)
		{
//			MMsg("*[%s] ", proper_map_cycle_mode_list[i].map_name);
		}
		else
		{
//			MMsg("[%s] ", proper_map_cycle_mode_list[i].map_name);
		}
	}

//	MMsg("\n");
//	MMsg("************ MAP LISTS LOADED *************\n");
}
コード例 #28
0
int main(void)
{
  struct Node *list1 = 0;
  struct Node *list2 = 0; 
  const int numbers[] = {
                         12, 34, 21, 56, 38, 94, 23, 22, 
                         67, 56, 88, 19, 59, 10, 17
                        };
  int size = sizeof(numbers) / sizeof(*numbers);

    // Create two lists
  for (int i = 0; i < size; i++)
  {
    AddToEnd(&list1, numbers[i]);
    AddToFront(&list2, numbers[i]);

    std::cout << "List1 (" << std::setw(2) << Count(list1) << " nodes): ";
    PrintList(list1);
    std::cout << "List2 (" << std::setw(2) << Count(list2) << " nodes): ";
    PrintList(list2);
    std::cout << std::endl;
  }

    // Find an existing value
  int value = 56;
  struct Node *node = FindItem(list1, value);
  if (node)
    std::cout << "Value: " << node->number << " was found.\n\n";
  else
    std::cout << "Value: " << node->number << " was not found.\n\n";

    // Find a non-existant value
  value = 123;
  node = FindItem(list1, value);
  if (node)
    std::cout << "Value: " << node->number << " was found.\n\n";
  else
    std::cout << "Value: " << value << " was not found.\n\n";

    // Release the nodes
  FreeList(list1);
  FreeList(list2);

    // Inserting
  list1 = 0;
  for (int i = 0; i < 5; i++)
  {
    AddToEnd(&list1, numbers[i]);
    std::cout << "List1 (" << std::setw(2) << Count(list1) << " nodes): ";
    PrintList(list1);
    std::cout << std::endl;
  }

  std::cout << "Inserting...\n";
  Insert(&list1, 91, 3);
  PrintList(list1);
  Insert(&list1, 92, 0);
  PrintList(list1);
  Insert(&list1, 93, 7);
  PrintList(list1);
  Insert(&list1, 94, 9);
  PrintList(list1);

  FreeList(list1);

  return 0;
}
コード例 #29
0
static void ProcFile( char * fname )
/**********************************/
{
    int         ftype;
    char *      name;
    int         status;
    int         namelen;
    char *      bak;

    namelen = strlen( fname ) + 5;
    name = alloca( namelen );
    if( name == NULL ) Suicide();           // null == no stack space left.
    strcpy( name, fname );
    ReplaceExt( name, ".obj", FALSE );
    InFile = QOpen( name, O_RDONLY | O_BINARY, 0 );
    for(;;) {
        CleanRecStuff();
        ftype = ReadRec();
        if( ftype == ENDLIBRARY || ftype == ENDFILE ) {
            break;
        } else if( ftype == LIBRARY ) {
            Warning( "exclude option does not apply to libraries" );
            FreeList( ExcludeList );
            ExcludeList = NULL;
        } else if( ftype != OBJECT ) {
            Error( "file is not a standard OBJECT or LIBRARY file" );
        }
        OutFile = QOpen( TEMP_OBJ_NAME, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, 0 );
        do {
            ProcessRec();
            status = ReadRec();
        } while( status == OK );
        if( status == ENDMODULE ) {
            ProcessRec();           // process the modend rec.
            DoReplace();
        } else {
            Error( "premature end of file encountered" );
        }
        FreeList( ExcludeList );    // do this here so concatenated .obj files
        ExcludeList = NULL;         // only have the first module excluded.
    }
    CloseFiles();
    if( MakeBackup ) {
        bak = alloca( namelen );
        if( bak == NULL ) Suicide();           // null == no stack space left.
        strcpy( bak, name );
        if( ftype == ENDLIBRARY ) {
            ReplaceExt( bak, ".bak", TRUE );
        } else {
            ReplaceExt( bak, ".bob", TRUE );
        }
        CopyFile( name, bak );
    }
    QRemove( name );
    if( ftype == ENDLIBRARY ) {
        rename( TEMP_LIB_NAME, name );
    } else {
        rename( TEMP_OBJ_NAME, name );
    }
    FileCleanup();
}
コード例 #30
0
ファイル: MidiShare.c プロジェクト: AntonLanghoff/whitecatlib
MidiEvPtr MIDISHAREAPI MidiDTask(TaskPtr routine, unsigned long date, short refNum, long a1,long a2,long a3) {
  	return MSDTask( routine,date,refNum,a1,a2,a3, FreeList(Memory(gMem)), SorterList(gMem));
}