Esempio n. 1
0
LibFileIoClass::~LibFileIoClass(void)
{
	LibError_SetExtErrorMessage("");
	FileClose();
}
Esempio n. 2
0
BOOLEAN WriteSoundArray()
{
    HWFILE		hFile;
    DebugMsg(TOPIC_JA2, DBG_LEVEL_3, String("WriteSoundArray"));
    //Debug code; make sure that what we got from the file is the same as what's there
    // Open a new file
    hFile = FileOpen( "TABLEDATA\\Sounds out.xml", FILE_ACCESS_WRITE | FILE_CREATE_ALWAYS, FALSE );
    if ( !hFile )
        return( FALSE );
    UINT32 cnt;

    FilePrintf(hFile,"<SOUNDLIST>\r\n");
    for(cnt = 0;cnt < NUM_SAMPLES;cnt++)
    {
        FilePrintf(hFile,"\t<SOUND>");
        STR8 szRemainder = szSoundEffects[cnt]; //the remaining string to be output (for making valid XML)
        while(szRemainder[0] != '\0')
        {
            UINT32 uiCharLoc = strcspn(szRemainder,"&<>\'\"\0");
            char invChar = szRemainder[uiCharLoc];

            if(uiCharLoc)
            {
                szRemainder[uiCharLoc] = '\0';
                FilePrintf(hFile,"%s",szRemainder);
                szRemainder[uiCharLoc] = invChar;
            }
            szRemainder += uiCharLoc;
            switch(invChar)
            {
                case '&':
                    FilePrintf(hFile,"&amp;");
                    szRemainder++;
                    break;

                case '<':
                    FilePrintf(hFile,"&lt;");
                    szRemainder++;
                    break;

                case '>':
                    FilePrintf(hFile,"&gt;");
                    szRemainder++;
                    break;

                case '\'':
                    FilePrintf(hFile,"&apos;");
                    szRemainder++;
                    break;

                case '\"':
                    FilePrintf(hFile,"&quot;");
                    szRemainder++;
                    break;
            }
        }
        FilePrintf(hFile,"</SOUND>\r\n");
    }
    FilePrintf(hFile,"</SOUNDLIST>\r\n");
    FileClose( hFile );
    return( TRUE );
}
void CEtsEodManagerDoc::DeleteContents()
{
	FileClose();
	CDocument::DeleteContents();
}
Esempio n. 4
0
/*****************************************************************************
*
*   This is the main program.
*     It reads command line or initial dialogue arguments
*     It initializes parse trees, entrez
*     It makes a list of the relevant files to search
*     It then calls ProcessFileList to open each file and process it
*
*****************************************************************************/
Int2 Main (void)
{
  Char         div [8];
  FileListPtr  flp = NULL;
  FILE         *fp;
  Int2         i;
  Boolean      is_network, did_init=FALSE;
  FileListPtr  next;
  CharPtr      outputfile;

  if (! GetArgs ("CdScan", NUMARGS, myargs))   /* get input args */
	goto ret;

											   /* process input args */
  if (myargs[0].intvalue == 1)
  	is_na = TRUE;      /* scan nucleic acids */
  else
  	is_na = FALSE;     /* scan proteins */
  format = (Int2)(myargs[1].intvalue);
  is_custom = (Boolean)(myargs[2].intvalue);
  if (myargs[3].intvalue)   /* show progress */
  {
  	pmon = MonitorStrNew("CdScan", 40);
  }
  outputfile = myargs[4].strvalue;   /* output file name */

  if (pmon != NULL)
  	MonitorStrValue(pmon, "Reading Parse Trees");

  if (! SeqEntryLoad() || ! SubmitAsnLoad())   /* read ASN.1 parse trees */
  {
  	Message(MSG_ERROR, "Can't open parse trees");
  	goto ret;
  }

  if (! PrintTemplateSetLoad ("asn2ff.prt"))
  {
    Message(MSG_ERROR, "Can't load print templates");
	goto ret;
  }

  if (pmon != NULL)
  	MonitorStrValue(pmon, "Initializing Entrez");

  if (! EntrezInit ("cdscan", FALSE, &is_network)) /* init Entrez */
  {
  	Message(MSG_ERROR, "Can't initialize Entrez");
  	goto ret;
  }

  did_init = TRUE;
  if (is_network)
  {
      Message (MSG_ERROR, "Network service does not allow scanning");
  	goto ret;
  }

  if (pmon != NULL)
  	MonitorStrValue(pmon, "Building File List");

  eip = EntrezGetInfo ();                        /* set up the file lists */
  if ((eip == NULL) || (eip->div_info == NULL))
  {
  	Message(MSG_ERROR, "Can't find Entrez file info");
  	goto ret;
  }


  flp = FileListNew (NULL, INT2_MIN, NULL, NULL);
  if (flp == NULL)
  {
  	Message(MSG_ERROR, "Can't allocate file list");
  	goto ret;
  }

  div_info = eip->div_info;
  for (i = 0; i < eip->div_count; i++)
  {
  	StringNCpy (div, div_info [i].tag, sizeof (div) - 1);
  	if (! is_na)
  	{
      	CdEnumFiles (CdDir_rec, TYP_AA, div, EnumerateFiles, &flp);
      }
  	else
  	{
      	CdEnumFiles (CdDir_rec, TYP_NT, div, EnumerateFiles, &flp);
  	}
  }

  fp = FileOpen (outputfile, "w");   /* test that we can open output file */
  if (fp == NULL)
  {
  	Message(MSG_ERROR, "Can't open [%s]", outputfile);
  	goto ret;
  }

  FileClose (fp);     /* will be reopened for each input file */

  ProcessFileList (flp, outputfile);              /* process the file list */

ret:                                                         /* clean up */

  if (pmon != NULL)     /* close the progress monitor */
	MonitorFree(pmon);

  if (did_init)
	  EntrezFini();         /* close entrez */

  while (flp != NULL)       /* free file list */
  {
    next = flp->next;
    MemFree (flp->fdir);
    MemFree (flp->fname);
    MemFree (flp);
    flp = next;
  }

  return 0;
}
Esempio n. 5
0
bool CfgSaveExW3(CFG_RW *rw, FOLDER *f, wchar_t *name, UINT *written_size, bool write_binary)
{
	wchar_t tmp[MAX_SIZE];
	bool text = !write_binary;
	UCHAR hash[SHA1_SIZE];
	BUF *b;
	IO *o;
	bool ret = true;
	UINT dummy_int = 0;
	// Validate arguments
	if (name == NULL || f == NULL)
	{
		return false;
	}
	if (written_size == NULL)
	{
		written_size = &dummy_int;
	}

	// Convert to buffer
	b = CfgFolderToBuf(f, text);
	if (b == NULL)
	{
		return false;
	}
	// Hash the contents
	Hash(hash, b->Buf, b->Size, true);

	// Compare the contents to be written with the content which was written last
	if (rw != NULL)
	{
		if (Cmp(hash, rw->LashHash, SHA1_SIZE) == 0)
		{
			// Contents are not changed
			ret = false;
		}
		else
		{
			Copy(rw->LashHash, hash, SHA1_SIZE);
		}
	}

	if (ret || OS_IS_UNIX(GetOsInfo()->OsType))
	{
		// Generate a temporary file name
		UniFormat(tmp, sizeof(tmp), L"%s.log", name);
		// Copy the file that currently exist to a temporary file
		FileCopyW(name, tmp);

		// Save the new file
		o = FileCreateW(name);
		if (o != NULL)
		{
			if (FileWrite(o, b->Buf, b->Size) == false)
			{
				// File saving failure
				FileClose(o);
				FileDeleteW(name);
				FileRenameW(tmp, name);

				if (rw != NULL)
				{
					Zero(rw->LashHash, sizeof(rw->LashHash));
				}
			}
			else
			{
				// Successful saving file
				FileClose(o);
				// Delete the temporary file
				FileDeleteW(tmp);
			}
		}
		else
		{
			// File saving failure
			FileRenameW(tmp, name);

			if (rw != NULL)
			{
				Zero(rw->LashHash, sizeof(rw->LashHash));
			}
		}
	}

	*written_size = b->Size;

	// Release memory 
	FreeBuf(b);

	return ret;
}
Esempio n. 6
0
BOOLEAN ReadInBurstSoundArray(STR fileName)
{
	HWFILE		hFile;
	UINT32		uiBytesRead;
	UINT32		uiFSize;
	CHAR8 *		lpcBuffer;
	XML_Parser	parser = XML_ParserCreate(NULL);

	burstSoundParseData pData;

	DebugMsg(TOPIC_JA2, DBG_LEVEL_3, String("Loading %s",SOUNDSFILENAME ) );

	// Open sounds file
	hFile = FileOpen( fileName, FILE_ACCESS_READ, FALSE );
	if ( !hFile )
		return( FALSE );

	uiFSize = FileGetSize(hFile);
	lpcBuffer = (CHAR8 *) MemAlloc(uiFSize+1);

	//Read in block
	if ( !FileRead( hFile, lpcBuffer, uiFSize, &uiBytesRead ) )
	{
		MemFree(lpcBuffer);
		return( FALSE );
	}

	lpcBuffer[uiFSize] = 0; //add a null terminator

	FileClose( hFile );


	XML_SetElementHandler(parser, burstSoundStartElementHandle, burstSoundEndElementHandle);
	XML_SetCharacterDataHandler(parser, burstSoundCharacterDataHandle);


	memset(&pData,0,sizeof(pData));
	pData.maxArraySize = MAX_SAMPLES;
	pData.curIndex = -1;

	XML_SetUserData(parser, &pData);


	if(!XML_Parse(parser, lpcBuffer, uiFSize, TRUE))
	{
		CHAR8 errorBuf[511];

		sprintf(errorBuf, "XML Parser Error in %s.xml: %s at line %d", SOUNDSFILENAME, XML_ErrorString(XML_GetErrorCode(parser)), XML_GetCurrentLineNumber(parser));
		LiveMessage(errorBuf);

		MemFree(lpcBuffer);
		return FALSE;
	}

	MemFree(lpcBuffer);


	XML_ParserFree(parser);

	return( TRUE );
}
Esempio n. 7
0
int loadStrings()
{
	const size_t tokenNum = 1 + STR_NUM * 2;
	jsmntok_t t[tokenNum];
	char buf[8192];
	wchar_t path[_MAX_LFN];
	jsmn_parser p;
	unsigned int i, j, k;
	const char *s;
	int l, r, len;
	File fd;

	swprintf(path, _MAX_LFN, L"%ls/%s",
		langPath, fontIsLoaded ? cfgs[CFG_LANG].val.s : "en.json");
	if (!FileOpen(&fd, path, 0))
		return 1;

	len = FileGetSize(&fd);
	if (len > sizeof(buf))
		return 1;

	FileRead(&fd, buf, len, 0);
	FileClose(&fd);

	jsmn_init(&p);
	r = jsmn_parse(&p, buf, len, t, tokenNum);
	if (r < 0)
		return r;

	for (i = 1; i < r; i++) {
		for (j = 0; j < STR_NUM; j++) {
			s = buf + t[i].start;

			len = t[i].end - t[i].start;
			if (!memcmp(s, keys[j], len) && !keys[j][len]) {
				i++;
				len = t[i].end - t[i].start;
				s = buf + t[i].start;
				for (k = 0; k + 1 < STR_MAX_LEN && len > 0; k++) {
					if (s[0] == '\\' && s[1] == 'n') {
						strings[j][k] = '\n';
						l = 2;
					} else {
						l = mbtowc(strings[j] + k, s, len);
						if (l < 0)
							break;
					}

					len -= l;
					s += l;
				}

				strings[j][k] = 0;
				mbtowc(NULL, NULL, 0);
				break;
			}
		}
	}

	return 0;
}
Esempio n. 8
0
static Int2 LIBCALLBACK TPASmartBioseqFetchFunc (Pointer data)

{
  BioseqPtr         bsp;
  Char              cmmd [256];
  Pointer           dataptr;
  Uint2             datatype;
  Uint2             entityID;
  FILE*             fp;
  OMProcControlPtr  ompcp;
  ObjMgrProcPtr     ompp;
  Char              path [PATH_MAX];
  Char              err_path [PATH_MAX];
  SeqEntryPtr       sep = NULL;
  SeqIdPtr          sip;
  TextSeqIdPtr      tsip;

  ompcp = (OMProcControlPtr) data;
  if (ompcp == NULL) return OM_MSG_RET_ERROR;
  ompp = ompcp->proc;
  if (ompp == NULL) return OM_MSG_RET_ERROR;
  sip = (SeqIdPtr) ompcp->input_data;
  if (sip == NULL) return OM_MSG_RET_ERROR;

  if (sip->choice != SEQID_TPG) return OM_MSG_RET_ERROR;
  tsip = (TextSeqIdPtr) sip->data.ptrvalue;
  if (tsip == NULL || StringHasNoText (tsip->accession)) return OM_MSG_RET_ERROR;

  if (tpasmartfetchcmd == NULL) {
    if (GetAppParam ("SEQUIN", "TPASMART", "FETCHSCRIPT", NULL, cmmd, sizeof (cmmd))) {
    	tpasmartfetchcmd = StringSaveNoNull (cmmd);
    }
  }
  if (tpasmartfetchcmd == NULL) return OM_MSG_RET_ERROR;

  TmpNam (path);

#ifdef OS_UNIX
  sprintf (err_path, "%s.err", path);
  sprintf (cmmd, "csh %s %s > %s 2>%s", tpasmartfetchcmd, tsip->accession, path, err_path);
  system (cmmd);
#endif
#ifdef OS_MSWIN
  sprintf (cmmd, "%s %s -o %s", tpasmartfetchcmd, tsip->accession, path);
  system (cmmd);
#endif

  fp = FileOpen (path, "r");
  if (fp == NULL) {
    FileRemove (path);
#ifdef OS_UNIX
    FileRemove (err_path);
#endif
    return OM_MSG_RET_ERROR;
  }
  dataptr = ReadAsnFastaOrFlatFile (fp, &datatype, &entityID, FALSE, FALSE, TRUE, FALSE);
  FileClose (fp);
  FileRemove (path);
#ifdef OS_UNIX
  FileRemove (err_path);
#endif

  if (dataptr == NULL) return OM_MSG_RET_OK;

  sep = GetTopSeqEntryForEntityID (entityID);
  if (sep == NULL) return OM_MSG_RET_ERROR;
  bsp = BioseqFindInSeqEntry (sip, sep);
  ompcp->output_data = (Pointer) bsp;
  ompcp->output_entityID = ObjMgrGetEntityIDForChoice (sep);
  return OM_MSG_RET_DONE;
}
Esempio n. 9
0
File: dem.c Progetto: GYGit/reactos
static VOID WINAPI DosInitialize(LPWORD Stack)
{
    /* Get the DOS BIOS file name (NULL-terminated) */
    // FIXME: Isn't it possible to use some DS:SI instead??
    LPCSTR DosBiosFileName = (LPCSTR)SEG_OFF_TO_PTR(getCS(), getIP());
    setIP(getIP() + strlen(DosBiosFileName) + 1); // Skip it

    DPRINT("DosInitialize('%s')\n", DosBiosFileName);

    /*
     * We succeeded, deregister the DOS Loading BOP
     * so that no app will be able to call us back.
     */
    RegisterBop(BOP_LOAD_DOS, NULL);

    /* Register the DOS BOPs */
    RegisterBop(BOP_DOS, DosSystemBop        );
    RegisterBop(BOP_CMD, DosCmdInterpreterBop);

    if (DosBiosFileName[0] != '\0')
    {
        BOOLEAN Success = FALSE;
        HANDLE  hDosBios;
        ULONG   ulDosBiosSize = 0;

        /* Open the DOS BIOS file */
        hDosBios = FileOpen(DosBiosFileName, &ulDosBiosSize);
        if (hDosBios == NULL) goto Quit;

        /* Attempt to load the DOS BIOS into memory */
        Success = FileLoadByHandle(hDosBios,
                                   REAL_TO_PHYS(TO_LINEAR(0x0070, 0x0000)),
                                   ulDosBiosSize,
                                   &ulDosBiosSize);

        DPRINT1("DOS BIOS file '%s' loading %s at %04X:%04X, size 0x%X (Error: %u).\n",
                DosBiosFileName,
                (Success ? "succeeded" : "failed"),
                0x0070, 0x0000,
                ulDosBiosSize,
                GetLastError());

        /* Close the DOS BIOS file */
        FileClose(hDosBios);

Quit:
        if (!Success)
        {
            BiosDisplayMessage("DOS BIOS file '%s' loading failed (Error: %u). The VDM will shut down.\n",
                               DosBiosFileName, GetLastError());
            return;
        }
    }
    else
    {
        /* Load the 16-bit startup code for DOS32 and register its Starting BOP */
        RtlCopyMemory(SEG_OFF_TO_PTR(0x0070, 0x0000), Startup, sizeof(Startup));

        // This is the equivalent of BOP_LOAD_DOS, function 0x11 "Load the DOS kernel"
        // for the Windows NT DOS.
        RegisterBop(BOP_START_DOS, DosStart);
    }

    /* Position execution pointers for DOS startup and return */
    setCS(0x0070);
    setIP(0x0000);
}
Esempio n. 10
0
Int2 Main(void)
{
  Char             app [64];
  Int4             rval = 0;
  CharPtr          id_file;
  ValNodePtr       fetch_list = NULL;
  ValNodePtr       field_list = NULL;
  ValNodePtr       table;
  Boolean          meta_mode = FALSE;
  FILE *fp;

  /* standard setup */

  ErrSetFatalLevel (SEV_MAX);
  ErrClearOptFlags (EO_SHOW_USERSTR);
  UseLocalAsnloadDataAndErrMsg ();
  ErrPathReset ();

  /* finish resolving internal connections in ASN.1 parse tables */

  if (! AllObjLoad ()) {
    Message (MSG_FATAL, "AllObjLoad failed");
    return 1;
  }
  if (! SubmitAsnLoad ()) {
    Message (MSG_FATAL, "SubmitAsnLoad failed");
    return 1;
  }
  if (! FeatDefSetLoad ()) {
    Message (MSG_FATAL, "FeatDefSetLoad failed");
    return 1;
  }
  if (! SeqCodeSetLoad ()) {
    Message (MSG_FATAL, "SeqCodeSetLoad failed");
    return 1;
  }
  if (! GeneticCodeTableLoad ()) {
    Message (MSG_FATAL, "GeneticCodeTableLoad failed");
    return 1;
  }

#ifdef INTERNAL_NCBI_TBL_CHK
    SmartFetchEnable ();
    TPASmartFetchEnable ();

    if (! PUBSEQBioseqFetchEnable ("tbl_chk", FALSE)) {
      Message (MSG_POSTERR, "PUBSEQBioseqFetchEnable failed");
      return 1;
    } 
#else
  PubSeqFetchEnable ();
#endif

  /* process command line arguments */

  sprintf (app, "tbl_chk %s", TBL_CHK_APPLICATION);
  if (! GetArgs (app, sizeof (myargs) / sizeof (Args), myargs)) {
    return 0;
  }

  id_file = (CharPtr) myargs [i_argInputFile].strvalue;
  debug_mode = (Boolean) myargs [D_argDebugMode].intvalue;
  meta_mode = (Boolean) myargs [m_argMetaMode].intvalue;

  fp = FileOpen (id_file, "r");
  if (fp == NULL) {
    Message (MSG_ERROR, "Unable to open %s", id_file);
    return 1;
  }

  table = ReadTabTableFromFile (fp);
  FileClose (fp);
  if (table == NULL || table->next == NULL) {
    Message (MSG_ERROR, "Table must have at least two rows, one header and one data");
    return 1;
  }

  field_list = GetFieldListFromHeader(table->data.ptrvalue);
  if (field_list == NULL) {
    Message (MSG_ERROR, "Unable to read table header");
    table = FreeTabTable (table);
    return 1;
  }
  fetch_list = FetchItemListFromTable (table);
  MakeFetchItemIndex(fetch_list);

  fp = FileOpen ((CharPtr) myargs [o_argOutputFile].strvalue, "w");
  if (fp == NULL) {
    Message (MSG_ERROR, "Unable to open %s", (CharPtr) myargs [o_argOutputFile].strvalue);
    rval = 1;
  } else {
    if (meta_mode) {
      fprintf (fp, "Accession\tField\tOld Value\tNew Value\n");
    }
    ProcessBioseqsWithCaching (fetch_list, field_list, table, meta_mode, fp);
  }
  FileClose (fp);
  field_list = FieldTypeListFree (field_list);
  fetch_list = FetchItemListFree (fetch_list);
  MakeFetchItemIndex(NULL);

  return rval;
}
Esempio n. 11
0
static BioseqPtr FetchBioseqFromSmartNotId (CharPtr accn, Uint2Ptr pEntityID)
{
  BioseqPtr         bsp;
  Char              cmmd [256];
  Pointer           dataptr;
  Uint2             datatype;
  Uint2             entityID;
  FILE*             fp;
  OMProcControlPtr  ompcp;
  ObjMgrProcPtr     ompp;
  Char              path [PATH_MAX];
  Char              err_path [PATH_MAX];
  SeqEntryPtr       sep = NULL;
  SeqIdPtr          sip;
  TextSeqIdPtr      tsip;
  Int4              gi = 0;
  ValNodePtr        vnp;
  time_t            t1, t2;

  if (srcchkfetchcmd == NULL) {
    if (GetAppParam ("SEQUIN", "TBL_CHK", "FETCHSCRIPT", NULL, cmmd, sizeof (cmmd))) {
    	srcchkfetchcmd = StringSaveNoNull (cmmd);
    }
  }
  if (srcchkfetchcmd == NULL) {
    if (GetAppParam ("SEQUIN", "SMART", "FETCHSCRIPT", NULL, cmmd, sizeof (cmmd))) {
    	srcchkfetchcmd = StringSaveNoNull (cmmd);
    }
  }
  if (srcchkfetchcmd == NULL) return NULL;

  TmpNam (path);

  t1 = time(NULL);
#ifdef OS_UNIX
  sprintf (err_path, "%s.err", path);
  sprintf (cmmd, "csh %s %s > %s 2>%s", srcchkfetchcmd, accn, path, err_path);
  system (cmmd);
#endif
#ifdef OS_MSWIN
  sprintf (cmmd, "%s %s -o %s", srcchkfetchcmd, accn, path);
  system (cmmd);
#endif

  fp = FileOpen (path, "r");
  if (fp == NULL) {
    FileRemove (path);
#ifdef OS_UNIX
    FileRemove (err_path);
#endif
    return OM_MSG_RET_ERROR;
  }
  dataptr = ReadAsnFastaOrFlatFile (fp, &datatype, &entityID, FALSE, FALSE, TRUE, FALSE);
  FileClose (fp);
  FileRemove (path);
#ifdef OS_UNIX
  FileRemove (err_path);
#endif

  if (dataptr == NULL) return NULL;

  sep = GetTopSeqEntryForEntityID (entityID);

  if (sep == NULL) return NULL;
  sip = SmartGuessMakeId (accn);
  bsp = BioseqFindInSeqEntry (sip, sep);
  sip = SeqIdFree (sip);
  if (debug_mode) {
    t2 = time(NULL);
    if (t2 - t1 > 1) {
      printf("Time to download %s from SMART:%d\n", accn, t2 - t1);
    }
  }
  if (pEntityID != NULL) {
    *pEntityID = entityID;
  }
  return bsp;
}
Esempio n. 12
0
//===========================================================================
// ファイルからSHA-1ハッシュ値を取得する
//===========================================================================
bool __fastcall TForm1::GetSHA1HashFromFile(
	String FilePath,              // パスワードファイルパス
	AnsiString &HashDataVer2,     // ver.2.*  ~:SHA-1ハッシュ値(20byte + 12byte)
	AnsiString &HashDataVer1 )    // ver.1.*  ~:ヘッダデータ(先頭文字列32文字)
{

int i;

int fh;
int bytes, rest;
char buffer[255];	                               //読み込みバッファ
char sha1_hash_data_mixed_padding[BUF_HASH_DATA];// 32byte

for (i = 0; i < BUF_HASH_DATA; i++) {
	sha1_hash_data_mixed_padding[i] = NULL;
}

if ( !FileExists(FilePath) ) return(false);

try{

	if ( (fh = FileOpen(FilePath, fmShareDenyNone)) == -1 ){
		//パスワードファイルが開けない?
		return(false);
	}

	//ヘッダ先頭の255byteを読む(ver.1.* ~)
	FileRead(fh, buffer, 255);
	HashDataVer1 = (AnsiString)buffer;

	//SHA-1ハッシュの計算
	FileSeek(fh, 0, 0);
	SHA1Context sha;
	unsigned char Message_Digest[20];
	ZeroMemory(Message_Digest, 20);

	//初期化(リセット)
	if ( SHA1Reset(&sha)){
		return(false);
	}

	//ファイルを読み出してSHA-1へ入力していく
	while ((bytes = FileRead (fh, buffer, 255)) != 0){
		rest = bytes;
		if ( SHA1Input(&sha, (const unsigned char *)buffer, bytes) ){
			return(false);
		}
	}

	if ( FileSeek(fh, -rest, 2) > 0 ){
		FileRead(fh, buffer, 255);
	}
	else{
		FileSeek(fh, 0, 0);
		FileRead(fh, buffer, 255);
	}

	//出力
	if(SHA1Result(&sha, Message_Digest)){
		return(false);
	}
	for (i = 0; i < BUF_SHA1_SIZE; i++){   // 20byte
		sha1_hash_data_mixed_padding[i] = Message_Digest[i];
	}

	//残りの12byteを補填
	for (i = 0; i < 12; i++) {             // 12byte
		 sha1_hash_data_mixed_padding[BUF_SHA1_SIZE+i] = buffer[i];
	}

	HashDataVer2 = "";
	for (i = 0; i < BUF_HASH_DATA; i++){   // 32byte
		//適切にキャストされるように1byteずつ代入
		HashDataVer2 += (AnsiString)sha1_hash_data_mixed_padding[i];
	}
	HashDataVer2.SetLength(32);

}
__finally{

	FileClose(fh);

}
return(true);


}
Esempio n. 13
0
/*
 * ProcImgSymInfo -- initialize symbolic information
 *
 * Note: This function should try to open files locally first, for two
 * reasons:
 * 1) If a local file is open as remote, then local caching may interfere with
 *    file operations (notably seeks with DIO_SEEK_CUR)
 * 2) Remote access goes through extra layer of indirection; this overhead
 *    is completely unnecessary for local debugging.
 */
static bool ProcImgSymInfo( image_entry *image )
{
    file_handle     fh;
    dip_priority    last_priority;
    char            buff[TXT_LEN];
    char            *symfile_name;
    const char      *nopath;
    size_t          len;
    bool            ret;

    ret = false;
    image->deferred_symbols = false;
    if( _IsOff( SW_LOAD_SYMS ) )
        return( ret );
    if( image->symfile_name != NULL ) {
        last_priority = DIP_PRIOR_MAX;
        fh = PathOpen( image->symfile_name, strlen( image->symfile_name ), "sym" );
        if( fh == NIL_HANDLE ) {
            nopath = SkipPathInfo( image->symfile_name, OP_REMOTE );
            fh = PathOpen( nopath, strlen( nopath ), "sym" );
            if( fh == NIL_HANDLE ) {
                /* try the sym file without an added extension */
                fh = FileOpen( image->symfile_name, OP_READ );
            }
        }
    } else {
        last_priority = DIP_PRIOR_EXPORTS - 1;
        fh = FileOpen( image->image_name, OP_READ );
        if( fh == NIL_HANDLE ) {
            fh = FileOpen( image->image_name, OP_READ | OP_REMOTE );
        }
    }
    if( fh != NIL_HANDLE ) {
        ret = CheckLoadDebugInfo( image, fh, DIP_PRIOR_MIN, last_priority );
        FileClose( fh );
        if( ret ) {
            return( ret );
        }
    }
    if( image->symfile_name == NULL ) {
        _AllocA( symfile_name, strlen( image->image_name ) + 1 );
        strcpy( symfile_name, image->image_name );
        symfile_name[ExtPointer( symfile_name, OP_REMOTE ) - symfile_name] = NULLCHAR;
        len = MakeFileName( buff, symfile_name, "sym", OP_REMOTE );
        _Alloc( image->symfile_name, len + 1 );
        if( image->symfile_name != NULL ) {
            memcpy( image->symfile_name, buff, len + 1 );
            fh = FileOpen( image->symfile_name, OP_READ );
            if( fh == NIL_HANDLE ) {
                fh = FileOpen( image->symfile_name, OP_READ | OP_REMOTE );
            }
            if( fh == NIL_HANDLE ) {
                fh = PathOpen( image->symfile_name, strlen( image->symfile_name ), "" );
            }
            if( fh != NIL_HANDLE ) {
                ret = CheckLoadDebugInfo( image, fh, DIP_PRIOR_MIN, DIP_PRIOR_MAX );
                FileClose( fh );
                if( ret ) {
                    return( ret );
                }
            }
            _Free( image->symfile_name );
            image->symfile_name = NULL;
        }
        if( _IsOff( SW_NO_EXPORT_SYMS ) ) {
            if( _IsOn( SW_DEFER_SYM_LOAD ) ) {
                image->deferred_symbols = true;
            } else {
                fh = FileOpen( image->image_name, OP_READ | OP_REMOTE );
                if( fh != NIL_HANDLE ) {
                    ret = CheckLoadDebugInfo( image, fh, DIP_PRIOR_EXPORTS, DIP_PRIOR_MAX );
                    FileClose( fh );
                    if( ret ) {
                        return( ret );
                    }
                }
            }
        }
    }
    return( ret );
}
Esempio n. 14
0
/*
 * lo_export -
 *	  exports an (inversion) large object.
 */
Datum
lo_export(PG_FUNCTION_ARGS)
{
	Oid			lobjId = PG_GETARG_OID(0);
	text	   *filename = PG_GETARG_TEXT_PP(1);
	File		fd;
	int			nbytes,
				tmp;
	char		buf[BUFSIZE];
	char		fnamebuf[MAXPGPATH];
	LargeObjectDesc *lobj;
	mode_t		oumask;

#ifndef ALLOW_DANGEROUS_LO_FUNCTIONS
	if (!superuser())
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
				 errmsg("must be superuser to use server-side lo_export()"),
				 errhint("Anyone can use the client-side lo_export() provided by libpq.")));
#endif

	CreateFSContext();

	/*
	 * open the inversion object (no need to test for failure)
	 */
	lobj = inv_open(lobjId, INV_READ, fscxt);

	/*
	 * open the file to be written to
	 *
	 * Note: we reduce backend's normal 077 umask to the slightly friendlier
	 * 022. This code used to drop it all the way to 0, but creating
	 * world-writable export files doesn't seem wise.
	 */
	text_to_cstring_buffer(filename, fnamebuf, sizeof(fnamebuf));
	oumask = umask(S_IWGRP | S_IWOTH);
	fd = PathNameOpenFile(fnamebuf, O_CREAT | O_WRONLY | O_TRUNC | PG_BINARY,
						  S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
	umask(oumask);
	if (fd < 0)
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not create server file \"%s\": %m",
						fnamebuf)));

	/*
	 * read in from the inversion file and write to the filesystem
	 */
	while ((nbytes = inv_read(lobj, buf, BUFSIZE)) > 0)
	{
		tmp = FileWrite(fd, buf, nbytes);
		if (tmp != nbytes)
			ereport(ERROR,
					(errcode_for_file_access(),
					 errmsg("could not write server file \"%s\": %m",
							fnamebuf)));
	}

	FileClose(fd);
	inv_close(lobj);

	PG_RETURN_INT32(1);
}
Esempio n. 15
0
/** Initializes the auxiliary structure with RPS BLAST database information.
 * @param ppinfo Resulting structure. [out]
 * @param rps_mmap Memory mapped lookup table [out]
 * @param rps_pssm_mmap Memory mapped PSSM [out]
 * @param dbname Name of the database [in]
 */
static Int2 
s_BlastRPSInfoInit(BlastRPSInfo **ppinfo, Nlm_MemMap **rps_mmap,
                   Nlm_MemMap **rps_pssm_mmap, const char* dbname)
{
   char filename[PATH_MAX];
   char pathname[PATH_MAX];
   BlastRPSInfo *info;
   FILE *auxfile;
   Int4 i;
   Int4 seq_size;
   Int4 num_db_seqs;
   Nlm_MemMapPtr lut_mmap;
   Nlm_MemMapPtr pssm_mmap;
   char buffer[PATH_MAX];
   ReadDBFILEPtr rdfp;
   char *tmp_dbname;
   Uint4 version;

   info = (BlastRPSInfo *)malloc(sizeof(BlastRPSInfo));
   if (info == NULL)
      ErrPostEx(SEV_FATAL, 1, 0, "Memory allocation failed");

   /* find the path to the RPS database */
   tmp_dbname = strdup(dbname);
   rdfp = readdb_new_ex2(tmp_dbname, READDB_DB_IS_PROT, 
                         READDB_NEW_DO_REPORT, NULL, NULL);
   sfree(tmp_dbname);
   if (rdfp == NULL)
      ErrPostEx(SEV_FATAL, 1, 0, "Cannot map RPS BLAST database");
   sprintf(pathname, "%s", rdfp->full_filename);
   rdfp = readdb_destruct(rdfp);

   sprintf(filename, "%s.loo", (char *)pathname);
   lut_mmap = Nlm_MemMapInit(filename);
   if (lut_mmap == NULL)
      ErrPostEx(SEV_FATAL, 1, 0, "Cannot map RPS BLAST lookup file");

   info->lookup_header = (BlastRPSLookupFileHeader *)lut_mmap->mmp_begin;
   version = info->lookup_header->magic_number; 
   if (version != RPS_MAGIC_NUM && version != RPS_MAGIC_NUM_28) {

      version = Nlm_SwitchUint4(version);
      if (version == RPS_MAGIC_NUM || version == RPS_MAGIC_NUM_28) {
         ErrPostEx(SEV_FATAL, 1, 0, "RPS BLAST lookup file was created "
                           "on an incompatible platform");
      }
      else {
         ErrPostEx(SEV_FATAL, 1, 0, "RPS BLAST lookup file is corrupt");
      }
   }

   sprintf(filename, "%s.rps", (char *)pathname);
   pssm_mmap = Nlm_MemMapInit(filename);
   if (pssm_mmap == NULL)
      ErrPostEx(SEV_FATAL, 1, 0, "Cannot map RPS BLAST profile file");

   info->profile_header = (BlastRPSProfileHeader *)pssm_mmap->mmp_begin;
   version = info->profile_header->magic_number;
   if (version != RPS_MAGIC_NUM && version != RPS_MAGIC_NUM_28) {

      version = Nlm_SwitchUint4(version);
      if (version == RPS_MAGIC_NUM || version == RPS_MAGIC_NUM_28) {
         ErrPostEx(SEV_FATAL, 1, 0, "RPS BLAST profile file was created "
                           "on an incompatible platform");
      }
      else {
         ErrPostEx(SEV_FATAL, 1, 0, "RPS BLAST profile file is corrupt");
      }
   }

   num_db_seqs = info->profile_header->num_profiles;

   sprintf(filename, "%s.aux", (char *)pathname);
   auxfile = FileOpen(filename, "r");
   if (auxfile == NULL)
      ErrPostEx(SEV_FATAL, 1, 0,"Cannot open RPS BLAST parameters file");

   fscanf(auxfile, "%s", buffer);
   info->aux_info.orig_score_matrix = strdup(buffer);
   fscanf(auxfile, "%d", &info->aux_info.gap_open_penalty);
   fscanf(auxfile, "%d", &info->aux_info.gap_extend_penalty);
   fscanf(auxfile, "%le", &info->aux_info.ungapped_k);
   fscanf(auxfile, "%le", &info->aux_info.ungapped_h);
   fscanf(auxfile, "%d", &info->aux_info.max_db_seq_length);
   fscanf(auxfile, "%d", &info->aux_info.db_length);
   fscanf(auxfile, "%lf", &info->aux_info.scale_factor);

   info->aux_info.karlin_k = (double *)malloc(num_db_seqs * sizeof(double));
   for (i = 0; i < num_db_seqs && !feof(auxfile); i++) {
      fscanf(auxfile, "%d", &seq_size); /* not used */
      fscanf(auxfile, "%le", &info->aux_info.karlin_k[i]);
   }

   if (i < num_db_seqs)
      ErrPostEx(SEV_FATAL, 1, 0, "Missing Karlin parameters");

   FileClose(auxfile);
   *ppinfo = info;
   *rps_mmap = lut_mmap;
   *rps_pssm_mmap = pssm_mmap;
   return 0;
}
Esempio n. 16
0
/* -- SSH --
   Create lookup table for the large sequence, that represented
   by all collection of PSSM matrixes and dump this table to disk
   Used by RPS Blast.
*/
Boolean RPSCreateLookupFile(ScoreRow *combinedMatrix, Int4 numProfiles,
                            Int4Ptr seqlens, CharPtr filename, 
                            Nlm_FloatHi scalingFactor)
{
    BlastScoreBlk *sbp;
    FILE *fd;
    Int4  **posMatrix;
    Int4 start, i, header_size, all_length, magicNumber;
    Int4Ptr offsets;
    Int4 num_lookups;
    BlastSeqLoc *lookup_segment=NULL;
    BlastAaLookupTable *lookup;
    LookupTableWrap* lookup_wrap_ptr=NULL;
    LookupTableOptions* lookup_options;
   

    if((fd = FileOpen(filename, "wb")) == NULL)
        return FALSE;
    
    num_lookups = 1; /* Single lookup table for all set */

    all_length = seqlens[numProfiles] - seqlens[0];
    
    posMatrix = MemNew((all_length + 1) * sizeof(Int4 *));
    for (i = 0; i < all_length; i++) {
        posMatrix[i] = (Int4 *) &(combinedMatrix[i][0]);
    }
    
    /* Last row is necessary */
    posMatrix[all_length] = MemNew(sizeof(Int4) * PRO_ALPHABET_SIZE);

    for(i = 0; i < PRO_ALPHABET_SIZE; i++) {
        posMatrix[all_length][i] = -INT2_MAX;
    }

    sbp = BlastScoreBlkNew(BLASTAA_SEQ_CODE, 1);
    RPSPsiMatrixAttach(sbp, posMatrix);
    LookupTableOptionsNew(eBlastTypeBlastp, &lookup_options);
    BLAST_FillLookupTableOptions(lookup_options, eBlastTypePsiBlast, FALSE, 
	(Int4) (myargs[3].floatvalue*scalingFactor), myargs[4].intvalue);


    BlastSeqLocNew(&lookup_segment, 0, all_length);

    /* Need query for psi-blast??  where to put the PSSM? */
    LookupTableWrapInit(NULL, lookup_options, NULL, lookup_segment, sbp, &lookup_wrap_ptr, NULL, NULL);
   
    RPSPsiMatrixDetach(sbp);
    sbp = BlastScoreBlkFree(sbp);
    lookup_options = LookupTableOptionsFree(lookup_options);
    lookup_segment = BlastSeqLocFree(lookup_segment);

    lookup = (BlastAaLookupTable*) lookup_wrap_ptr->lut;

    /* Only Uint4 maximum length for lookup file allowed in current
       implementation */
    header_size = (numProfiles+1)*sizeof(Int4) + 8*sizeof(Int4);
    
    /* Beginning of file will be allocated for lookup offsets */
    fseek(fd, header_size, SEEK_SET);
    
    offsets = MemNew(sizeof(Int4) * (num_lookups + 1));
    

    offsets[0] = ftell(fd);
    
    start = seqlens[0]; /* 0 */
    
    RPSDumpLookupTable(lookup, fd);
    
    i = 1;
    
    offsets[i] = ftell(fd); /* Last offset also recorded */
    
    fseek(fd, 0, SEEK_SET);
    magicNumber = RPS_MAGIC_NUMBER;
    FileWrite(&magicNumber, sizeof(Int4), 1, fd); /* header[0] */
    FileWrite(&num_lookups, sizeof(Int4), 1, fd); /* header[1] */
    FileWrite(&lookup->neighbor_matches, sizeof(Int4), 1, fd); /* header[2] */
    FileWrite(&lookup->neighbor_matches, sizeof(Int4), 1, fd); /* header[3] */
    FileWrite(&lookup->overflow_size, sizeof(Int4), 1, fd); /* header[4] */
    
    /* Now writing recorded offsets in the beginning of the file */
    
    fseek(fd, 8*sizeof(Int4), SEEK_SET);
    FileWrite(offsets, sizeof(Int4), num_lookups + 1, fd);
    FileClose(fd);
    
    /* Final memory cleenup */
    
    MemFree(posMatrix[all_length]);
    MemFree(posMatrix);

    return TRUE;
}
Esempio n. 17
0
CEncoderVorbis::~CEncoderVorbis()
{
  FileClose();
}
Esempio n. 18
0
Int2  Main(void)

{
    
    Char *profilesFileName; /*file name for list of profile file names*/
    Char sequencesFileName[MAX_NAME_LENGTH]; /*file anme for list of sequence file names*/
    Char matrixFileName[MAX_NAME_LENGTH]; /*file name for list of matrix file names*/
    Char auxFileName[MAX_NAME_LENGTH]; /*file name for file containing auxiliary information*/
    Char bigFileName[MAX_NAME_LENGTH]; /*file name to store byte-encoded coalesced matrix*/
    Char lookupName[MAX_NAME_LENGTH]; /*file name to store precalculated lookup table */
    FILE *auxiliaryfp; /*file descriptor for matrix auxiliary file*/
    FILE *sequencesfp; /*files descriptor for file containing list of sequences*/
    FILE *matrixnamefp; /*file descriptor for file containing matrix names*/
    FILE *bigmatrixfile; /*file descriptor for file containing single big matrix*/
    Int4 numProfiles; /*number of profiles*/
    Int4 totalProfileLength; /*total length of all profiles*/
    ScoreRow *combinedMatrix; /*combined matrix for all profiles*/
    Char *directoryPrefix; /*directory where profile library is kept, used
                             to reach other directories indirectly*/

    Int4Ptr seqlens;
    Nlm_FloatHi scalingFactor; /*matrix scale to skip over in reading*/

    if (! GetArgs ("copymatrices", NUMARG, myargs)) {
        return (1);
    }
    
    if ((Boolean) myargs[1].intvalue) {
        IMPALAPrintHelp(FALSE, 80, "copymat", stdout);
        return(1);
    }
    profilesFileName = myargs[0].strvalue;
    directoryPrefix = (Char *) MemNew(MAX_NAME_LENGTH *sizeof(char));
    strcpy(directoryPrefix,profilesFileName);
    
    impalaMakeFileNames(profilesFileName, auxFileName, bigFileName,
                        sequencesFileName, matrixFileName, NULL, 
                        directoryPrefix);
    
    if ((matrixnamefp = FileOpen(matrixFileName, "r")) == NULL) {
        ErrPostEx(SEV_FATAL, 1, 0, "copymatrices: Unable to open file with matrix file names %s\n", matrixFileName);
        return (1);
    }
    
    if ((sequencesfp = FileOpen(sequencesFileName, "r")) == NULL) {
        ErrPostEx(SEV_FATAL, 1, 0, "copymatrices: Unable to open file with sequence file names %s\n", sequencesFileName);
        return (1);
    }
    
    if ((auxiliaryfp = FileOpen(auxFileName, "r")) == NULL) {
        ErrPostEx(SEV_FATAL, 1, 0, "profiles: Unable to open auxiliary file %s\n", auxFileName);
        return (1);
    }

    /* -- SSH -- Name of matrix file depends on program - RPS or Impala */
    
    if((Boolean) myargs[2].intvalue) {
        sprintf(bigFileName, "%s.rps", profilesFileName);
    }
    
    if ((bigmatrixfile = FileOpen(bigFileName, "wb")) == NULL) {
        ErrPostEx(SEV_FATAL, 1, 0, "rps-blast: Unable to open big matrix file %s\n", bigFileName);
        return (1);
    }
    
    numProfiles =  countProfiles(sequencesfp, matrixnamefp);
    totalProfileLength = findTotalLength(auxiliaryfp, numProfiles, 
                                         &scalingFactor);
    
    /* -- SSH -- Additional line in matrix with -INT2_MAX values */
    if((Boolean) myargs[2].intvalue) {
        totalProfileLength += numProfiles;
    }

    combinedMatrix = allocateMatrix(totalProfileLength);
    if (NULL == combinedMatrix) {
        ErrPostEx(SEV_FATAL, 1, 0, "copymatrices: Unable to allocate matrix with%d rows\n", totalProfileLength);
        return (1);
        
    }
    /* -- SSH -- RPS Blast data */
    if ((Boolean) myargs[2].intvalue) {
        seqlens = (Int4Ptr) MemNew((numProfiles +1) * sizeof(Int4));
    } else {
        seqlens = NULL;
    }
    
    readAllMatrices(matrixnamefp, combinedMatrix, numProfiles,
                    directoryPrefix, seqlens);
    
    /* -- SSH -- For RPS Blast additional info will be added to the file */
    if ((Boolean) myargs[2].intvalue) {
        Int4 magicNumber = RPS_MAGIC_NUMBER;
        FileWrite(&magicNumber, sizeof(Int4), 1, bigmatrixfile);
        FileWrite(&numProfiles, sizeof(Int4), 1, bigmatrixfile);
        FileWrite(seqlens, sizeof(Int4), numProfiles + 1, bigmatrixfile);
        
        sprintf(lookupName, "%s.loo", profilesFileName);
        RPSCreateLookupFile(combinedMatrix, numProfiles, seqlens, lookupName,
                            scalingFactor);

        if(!RPSConcatSequences(sequencesfp, profilesFileName)) {
            ErrPostEx(SEV_ERROR, 0,0, "Failure to concatenate sequences");
            return 1;
        }
        
    }
    
    FileWrite((void *) combinedMatrix[0], sizeof(ScoreRow), 
              (size_t) totalProfileLength, bigmatrixfile);
    freeMatrix(combinedMatrix); 
    FileClose(bigmatrixfile);
    FileClose(matrixnamefp);
    FileClose(sequencesfp);
    FileClose(auxiliaryfp);
    return 0;
}
Esempio n. 19
0
static void
ResourceOwnerReleaseInternal(ResourceOwner owner,
							 ResourceReleasePhase phase,
							 bool isCommit,
							 bool isTopLevel)
{
	ResourceOwner child;
	ResourceOwner save;
	ResourceReleaseCallbackItem *item;
	Datum		foundres;

	/* Recurse to handle descendants */
	for (child = owner->firstchild; child != NULL; child = child->nextchild)
		ResourceOwnerReleaseInternal(child, phase, isCommit, isTopLevel);

	/*
	 * Make CurrentResourceOwner point to me, so that ReleaseBuffer etc don't
	 * get confused.  We needn't PG_TRY here because the outermost level will
	 * fix it on error abort.
	 */
	save = CurrentResourceOwner;
	CurrentResourceOwner = owner;

	if (phase == RESOURCE_RELEASE_BEFORE_LOCKS)
	{
		/*
		 * Release buffer pins.  Note that ReleaseBuffer will remove the
		 * buffer entry from our array, so we just have to iterate till there
		 * are none.
		 *
		 * During a commit, there shouldn't be any remaining pins --- that
		 * would indicate failure to clean up the executor correctly --- so
		 * issue warnings.  In the abort case, just clean up quietly.
		 */
		while (ResourceArrayGetAny(&(owner->bufferarr), &foundres))
		{
			Buffer		res = DatumGetBuffer(foundres);

			if (isCommit)
				PrintBufferLeakWarning(res);
			ReleaseBuffer(res);
		}

		/* Ditto for relcache references */
		while (ResourceArrayGetAny(&(owner->relrefarr), &foundres))
		{
			Relation	res = (Relation) DatumGetPointer(foundres);

			if (isCommit)
				PrintRelCacheLeakWarning(res);
			RelationClose(res);
		}

		/* Ditto for dynamic shared memory segments */
		while (ResourceArrayGetAny(&(owner->dsmarr), &foundres))
		{
			dsm_segment *res = (dsm_segment *) DatumGetPointer(foundres);

			if (isCommit)
				PrintDSMLeakWarning(res);
			dsm_detach(res);
		}
	}
	else if (phase == RESOURCE_RELEASE_LOCKS)
	{
		if (isTopLevel)
		{
			/*
			 * For a top-level xact we are going to release all locks (or at
			 * least all non-session locks), so just do a single lmgr call at
			 * the top of the recursion.
			 */
			if (owner == TopTransactionResourceOwner)
			{
				ProcReleaseLocks(isCommit);
				ReleasePredicateLocks(isCommit);
			}
		}
		else
		{
			/*
			 * Release locks retail.  Note that if we are committing a
			 * subtransaction, we do NOT release its locks yet, but transfer
			 * them to the parent.
			 */
			LOCALLOCK **locks;
			int			nlocks;

			Assert(owner->parent != NULL);

			/*
			 * Pass the list of locks owned by this resource owner to the lock
			 * manager, unless it has overflowed.
			 */
			if (owner->nlocks > MAX_RESOWNER_LOCKS)
			{
				locks = NULL;
				nlocks = 0;
			}
			else
			{
				locks = owner->locks;
				nlocks = owner->nlocks;
			}

			if (isCommit)
				LockReassignCurrentOwner(locks, nlocks);
			else
				LockReleaseCurrentOwner(locks, nlocks);
		}
	}
	else if (phase == RESOURCE_RELEASE_AFTER_LOCKS)
	{
		/*
		 * Release catcache references.  Note that ReleaseCatCache will remove
		 * the catref entry from our array, so we just have to iterate till
		 * there are none.
		 *
		 * As with buffer pins, warn if any are left at commit time.
		 */
		while (ResourceArrayGetAny(&(owner->catrefarr), &foundres))
		{
			HeapTuple	res = (HeapTuple) DatumGetPointer(foundres);

			if (isCommit)
				PrintCatCacheLeakWarning(res);
			ReleaseCatCache(res);
		}

		/* Ditto for catcache lists */
		while (ResourceArrayGetAny(&(owner->catlistrefarr), &foundres))
		{
			CatCList   *res = (CatCList *) DatumGetPointer(foundres);

			if (isCommit)
				PrintCatCacheListLeakWarning(res);
			ReleaseCatCacheList(res);
		}

		/* Ditto for plancache references */
		while (ResourceArrayGetAny(&(owner->planrefarr), &foundres))
		{
			CachedPlan *res = (CachedPlan *) DatumGetPointer(foundres);

			if (isCommit)
				PrintPlanCacheLeakWarning(res);
			ReleaseCachedPlan(res, true);
		}

		/* Ditto for tupdesc references */
		while (ResourceArrayGetAny(&(owner->tupdescarr), &foundres))
		{
			TupleDesc	res = (TupleDesc) DatumGetPointer(foundres);

			if (isCommit)
				PrintTupleDescLeakWarning(res);
			DecrTupleDescRefCount(res);
		}

		/* Ditto for snapshot references */
		while (ResourceArrayGetAny(&(owner->snapshotarr), &foundres))
		{
			Snapshot	res = (Snapshot) DatumGetPointer(foundres);

			if (isCommit)
				PrintSnapshotLeakWarning(res);
			UnregisterSnapshot(res);
		}

		/* Ditto for temporary files */
		while (ResourceArrayGetAny(&(owner->filearr), &foundres))
		{
			File		res = DatumGetFile(foundres);

			if (isCommit)
				PrintFileLeakWarning(res);
			FileClose(res);
		}
	}

	/* Let add-on modules get a chance too */
	for (item = ResourceRelease_callbacks; item; item = item->next)
		(*item->callback) (phase, isCommit, isTopLevel, item->arg);

	CurrentResourceOwner = save;
}
Esempio n. 20
0
static Int4
BL2SEQ_GetSequences(Boolean seq1_is_na, Boolean seq2_is_na, BioseqPtr *query_bsp, BioseqPtr *subject_bsp, 
    SeqEntryPtr *sep, SeqEntryPtr *sep1, SeqLocPtr *lcase_mask, Boolean believe_query)
{
        Boolean entrez_lookup = (Boolean) myargs[ARG_ACCN].intvalue;
        char *query_accver = NULL, *subject_accver = NULL;  /* Used if entrez_lookup. */
	char *blast_inputfile = NULL, *blast_inputfile1 = NULL;  /* Used if FASTA read. */
        
        if (entrez_lookup) {
           query_accver = myargs [ARG_QUERY].strvalue;
           subject_accver = myargs [ARG_SUBJECT].strvalue;
        } else {
           blast_inputfile = myargs [ARG_QUERY].strvalue;
           blast_inputfile1 = myargs [ARG_SUBJECT].strvalue;
        }

        if (entrez_lookup) {
           *query_bsp = BioseqFromAccession(query_accver, seq1_is_na);
        } else {
           FILE *infp;
	   if ((infp = FileOpen(blast_inputfile, "r")) == NULL)
	   {
		ErrPostEx(SEV_FATAL, 1, 0, "blast: Unable to open input file %s\n", blast_inputfile);
		return FALSE;
	   }
           if (myargs[ARG_LCASE].intvalue)
              *sep = FastaToSeqEntryForDb(infp, seq1_is_na, NULL, 
                                         believe_query, NULL, NULL, 
                                         lcase_mask);
           else
              *sep = FastaToSeqEntryEx(infp, seq1_is_na, NULL, believe_query);

           FileClose(infp);

           if (*sep != NULL) {
              *query_bsp = NULL;
              if (seq1_is_na)
                 SeqEntryExplore(*sep, query_bsp, FindNuc);
              else
                 SeqEntryExplore(*sep, query_bsp, FindProt);

           }
        }
        if (*query_bsp == NULL) {
           ErrPostEx(SEV_FATAL, 1, 0, "Unable to obtain bioseq\n");
           return FALSE;
        }

        if (entrez_lookup) {
           *subject_bsp = 
              BioseqFromAccession(subject_accver, seq2_is_na);
        } else {
           FILE *infp1;
	   if ((infp1 = FileOpen(blast_inputfile1, "r")) == NULL)
	   {
		ErrPostEx(SEV_FATAL, 1, 0, "blast: Unable to open input file %s\n", blast_inputfile1);
		return FALSE;
	   }
           *sep1 = FastaToSeqEntryEx(infp1, seq2_is_na, NULL, FALSE);

           FileClose(infp1);

           if (*sep1 != NULL) {
              *subject_bsp = NULL;
              if (seq2_is_na)
                 SeqEntryExplore(*sep1, subject_bsp, FindNuc);
              else
                 SeqEntryExplore(*sep1, subject_bsp, FindProt);
              
           }
        }
        
        if (*subject_bsp == NULL) {
           ErrPostEx(SEV_FATAL, 1, 0, "Unable to obtain bioseq\n");
           return FALSE;
        }

        return TRUE;
}
Esempio n. 21
0
void __fastcall TFormSim::Button6Click(TObject *Sender)
{
int file;
file = FileOpen("D:\\smart-environment-simulator20140308\\Bin\\new.txt", fmOpenWrite);
if(frmMainFrame->num>0){
    for(int i=0;i<frmMainFrame->route1->Count;i++){
        FCMsNode*my = (FCMsNode*)frmMainFrame->route1->Items[i];
        if(i==frmMainFrame->route1->Count-1)
        {
            FileSeek(file,0,2);
            String s = my->m_strName;
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
            FileWrite(file, "\r\n",sizeof("\r\n"));
        }
        else
        {
            FileSeek(file,0,2);
            String s = my->m_strName;
            s = s+"->";
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
        }
}
}
if(frmMainFrame->num>1){
    for(int i=0;i<frmMainFrame->route2->Count;i++){
        FCMsNode*my = (FCMsNode*)frmMainFrame->route2->Items[i];
        if(i==frmMainFrame->route2->Count-1){
            FileSeek(file,0,2);
            String s = my->m_strName;
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
            FileWrite(file, "\r\n",sizeof("\r\n"));
        }
        else{
            FileSeek(file,0,2);
            String s = my->m_strName;
            s = s+"->";
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
        }
}
}
if(frmMainFrame->num>2){
    for(int i=0;i<frmMainFrame->route3->Count;i++){
        FCMsNode*my = (FCMsNode*)frmMainFrame->route3->Items[i];
        if(i==frmMainFrame->route3->Count-1){
            FileSeek(file,0,2);
            String s = my->m_strName;
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
            FileWrite(file, "\r\n",sizeof("\r\n"));
        }
        else{
            FileSeek(file,0,2);
            String s = my->m_strName;
            s = s+"->";
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
        }
}
}
if(frmMainFrame->num>3){
    for(int i=0;i<frmMainFrame->route4->Count;i++){
        FCMsNode*my = (FCMsNode*)frmMainFrame->route4->Items[i];
        if(i==frmMainFrame->route4->Count-1){
            FileSeek(file,0,2);
            String s = my->m_strName;
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
            FileWrite(file, "\r\n",sizeof("\r\n"));
        }
        else{
            FileSeek(file,0,2);
            String s = my->m_strName;
            s = s+"->";
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
        }
}
}
//**************By WYP at 20150426**********************************
if(frmMainFrame->num>4){
    for(int i=0;i<frmMainFrame->route5->Count;i++){
        FCMsNode*my = (FCMsNode*)frmMainFrame->route5->Items[i];
        if(i==frmMainFrame->route5->Count-1){
            FileSeek(file,0,2);
            String s = my->m_strName;
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
            FileWrite(file, "\r\n",sizeof("\r\n"));
        }
        else{
            FileSeek(file,0,2);
            String s = my->m_strName;
            s = s+"->";
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
        }
}
}
if(frmMainFrame->num>5){
    for(int i=0;i<frmMainFrame->route6->Count;i++){
        FCMsNode*my = (FCMsNode*)frmMainFrame->route6->Items[i];
        if(i==frmMainFrame->route6->Count-1){
            FileSeek(file,0,2);
            String s = my->m_strName;
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
            FileWrite(file, "\r\n",sizeof("\r\n"));
        }
        else{
            FileSeek(file,0,2);
            String s = my->m_strName;
            s = s+"->";
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
        }
}
}
if(frmMainFrame->num>6){
    for(int i=0;i<frmMainFrame->route7->Count;i++){
        FCMsNode*my = (FCMsNode*)frmMainFrame->route7->Items[i];
        if(i==frmMainFrame->route7->Count-1){
            FileSeek(file,0,2);
            String s = my->m_strName;
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
            FileWrite(file, "\r\n",sizeof("\r\n"));
        }
        else{
            FileSeek(file,0,2);
            String s = my->m_strName;
            s = s+"->";
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
        }
}
}
if(frmMainFrame->num>7){
    for(int i=0;i<frmMainFrame->route8->Count;i++){
        FCMsNode*my = (FCMsNode*)frmMainFrame->route8->Items[i];
        if(i==frmMainFrame->route8->Count-1){
            FileSeek(file,0,2);
            String s = my->m_strName;
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
            FileWrite(file, "\r\n",sizeof("\r\n"));
        }
        else{
            FileSeek(file,0,2);
            String s = my->m_strName;
            s = s+"->";
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
        }
}
}
if(frmMainFrame->num>8){
    for(int i=0;i<frmMainFrame->route9->Count;i++){
        FCMsNode*my = (FCMsNode*)frmMainFrame->route9->Items[i];
        if(i==frmMainFrame->route9->Count-1){
            FileSeek(file,0,2);
            String s = my->m_strName;
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
            FileWrite(file, "\r\n",sizeof("\r\n"));
        }
        else{
            FileSeek(file,0,2);
            String s = my->m_strName;
            s = s+"->";
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
        }
}
}
//******************************************************************
FileClose(file);
}
Esempio n. 22
0
Int2 Main_old (void)
 
{
	
	AsnIoPtr aip;
	BioseqPtr fake_bsp = NULL, fake_subject_bsp = NULL, query_bsp = NULL, 
                  subject_bsp = NULL;
        BioseqPtr bsp1, bsp2;
	BLAST_KarlinBlkPtr ka_params=NULL, ka_params_gap=NULL;
	BLAST_OptionsBlkPtr options=NULL;
	Boolean seq1_is_na, seq2_is_na;
	CharPtr params_buffer=NULL;
        DbtagPtr        dbtagptr;
	Uint1 align_type;
	Uint4 align_options;
	SeqAlignPtr  seqalign;
        SeqAnnotPtr seqannot;
	SeqEntryPtr sep = NULL, sep1 = NULL;
	CharPtr program_name, blast_outputfile;
	FILE *outfp;
	ValNodePtr  mask_loc, mask_loc_start, vnp, other_returns=NULL, error_returns=NULL;
	BLAST_MatrixPtr matrix;
        Int4Ptr PNTR txmatrix;
        int (LIBCALLBACK *handle_results)PROTO((VoidPtr search)) = NULL;
        Boolean entrez_lookup = FALSE;
        Boolean html, seqannot_output, believe_query;
        Uint1 tabular_output;
        Boolean gapped_calculation;

        entrez_lookup = (Boolean) myargs[ARG_ACCN].intvalue;
        html = (Boolean) myargs[ARG_HTML].intvalue;
        seqannot_output = (myargs[ARG_ASNOUT].strvalue != NULL);

        blast_outputfile = myargs [ARG_OUT].strvalue;

	program_name = StringSave(myargs[ARG_PROGRAM].strvalue);
	if (StringCmp(program_name, "blastn") && 
	    StringCmp(program_name, "blastp") && 
	    StringCmp(program_name, "blastx") && 
	    StringCmp(program_name, "tblastn") && 
	    StringCmp(program_name, "tblastx")) {
		ErrPostEx(SEV_FATAL, 1, 0, "Program name must be blastn, blastp, blastx, tblastn or tblastx\n");
		return (1);
	}
	   
	align_type = BlastGetTypes(program_name, &seq1_is_na, &seq2_is_na);

	if ((outfp = FileOpen(blast_outputfile, "w")) == NULL)
	{
		ErrPostEx(SEV_FATAL, 1, 0, "blast: Unable to open output file %s\n", blast_outputfile);
		return (1);
	}

        gapped_calculation = (Boolean) myargs[ARG_GAPPED].intvalue;
        believe_query = (seqannot_output || entrez_lookup); 

        options = BLASTOptionNewEx(program_name, gapped_calculation,
                                   (Boolean) myargs[ARG_USEMEGABLAST].intvalue);

        if (BL2SEQ_GetSequences(seq1_is_na, seq2_is_na, &query_bsp, &subject_bsp,
                                &sep, &sep1, &(options->query_lcase_mask), 
                                believe_query) == FALSE)
        {
            ErrPostEx(SEV_FATAL, 1, 0, "blast: Unable to get sequences");
            return (1);
        }

        if (!entrez_lookup) {
            if (!believe_query)
                fake_bsp = BlastMakeFakeBioseq(query_bsp, NULL);
            
            fake_subject_bsp = BioseqNew();
            fake_subject_bsp->descr = subject_bsp->descr;
            fake_subject_bsp->repr = subject_bsp->repr;
            fake_subject_bsp->mol = subject_bsp->mol;
            fake_subject_bsp->length = subject_bsp->length;
            fake_subject_bsp->seq_data = subject_bsp->seq_data;
            fake_subject_bsp->seq_data_type = subject_bsp->seq_data_type;
            dbtagptr = DbtagNew();
            dbtagptr->db = StringSave("BL_ORD_ID");
            dbtagptr->tag = ObjectIdNew();

            if (BioseqGetTitle(subject_bsp) != NULL)
              dbtagptr->tag->str = StringSave(BioseqGetTitle(subject_bsp));
            else
              dbtagptr->tag->str = StringSave("No definition line found");

            ValNodeAddPointer(&fake_subject_bsp->id, SEQID_GENERAL, dbtagptr);
            bsp1 = (believe_query ? query_bsp : fake_bsp);
            bsp2 = fake_subject_bsp;
        } else {
            bsp1 = query_bsp;
            bsp2 = subject_bsp;
        }

        tabular_output = (Uint1) myargs[ARG_FORMAT].intvalue; 


    	if (myargs[ARG_SEARCHSP].floatvalue)
           options->searchsp_eff = (Nlm_FloatHi) myargs[ARG_SEARCHSP].floatvalue;


	options->filter_string = StringSave(myargs[ARG_FILTER].strvalue);
	options->expect_value  = (Nlm_FloatHi) myargs [ARG_EVALUE].floatvalue;

        if (StringICmp("blastn", program_name) == 0)
        {
                options->penalty = myargs[ARG_MISMATCH].intvalue;
                options->reward = myargs[ARG_MATCH].intvalue;
        }

	options->db_length = (Int8) myargs[ARG_DBSIZE].floatvalue;

	options->discontinuous = FALSE;

        if (myargs[ARG_XDROP].intvalue != 0)
	{
               options->gap_x_dropoff = myargs[ARG_XDROP].intvalue;
	}
        if (myargs[ARG_WORDSIZE].intvalue != 0)
               options->wordsize = (Int2) myargs[ARG_WORDSIZE].intvalue;

	if (options->is_megablast_search) {
	   options->cutoff_s2 = options->wordsize*options->reward;
        }
	options->matrix = MemFree(options->matrix);
        BLASTOptionSetGapParams(options, myargs[ARG_MATRIX].strvalue, 0, 0); 

        if (myargs[ARG_GAPOPEN].intvalue != -1)
              options->gap_open = myargs[ARG_GAPOPEN].intvalue;
        if (myargs[ARG_GAPEXT].intvalue != -1)
               options->gap_extend = myargs[ARG_GAPEXT].intvalue;

	options->strand_option = myargs[ARG_STRAND].intvalue;

        /* Input longest intron length is in nucleotide scale; in the lower 
           level code it will be used in protein scale */
        if (myargs[ARG_INTRON].intvalue > 0) 
           options->longest_intron = myargs[ARG_INTRON].intvalue;


        if (!myargs[ARG_LOC1].strvalue && !myargs[ARG_LOC2].strvalue) {
           seqalign = BlastTwoSequencesWithCallback(bsp1, bsp2, program_name, 
              options, &other_returns, &error_returns, handle_results);
        } else {
            SeqLocPtr slp1=NULL, slp2=NULL;
            if (BL2SEQ_MakeSeqLoc(bsp1, bsp2, &slp1, &slp2, options->strand_option) == FALSE)
                return 1;
           seqalign = BlastTwoSequencesByLocWithCallback(slp1, slp2, program_name, options, &other_returns, &error_returns, handle_results, NULL);
           SeqLocFree(slp1);
           SeqLocFree(slp2);
        }

        if (error_returns) {
           BlastErrorPrint(error_returns);
           for (vnp = error_returns; vnp; vnp = vnp->next) {
              BlastDestroyErrorMessage((BlastErrorMsgPtr)vnp->data.ptrvalue);
           }
           ValNodeFree(error_returns);
        }
       
        ka_params = NULL;
        ka_params_gap = NULL;
        params_buffer = NULL;
        mask_loc = NULL;
        matrix = NULL;
        txmatrix = NULL;
        for (vnp=other_returns; vnp; vnp = vnp->next) {
           switch (vnp->choice) {
           case TXKABLK_NOGAP:
              ka_params = vnp->data.ptrvalue;
              break;
           case TXKABLK_GAP:
              ka_params_gap = vnp->data.ptrvalue;
              break;
           case TXPARAMETERS:
              params_buffer = vnp->data.ptrvalue;
              break;
           case TXMATRIX:
              matrix = vnp->data.ptrvalue;
              if (matrix && !tabular_output)
                 txmatrix = BlastMatrixToTxMatrix(matrix);
              break;
           case SEQLOC_MASKING_NOTSET:
           case SEQLOC_MASKING_PLUS1:
           case SEQLOC_MASKING_PLUS2:
           case SEQLOC_MASKING_PLUS3:
           case SEQLOC_MASKING_MINUS1:
           case SEQLOC_MASKING_MINUS2:
           case SEQLOC_MASKING_MINUS3:
              ValNodeAddPointer(&mask_loc, vnp->choice, vnp->data.ptrvalue);
              break;
           default:
              break;
           }
        }	
        if (!tabular_output || seqannot_output) {
           align_options = 0;
           align_options += TXALIGN_MATRIX_VAL;
           align_options += TXALIGN_SHOW_QS;
           align_options += TXALIGN_COMPRESS;
           align_options += TXALIGN_END_NUM;
           if (StringICmp("blastx", program_name) == 0) {
              align_options += TXALIGN_BLASTX_SPECIAL;
           }
           
           if (html)
              align_options += TXALIGN_HTML;

           seqannot = SeqAnnotNew();
           seqannot->type = 2;
           AddAlignInfoToSeqAnnot(seqannot, align_type);
           seqannot->data = seqalign;
           aip = NULL;
           if (seqannot_output)
              aip = AsnIoOpen (myargs[ARG_ASNOUT].strvalue,"w");
           
           if (aip && seqannot) {
              SeqAnnotAsnWrite((SeqAnnotPtr) seqannot, aip, NULL);
              AsnIoReset(aip);
              aip = AsnIoClose(aip);
           }
        }
        if (!tabular_output) {    
           AcknowledgeBlastQuery(query_bsp, 70, outfp, believe_query, html);
           ShowTextAlignFromAnnot(seqannot, 60, outfp, NULL, NULL, align_options, txmatrix, mask_loc, FormatScoreFunc);
           
           seqannot = SeqAnnotFree(seqannot);
           if (txmatrix)
              txmatrix = TxMatrixDestruct(txmatrix);
           init_buff_ex(85);
        
           if (ka_params) {
              PrintKAParameters(ka_params->Lambda, ka_params->K, ka_params->H, 70, outfp, FALSE);
           }
        
           if (ka_params_gap) {
              PrintKAParameters(ka_params_gap->Lambda, ka_params_gap->K, ka_params_gap->H, 70, outfp, TRUE);
           }
        
           PrintTildeSepLines(params_buffer, 70, outfp);
           free_buff();
        } else {
           PrintTabularOutputHeader(NULL, query_bsp, NULL, 
              program_name, 0, believe_query, outfp);

           BlastPrintTabulatedResults(seqalign, query_bsp, NULL, 
              1, program_name, !gapped_calculation,
              believe_query, 0, 0, outfp, FALSE);
           SeqAlignSetFree(seqalign);
        }

        matrix = BLAST_MatrixDestruct(matrix);
        MemFree(ka_params);
        MemFree(ka_params_gap);
        MemFree(params_buffer);
    
        mask_loc_start = mask_loc;
        while (mask_loc) {
           SeqLocSetFree(mask_loc->data.ptrvalue);
           mask_loc = mask_loc->next;
        }
        ValNodeFree(mask_loc_start);
        
        fake_bsp = BlastDeleteFakeBioseq(fake_bsp);

        other_returns = ValNodeFree(other_returns);
    options->query_lcase_mask = SeqLocSetFree(options->query_lcase_mask);
	options = BLASTOptionDelete(options);
	MemFree(program_name);
	FileClose(outfp);

        if (entrez_lookup) {
           BioseqFree(query_bsp);
           BioseqFree(subject_bsp);
        } else {
           SeqEntryFree(sep);
           SeqEntryFree(sep1);
        }
	return 0;
}
Esempio n. 23
0
Int2 Main(void)
{
	AsnIoPtr aip;
	FILE * aa = NULL, * na = NULL, * ql = NULL;
	SeqEntryPtr sep;
	SeqSubmitPtr ssp;
	AsnTypePtr atp, atp2;
	AsnModulePtr amp;
	Uint1 group_segs = 0;
	Boolean limit_to_genbank,
		make_dna,
		make_protein,
		make_quality,
		far_quality,
		do_it;
	

					/* check command line arguments */

	if ( ! GetArgs("asn2fast",NUMARG, myargs))
		return 1;

					/* load the sequence alphabets  */
					/* (and sequence parse trees)   */
	if (! SeqEntryLoad())
	{
		ErrShow();
		return 1;
	}
				    /* get pointer to all loaded ASN.1 modules */
	amp = AsnAllModPtr();
	if (amp == NULL)
	{
		ErrShow();
		return 1;
	}

	if (myargs[11].intvalue) {
		if (! SubmitAsnLoad())
			Message(MSG_FATAL, "Unable to load parse trees.");
		
		atp2 = AsnFind("Seq-submit");
		if (atp2 == NULL)
			Message(MSG_FATAL, "Unable to find Seq-submit");
		atp = AsnFind("Seq-submit");
		if (atp == NULL)
			Message(MSG_FATAL, "Unable to find Seq-submit");

	} else {
		atp = AsnFind("Bioseq-set"); /* get the initial type pointers */
		if (atp == NULL)
		{
			ErrShow();
			return 1;
		}
	
		atp2 = AsnFind("Bioseq-set.seq-set.E");
		if (atp2 == NULL)
		{
			ErrShow();
			return 1;
		}
	}

	make_protein = (Boolean)(myargs[7].intvalue);
	make_dna = (Boolean)(myargs[8].intvalue);
	make_quality = (Boolean)(myargs[12].intvalue);
	far_quality = (Boolean)(myargs[14].intvalue);

					/* open the ASN.1 input file in the right mode */

	if ((aip = AsnIoOpen (myargs[0].strvalue, myargs[2].intvalue?"rb":"r"))
          == NULL)
	{
		ErrShow();
		return 1;
	}

				  				/* open the output file */

	if ((myargs[3].strvalue != NULL) && (make_protein))
	{
		if ( (aa = FileOpen (myargs[3].strvalue, "w")) == NULL)
		{
			ErrShow();
			return 1;
		}
	}

	if ((myargs[4].strvalue != NULL) && (make_dna))
	{
		if ( (na = FileOpen (myargs[4].strvalue, "w")) == NULL)
		{
			ErrShow();
			return 1;
		}
	}

	if ((myargs[13].strvalue != NULL) && (make_quality))
	{
		if ( (ql = FileOpen (myargs[13].strvalue, "w")) == NULL)
		{
			ErrShow();
			return 1;
		}
	}

                                /* log errors instead of die */
    if (myargs[5].strvalue != NULL)
    {
        if (! ErrSetLog (myargs[5].strvalue))
            ErrShow();
        else
            ErrSetOpts (ERR_CONTINUE, ERR_LOG_ON);
   }

	if (myargs[6].intvalue)  /* combine segmented seqs */
	{
		group_segs = 1;
		if (myargs[10].intvalue)
			group_segs = 3;       /* and instantiate virtuals */
	}

	limit_to_genbank = (Boolean)(myargs[9].intvalue);

	if (myargs [15].intvalue) {
		ID1BioseqFetchEnable ("asn2fast", FALSE);
	}
	if (myargs [16].intvalue) {
		LocalSeqFetchInit (FALSE);
	}

	if ( myargs[1].intvalue)   /* read one Seq-entry */
	{

		sep = SeqEntryAsnRead(aip, NULL);
		do_it = TRUE;
		if (limit_to_genbank)
			do_it = CheckIsGenBank(sep);
		if (do_it)
		{
			if (make_protein)
				SeqEntrysToFasta(sep, aa, FALSE, group_segs);
			if (make_dna)
				SeqEntrysToFasta(sep, na, TRUE, group_segs);
			if (make_quality) {
				if (far_quality) {
					SeqEntryExplore (sep, (Pointer) ql, PrintFarQualScores);
				} else {
					SeqEntryExplore (sep, (Pointer) ql, PrintQualScores);
				}
			}
		}
		SeqEntryFree(sep);
	}
	else if ( myargs[11].intvalue)   /* read Seq-submit's */
	{
		while ((atp = AsnReadId(aip, amp, atp)) != NULL)
		{
			if (atp == atp2)    /* top level Seq-entry */
			{
				ssp = SeqSubmitAsnRead(aip, atp);
				if (ssp->datatype == 1)
				{
					sep = (SeqEntryPtr) ssp->data;
					do_it = TRUE;
					if (limit_to_genbank)
						do_it = CheckIsGenBank(sep);
					if (do_it)
					{
						if (make_protein)
							SeqEntrysToFasta(sep, aa, FALSE, group_segs);
						if (make_dna)
							SeqEntrysToFasta(sep, na, TRUE, group_segs);
						if (make_quality) {
							if (far_quality) {
								SeqEntryExplore (sep, (Pointer) ql, PrintFarQualScores);
							} else {
								SeqEntryExplore (sep, (Pointer) ql, PrintQualScores);
							}
						}
					}
				}
				SeqSubmitFree(ssp);
			}
			else
			{
				AsnReadVal(aip, atp, NULL);
			}
		}
	}
	else                      /* read Seq-entry's from a Bioseq-set */
	{
		while ((atp = AsnReadId(aip, amp, atp)) != NULL)
		{
			if (atp == atp2)    /* top level Seq-entry */
			{
				sep = SeqEntryAsnRead(aip, atp);
				do_it = TRUE;
				if (limit_to_genbank)
					do_it = CheckIsGenBank(sep);
				if (do_it)
				{
					if (make_protein)
						SeqEntrysToFasta(sep, aa, FALSE, group_segs);
					if (make_dna)
						SeqEntrysToFasta(sep, na, TRUE, group_segs);
					if (make_quality) {
						if (far_quality) {
							SeqEntryExplore (sep, (Pointer) ql, PrintFarQualScores);
						} else {
							SeqEntryExplore (sep, (Pointer) ql, PrintQualScores);
						}
					}
				}
				SeqEntryFree(sep);
			}
			else
			{
				AsnReadVal(aip, atp, NULL);
			}
		}
	}

	AsnIoClose(aip);
	if (make_protein)
		FileClose(aa);
	if (make_dna)
		FileClose(na);
	if (make_quality)
		FileClose (ql);

	if (myargs [16].intvalue) {
		LocalSeqFetchDisable ();
	}
	if (myargs [15].intvalue) {
		ID1BioseqFetchDisable ();
	}

	return(0);
}
Esempio n. 24
0
ZipFile::~ZipFile()
{
	FileClose();
}
Esempio n. 25
0
FOLDER *CfgReadW(wchar_t *name)
{
	wchar_t tmp[MAX_SIZE];
	wchar_t newfile[MAX_SIZE];
	BUF *b;
	IO *o;
	UINT size;
	void *buf;
	FOLDER *f;
	bool delete_new = false;
	bool binary_file = false;
	bool invalid_file = false;
	UCHAR header[8];
	// Validate arguments
	if (name == NULL)
	{
		return NULL;
	}

	// Generate a new file name
	UniFormat(newfile, sizeof(newfile), L"%s.new", name);
	// Generate a temporary file name
	UniFormat(tmp, sizeof(tmp), L"%s.log", name);

	// Read the new file if it exists
	o = FileOpenW(newfile, false);
	if (o == NULL)
	{
		// Read the temporary file
		o = FileOpenW(tmp, false);
	}
	else
	{
		delete_new = true;
	}
	if (o == NULL)
	{
		// Read the original file if there is no temporary file
		o = FileOpenW(name, false);
	}
	else
	{
		// Read the original file too if the size of temporary file is 0
		if (FileSize(o) == 0)
		{
			invalid_file = true;
		}

		if (invalid_file)
		{
			FileClose(o);
			o = FileOpenW(name, false);
		}
	}
	if (o == NULL)
	{
		// Failed to read
		return NULL;
	}

	// Read into the buffer
	size = FileSize(o);
	buf = Malloc(size);
	FileRead(o, buf, size);
	b = NewBuf();
	WriteBuf(b, buf, size);
	SeekBuf(b, 0, 0);

	// Close the file
	FileClose(o);

	if (delete_new)
	{
		// Delete the new file
		FileDeleteW(newfile);
	}

	// If the beginning 8 character of the buffer is "SEVPN_DB", it is binary file
	ReadBuf(b, header, sizeof(header));
	if (Cmp(header, TAG_BINARY, 8) == 0)
	{
		UCHAR hash1[SHA1_SIZE], hash2[SHA1_SIZE];
		binary_file = true;

		// Check the hash 
		ReadBuf(b, hash1, sizeof(hash1));

		Hash(hash2, ((UCHAR *)b->Buf) + 8 + SHA1_SIZE, b->Size - 8 - SHA1_SIZE, true);

		if (Cmp(hash1, hash2, SHA1_SIZE) != 0)
		{
			// Corrupted file
			invalid_file = true;
			FreeBuf(b);
			return NULL;
		}
	}

	SeekBuf(b, 0, 0);

	if (binary_file)
	{
		SeekBuf(b, 8 + SHA1_SIZE, 0);
	}

	// Convert the buffer into a folder
	if (binary_file == false)
	{
		// Text mode
		f = CfgBufTextToFolder(b);
	}
	else
	{
		// Binary mode
		f = CfgBufBinToFolder(b);
	}

	// Memory release
	Free(buf);
	FreeBuf(b);

	FileDeleteW(newfile);

	return f;
}
Esempio n. 26
0
//=============================================================================
CSaveData::~CSaveData()
{
    PAGED_CODE();

    DPF_ENTER(("[CSaveData::~CSaveData]"));

    // Update the wave header in data file with real file size.
    //
    if(m_pFilePtr)
    {
        m_FileHeader.dwFileSize =
            (DWORD) m_pFilePtr->QuadPart - 2 * sizeof(DWORD);
        m_DataHeader.dwDataLength = (DWORD) m_pFilePtr->QuadPart -
                                     sizeof(m_FileHeader)        -
                                     m_FileHeader.dwFormatLength -
                                     sizeof(m_DataHeader);

        if (STATUS_SUCCESS == KeWaitForSingleObject
            (
                &m_FileSync,
                Executive,
                KernelMode,
                FALSE,
                NULL
            ))
        {
            if (NT_SUCCESS(FileOpen(FALSE)))
            {
                FileWriteHeader();

                FileClose();
            }

            KeReleaseMutex(&m_FileSync, FALSE);
        }
    }

    //frees the work items
   for (int i = 0; i < MAX_WORKER_ITEM_COUNT; i++)
   {
    
       if (m_pWorkItems[i].WorkItem!=NULL)
       {
           IoFreeWorkItem(m_pWorkItems[i].WorkItem);
           m_pWorkItems[i].WorkItem = NULL;
       }
   }

    if (m_waveFormat)
    {
        ExFreePoolWithTag(m_waveFormat, MSVAD_POOLTAG);
    }

    if (m_fFrameUsed)
    {
        ExFreePoolWithTag(m_fFrameUsed, MSVAD_POOLTAG);

        // NOTE : Do not release m_pFilePtr.
    }

    if (m_FileName.Buffer)
    {
        ExFreePoolWithTag(m_FileName.Buffer, MSVAD_POOLTAG);
    }

    if (m_pDataBuffer)
    {
        ExFreePoolWithTag(m_pDataBuffer, MSVAD_POOLTAG);
    }
} // CSaveData
Esempio n. 27
0
void CEtsEodManagerDoc::OnCloseDocument()
{
	FileClose();
	CDocument::OnCloseDocument();
}
Esempio n. 28
0
BOOLEAN ReadInDrugsStats(STR fileName)
{
	HWFILE		hFile;
	UINT32		uiBytesRead;
	UINT32		uiFSize;
	CHAR8 *		lpcBuffer;
	XML_Parser	parser = XML_ParserCreate(NULL);

	drugsParseData pData;

	DebugMsg(TOPIC_JA2, DBG_LEVEL_3, "Loading Drugs.xml" );

	// Open drugs file
	hFile = FileOpen( fileName, FILE_ACCESS_READ, FALSE );
	if ( !hFile )
		return( FALSE );

	uiFSize = FileGetSize(hFile);
	lpcBuffer = (CHAR8 *) MemAlloc(uiFSize+1);

	//Read in block
	if ( !FileRead( hFile, lpcBuffer, uiFSize, &uiBytesRead ) )
	{
		MemFree(lpcBuffer);
		return( FALSE );
	}

	lpcBuffer[uiFSize] = 0; //add a null terminator

	FileClose( hFile );


	XML_SetElementHandler(parser, drugsStartElementHandle, drugsEndElementHandle);
	XML_SetCharacterDataHandler(parser, drugsCharacterDataHandle);


	memset(&pData,0,sizeof(pData));
	pData.curArray = Drug;
	pData.maxArraySize = DRUG_TYPE_MAX;

	XML_SetUserData(parser, &pData);


	if(!XML_Parse(parser, lpcBuffer, uiFSize, TRUE))
	{
		CHAR8 errorBuf[511];

		sprintf(errorBuf, "XML Parser Error in Drugs.xml: %s at line %d", XML_ErrorString(XML_GetErrorCode(parser)), XML_GetCurrentLineNumber(parser));
		LiveMessage(errorBuf);

		MemFree(lpcBuffer);
		return FALSE;
	}

	MemFree(lpcBuffer);


	XML_ParserFree(parser);


	return( TRUE );
}
Esempio n. 29
0
// Download thread
void ViDownloadThread(THREAD *thread, void *param)
{
	VI_INSTALL_DLG *d;
	VI_SETTING_ARCH *a;
	HWND hWnd;
	UINT num_files = 2;
	VI_DOWNLOAD_FILE files[2];
	VI_DOWNLOAD_FILE *f;
	UINT i;
	// Validate arguments
	if (thread == NULL || param == NULL)
	{
		return;
	}

	d = (VI_INSTALL_DLG *)param;
	hWnd = d->hWnd;

	Zero(files, sizeof(files));

	a = ViGetSuitableArchForCpu();

	// File body
	f = &files[0];
	StrCpy(f->SrcPath, sizeof(f->SrcPath), a->Path);

	// Configuration file
	if (IsEmptyStr(setting.SettingPath) == false)
	{
		f = &files[1];
		StrCpy(f->SrcPath, sizeof(f->SrcPath), setting.SettingPath);
	}
	else
	{
		// No configuration file
		num_files = 1;
	}

	for (i = 0;i < num_files;i++)
	{
		bool b = true;

		if (i == 0 && setting.DownloadNotRequired)
		{
			b = false;
		}

		if (b)
		{
			wchar_t tmp[MAX_SIZE];
			IO *dest = NULL;
			VI_FILE *down;
			UINT ret;
			UINT totalsize;
			UINT currentsize;
			wchar_t filename_w[MAX_PATH];

			f = &files[i];
			GetFileNameFromFilePath(f->FileName, sizeof(f->FileName), f->SrcPath);
			MakeSafeFileName(f->FileName, sizeof(f->FileName), f->FileName);

			StrToUni(filename_w, sizeof(filename_w), f->FileName);
			ConbinePathW(f->DestPathW, sizeof(f->DestPathW), MsGetMyTempDirW(), filename_w);

			ViInstallDlgSetPos(hWnd, 0);
			UniFormat(tmp, sizeof(tmp), _U(IDS_DOWNLOADSTART+skip), f->FileName);
			ViInstallDlgSetText(d, hWnd, S_STATUS, tmp);

			down = ViOpenFile(f->SrcPath);
			if (down == NULL)
			{
				MsgBoxEx(hWnd, MB_ICONSTOP, _U(IDS_DOWNLOAD_ERROR+skip), f->FileName);

				ViInstallDlgCancel(hWnd);
				return;
			}

			dest = FileCreateW(f->DestPathW);
			if (dest == NULL)
			{
				MsgBoxEx(hWnd, MB_ICONSTOP, _U(IDS_TEMP_ERROR+skip), f->DestPathW);

				ViCloseFile(down);
				ViInstallDlgCancel(hWnd);
				return;
			}

			totalsize = ViGetFileSize(down);
			currentsize = 0;

			UniFormat(tmp, sizeof(tmp), _U(IDS_DOWNLOADING3+skip), f->FileName);
			ViInstallDlgSetText(d, hWnd, S_STATUS, tmp);

			while (true)
			{
				UINT pos = 0;

				if (d->Halt)
				{
					// User cancel
					FileClose(dest);
					ViCloseFile(down);
					return;
				}

				UniFormat(tmp, sizeof(tmp), _U(IDS_DOWNLOADING3+skip), f->FileName);

				ViInstallDlgSetText(d, hWnd, IDS_DOWNLOADING3+skip, tmp);
				ret = ViReadFile(down, d->Buf, d->BufSize);

				if (ret == INFINITE)
				{
					// Communication error
					MsgBoxEx(hWnd, MB_ICONSTOP, _U(IDS_DOWNLOAD_ERROR+skip), f->FileName);

					FileClose(dest);
					ViCloseFile(down);
					ViInstallDlgCancel(hWnd);

					return;
				}

				// Draw progress
				currentsize += ret;

				if (totalsize != 0)
				{
					UniFormat(tmp, sizeof(tmp), _U(IDS_DOWNLOADING+skip),
						((float)totalsize) / 1024.0f / 1024.0f,
						((float)currentsize) / 1024.0f / 1024.0f);

					pos = (UINT)(((float)currentsize) * 100.0f / ((float)totalsize));
				}
				else
				{
					UniFormat(tmp, sizeof(tmp), _U(IDS_DOWNLOADING2+skip),
						((float)currentsize) / 1024.0f / 1024.0f);
					pos = (UINT)(((float)currentsize) * 100.0f / (1024.0f * 1024.0f * 10.0f));
				}

				ViInstallDlgSetText(d, hWnd, S_SIZEINFO, tmp);
				ViInstallDlgSetPos(hWnd, pos);

				if (ret == 0)
				{
					// Download Complete
					break;
				}
				else
				{
					FileWrite(dest, d->Buf, ret);
				}
			}

			ViCloseFile(down);
			FileClose(dest);
		}
	}

	UniStrCpy(setting.DownloadedInstallerPathW, sizeof(setting.DownloadedInstallerPathW),
		files[0].DestPathW);

	if (num_files >= 2)
	{
		UniStrCpy(setting.DownloadedSettingPathW, sizeof(setting.DownloadedSettingPathW),
			files[1].DestPathW);
	}

	PostMessageA(hWnd, WM_VI_DOWNLOAD_FINISHED, 0, 0);
}
Esempio n. 30
0
static void
ResourceOwnerReleaseInternal(ResourceOwner owner,
							 ResourceReleasePhase phase,
							 bool isCommit,
							 bool isTopLevel)
{
	ResourceOwner child;
	ResourceOwner save;
	ResourceReleaseCallbackItem *item;

	/* Recurse to handle descendants */
	for (child = owner->firstchild; child != NULL; child = child->nextchild)
		ResourceOwnerReleaseInternal(child, phase, isCommit, isTopLevel);

	/*
	 * Make CurrentResourceOwner point to me, so that ReleaseBuffer etc don't
	 * get confused.  We needn't PG_TRY here because the outermost level will
	 * fix it on error abort.
	 */
	save = CurrentResourceOwner;
	CurrentResourceOwner = owner;

	if (phase == RESOURCE_RELEASE_BEFORE_LOCKS)
	{
		/*
		 * Release buffer pins.  Note that ReleaseBuffer will remove the
		 * buffer entry from my list, so I just have to iterate till there are
		 * none.
		 *
		 * During a commit, there shouldn't be any remaining pins --- that
		 * would indicate failure to clean up the executor correctly --- so
		 * issue warnings.	In the abort case, just clean up quietly.
		 *
		 * We are careful to do the releasing back-to-front, so as to avoid
		 * O(N^2) behavior in ResourceOwnerForgetBuffer().
		 */
		while (owner->nbuffers > 0)
		{
			if (isCommit)
				PrintBufferLeakWarning(owner->buffers[owner->nbuffers - 1]);
			ReleaseBuffer(owner->buffers[owner->nbuffers - 1]);
		}

		/*
		 * Release relcache references.  Note that RelationClose will remove
		 * the relref entry from my list, so I just have to iterate till there
		 * are none.
		 *
		 * As with buffer pins, warn if any are left at commit time, and
		 * release back-to-front for speed.
		 */
		while (owner->nrelrefs > 0)
		{
			if (isCommit)
				PrintRelCacheLeakWarning(owner->relrefs[owner->nrelrefs - 1]);
			RelationClose(owner->relrefs[owner->nrelrefs - 1]);
		}

		/*
		 * Release dynamic shared memory segments.  Note that dsm_detach()
		 * will remove the segment from my list, so I just have to iterate
		 * until there are none.
		 *
		 * As in the preceding cases, warn if there are leftover at commit
		 * time.
		 */
		while (owner->ndsms > 0)
		{
			if (isCommit)
				PrintDSMLeakWarning(owner->dsms[owner->ndsms - 1]);
			dsm_detach(owner->dsms[owner->ndsms - 1]);
		}
	}
	else if (phase == RESOURCE_RELEASE_LOCKS)
	{
		if (isTopLevel)
		{
			/*
			 * For a top-level xact we are going to release all locks (or at
			 * least all non-session locks), so just do a single lmgr call at
			 * the top of the recursion.
			 */
			if (owner == TopTransactionResourceOwner)
			{
				ProcReleaseLocks(isCommit);
				ReleasePredicateLocks(isCommit);
			}
		}
		else
		{
			/*
			 * Release locks retail.  Note that if we are committing a
			 * subtransaction, we do NOT release its locks yet, but transfer
			 * them to the parent.
			 */
			LOCALLOCK **locks;
			int			nlocks;

			Assert(owner->parent != NULL);

			/*
			 * Pass the list of locks owned by this resource owner to the lock
			 * manager, unless it has overflowed.
			 */
			if (owner->nlocks > MAX_RESOWNER_LOCKS)
			{
				locks = NULL;
				nlocks = 0;
			}
			else
			{
				locks = owner->locks;
				nlocks = owner->nlocks;
			}

			if (isCommit)
				LockReassignCurrentOwner(locks, nlocks);
			else
				LockReleaseCurrentOwner(locks, nlocks);
		}
	}
	else if (phase == RESOURCE_RELEASE_AFTER_LOCKS)
	{
		/*
		 * Release catcache references.  Note that ReleaseCatCache will remove
		 * the catref entry from my list, so I just have to iterate till there
		 * are none.
		 *
		 * As with buffer pins, warn if any are left at commit time, and
		 * release back-to-front for speed.
		 */
		while (owner->ncatrefs > 0)
		{
			if (isCommit)
				PrintCatCacheLeakWarning(owner->catrefs[owner->ncatrefs - 1]);
			ReleaseCatCache(owner->catrefs[owner->ncatrefs - 1]);
		}
		/* Ditto for catcache lists */
		while (owner->ncatlistrefs > 0)
		{
			if (isCommit)
				PrintCatCacheListLeakWarning(owner->catlistrefs[owner->ncatlistrefs - 1]);
			ReleaseCatCacheList(owner->catlistrefs[owner->ncatlistrefs - 1]);
		}
		/* Ditto for plancache references */
		while (owner->nplanrefs > 0)
		{
			if (isCommit)
				PrintPlanCacheLeakWarning(owner->planrefs[owner->nplanrefs - 1]);
			ReleaseCachedPlan(owner->planrefs[owner->nplanrefs - 1], true);
		}
		/* Ditto for tupdesc references */
		while (owner->ntupdescs > 0)
		{
			if (isCommit)
				PrintTupleDescLeakWarning(owner->tupdescs[owner->ntupdescs - 1]);
			DecrTupleDescRefCount(owner->tupdescs[owner->ntupdescs - 1]);
		}
		/* Ditto for snapshot references */
		while (owner->nsnapshots > 0)
		{
			if (isCommit)
				PrintSnapshotLeakWarning(owner->snapshots[owner->nsnapshots - 1]);
			UnregisterSnapshot(owner->snapshots[owner->nsnapshots - 1]);
		}

		/* Ditto for temporary files */
		while (owner->nfiles > 0)
		{
			if (isCommit)
				PrintFileLeakWarning(owner->files[owner->nfiles - 1]);
			FileClose(owner->files[owner->nfiles - 1]);
		}

		/* Clean up index scans too */
		ReleaseResources_hash();
	}

	/* Let add-on modules get a chance too */
	for (item = ResourceRelease_callbacks; item; item = item->next)
		(*item->callback) (phase, isCommit, isTopLevel, item->arg);

	CurrentResourceOwner = save;
}