Debug Assertion Failed while using ActiveX control - mfcc

Am newbie to this forum & MFC... Am getting Debug Assertion Failed
while using ActiveX control. Please guide me on this..My code looks
like this:
//CMyProjectDlg.h
class CMyProjectDlg: public CDialog
{
public:
CMyProject(CWnd* pParent = NULL);
enum { IDD = IDD_CMYPROJECT_DIALOG };
CMiDocView m_MIDOCtrl;
//Here CMiDocView is the class defined in other header file
protected:
BOOL bReadOCRByMODIAXCtrl(CString csFilePath, CString &csText);
};
//CMyProjectDlg.cpp
BOOL CMyProjectDlg::bReadOCRByMODIAXCtrl(CString csFilePath, CString &csText)
{
BOOL bRet = TRUE;
HRESULT hr = 0;
csText.Empty();
IUnknown *pVal = NULL;
IDocument *IDobj = NULL;
ILayout *ILayout = NULL;
IImages *IImages = NULL;
IImage *IImage = NULL;
IWords *IWords = NULL;
IWord *IWord = NULL;
try{
pVal = (IUnknown *) m_MIDOCtrl.GetDocument();
//After Executing this statement, I used to Debug Assertion failed...
if ( pVal != NULL )
{
hr = pVal->QueryInterface(IID_IDocument,(void**) &IDobj);
if ( SUCCEEDED(hr) )
{
hr = IDobj->OCR(miLANG_SYSDEFAULT,1,1);
if ( SUCCEEDED(hr) )
{
IDobj->get_Images(&IImages);
long iImageCount=0;
IImages->get_Count(&iImageCount);
for ( int img =0; img<iImageCount;img++)
{
IImages->get_Item(img,(IDispatch**)&IImage);
IImage->get_Layout(&ILayout);
long numWord=0;
ILayout->get_NumWords(&numWord);
ILayout->get_Words(&IWords);
IWords->get_Count(&numWord);
for ( long i=0; i<numWord;i++)
{
IWords->get_Item(i,(IDispatch**)&IWord);
CString csTemp;
BSTR result;
IWord->get_Text(&result);
char buf[256];
sprintf(buf,"%S",result);
csTemp.Format("%s",buf);
csText += csTemp;
csText +=" ";
//Release all objects
IWord->Release();
IWords->Release();
ILayout->Release();
IImage->Release();
}
IImages->Release();
} else {
bRet = FALSE;
}
} else {
bRet = FALSE;
}
IDobj->Close(0);
IDobj->Release();
pVal->Release();
} else {
bRet = FALSE;
}
pVal = NULL;
IDobj = NULL;
ILayout = NULL;
IImages = NULL;
IImage = NULL;
IWords = NULL;
IWord = NULL;
}
catch(...)
{
}
return bRet;
}
void CMyProjectDlg::OnBnClickedOCR()
{
//Dynamic object creation:
CMyProjectDlg *ob = new CMyProjectDlg;
((CMiDocView *)GetDlgItem(IDC_MIDOCVIEW1))->SetFileName("E:\\aaa.tiff");
//IDC_MIDOCVIEW is the ID for the ActiveX control..
((CMiDocView *) GetDlgItem( IDC_MIDOCVIEW1 ))->SetFitMode(1);
CString cs;
ob->bReadOCRByMODIAXCtrl("E:\\aaa.tiff",cs);
//Release the memory:
delete ob;
}
After clicking OCR button, I used to get Debug assertion failed on the line:
pVal = (IUnknown *) m_MIDOCtrl.GetDocument();
When i press retry, the control goes to
ASSERT(m_pCtrlsite != NULL ) in winocc.cpp
while Debugging i came to know that {CMIDOCView hWnd = 0x0000000}.
Please can anyone suggest me what am doing wrong here ??
Thank you all..

Related

Loading delay exceeded warning - Programmer Instrument - Unity

I'm getting an warning that says ": Loading delay exceeded, sound may play at incorrect time" whenever I try to use the example code from FMOD for Programmer Instrument
I thought maybe I need to wait for the FMOD.Sound openState == READY, but that doesn't seem to have worked. Am I missing something? Here's my code:
public static void PlayDialogue(string key, Action callback = null)
{
// Create Instance
FMOD.Studio.EventInstance dialogueInstance = FMODUnity.RuntimeManager.CreateInstance(instance.dialogueEvent);
// Pin the key string in memory and pass a pointer through the user data
GCHandle stringHandle = GCHandle.Alloc(key, GCHandleType.Pinned);
dialogueInstance.setUserData(GCHandle.ToIntPtr(stringHandle));
dialogueInstance.setCallback(instance.dialogueCallback);
}
[AOT.MonoPInvokeCallback(typeof(FMOD.Studio.EVENT_CALLBACK))]
static FMOD.RESULT DialogueCallback(FMOD.Studio.EVENT_CALLBACK_TYPE type, IntPtr instancePtr, IntPtr parameterPtr)
{
// Get Instance
FMOD.Studio.EventInstance instance = new FMOD.Studio.EventInstance(instancePtr);
// Retrieve the user data
IntPtr stringPtr;
instance.getUserData(out stringPtr);
// Get the string object
GCHandle stringHandle = GCHandle.FromIntPtr(stringPtr);
String key = stringHandle.Target as String;
switch (type)
{
case FMOD.Studio.EVENT_CALLBACK_TYPE.CREATE_PROGRAMMER_SOUND:
{
FMOD.MODE soundMode = FMOD.MODE.LOOP_NORMAL
| FMOD.MODE.CREATECOMPRESSEDSAMPLE
| FMOD.MODE.NONBLOCKING;
FMOD.Studio.PROGRAMMER_SOUND_PROPERTIES programmerSoundProperties =
(FMOD.Studio.PROGRAMMER_SOUND_PROPERTIES)Marshal.PtrToStructure(
parameterPtr, typeof(FMOD.Studio.PROGRAMMER_SOUND_PROPERTIES));
FMOD.Sound dialogueSound;
if (key.Contains("."))
{
// Load Sound by Given Path
FMOD.RESULT soundResult = FMODUnity.RuntimeManager.CoreSystem.createSound(
Application.streamingAssetsPath + "/" + key, soundMode, out dialogueSound);
if (soundResult == FMOD.RESULT.OK)
{
programmerSoundProperties.sound = dialogueSound.handle;
programmerSoundProperties.subsoundIndex = -1;
Marshal.StructureToPtr(programmerSoundProperties, parameterPtr, false);
// Wait To Play
WaitForLoadThenPlay(instancePtr, parameterPtr);
}
}
else
{
// Load Sound Path
FMOD.Studio.SOUND_INFO dialogueSoundInfo;
FMOD.RESULT keyResult = FMODUnity.RuntimeManager.StudioSystem.getSoundInfo(key, out dialogueSoundInfo);
if (keyResult != FMOD.RESULT.OK) break;
// Load Sound
FMOD.RESULT soundResult = FMODUnity.RuntimeManager.CoreSystem.createSound(
dialogueSoundInfo.name_or_data, soundMode | dialogueSoundInfo.mode, ref dialogueSoundInfo.exinfo, out dialogueSound);
if (soundResult == FMOD.RESULT.OK)
{
programmerSoundProperties.sound = dialogueSound.handle;
programmerSoundProperties.subsoundIndex = dialogueSoundInfo.subsoundindex;
Marshal.StructureToPtr(programmerSoundProperties, parameterPtr, false);
// Wait To Play
WaitForLoadThenPlay(instancePtr, parameterPtr);
}
}
break;
}
case FMOD.Studio.EVENT_CALLBACK_TYPE.DESTROY_PROGRAMMER_SOUND:
{
FMOD.Studio.PROGRAMMER_SOUND_PROPERTIES parameter =
(FMOD.Studio.PROGRAMMER_SOUND_PROPERTIES)Marshal.PtrToStructure(
parameterPtr, typeof(FMOD.Studio.PROGRAMMER_SOUND_PROPERTIES));
FMOD.Sound sound = new FMOD.Sound(parameter.sound);
sound.release();
break;
}
case FMOD.Studio.EVENT_CALLBACK_TYPE.DESTROYED:
{
// Now the event has been destroyed, unpin the string memory so it can be garbage collected
stringHandle.Free();
break;
}
}
return FMOD.RESULT.OK;
}
private static void WaitForLoadThenPlay(IntPtr instancePtr, IntPtr parameterPtr)
=> instance.StartCoroutine(instance.WaitForLoadThenPlayRoutine(instancePtr, parameterPtr));
private IEnumerator WaitForLoadThenPlayRoutine(IntPtr instancePtr, IntPtr parameterPtr)
{
// Get Instance
FMOD.Studio.EventInstance instance = new FMOD.Studio.EventInstance(instancePtr);
// Grab Sound Reference
FMOD.Studio.PROGRAMMER_SOUND_PROPERTIES parameter =
(FMOD.Studio.PROGRAMMER_SOUND_PROPERTIES)Marshal.PtrToStructure(
parameterPtr, typeof(FMOD.Studio.PROGRAMMER_SOUND_PROPERTIES));
FMOD.Sound sound = new FMOD.Sound(parameter.sound);
// Wait for Load
FMOD.OPENSTATE state = FMOD.OPENSTATE.BUFFERING;
uint percentbuffered;
bool starving;
bool diskbusy;
while (state != FMOD.OPENSTATE.READY)
{
yield return null;
sound.getOpenState(out state, out percentbuffered, out starving, out diskbusy);
}
instance.start();
instance.release();
}
Here's what I ended up doing. I don't know if it makes sense or not, but it does get rid of the warnings. I really wish they'd fix the documentation. The example script doesn't work properly.
public static void PlayDialogue(string key, Action callback = null) => instance.StartCoroutine(PlayDialogueRoutine(key, callback));
public static IEnumerator PlayDialogueRoutine(string key, Action callback = null)
{
// Check if Already Playing
if (instance.activeDialogue.ContainsKey(key))
{
Debug.LogError("Tried to play already playing dialogue");
callback?.Invoke();
yield break;
}
// Load Sound Path
FMOD.Studio.SOUND_INFO dialogueSoundInfo;
FMOD.RESULT keyResult = FMODUnity.RuntimeManager.StudioSystem.getSoundInfo(key, out dialogueSoundInfo);
if (keyResult != FMOD.RESULT.OK)
{
Debug.LogError("Couldn't find dialogue with key: " + key);
callback?.Invoke();
yield break;
}
// Load Sound
FMOD.Sound dialogueSound;
FMOD.MODE soundMode = FMOD.MODE.LOOP_NORMAL
| FMOD.MODE.CREATECOMPRESSEDSAMPLE
| FMOD.MODE.NONBLOCKING;
FMOD.RESULT soundResult = FMODUnity.RuntimeManager.CoreSystem.createSound(
dialogueSoundInfo.name_or_data, soundMode | dialogueSoundInfo.mode,
ref dialogueSoundInfo.exinfo, out dialogueSound);
if (soundResult != FMOD.RESULT.OK)
{
Debug.LogError("Couldn't load sound: " + key);
callback?.Invoke();
yield break;
}
// Wait to Load
int maxFrameWait = 120;
FMOD.OPENSTATE openstate = FMOD.OPENSTATE.BUFFERING;
uint percentbuffered;
bool starving;
bool diskbusy;
while (openstate != FMOD.OPENSTATE.READY)
{
yield return null;
dialogueSound.getOpenState(out openstate, out percentbuffered, out starving, out diskbusy);
if (--maxFrameWait <= 0)
{
dialogueSound.release();
Debug.LogError("Failed to load dialogue sound " + key);
yield break;
}
}
// Create Instance
FMOD.Studio.EventInstance dialogueInstance = FMODUnity.RuntimeManager.CreateInstance(instance.dialogueEvent);
// Store Reference (and remove in play stopped callback)
instance.activeDialogue[key] = dialogueInstance;
// Pin Memory
FMODDialogueParameterWrapper soundWrapper = new FMODDialogueParameterWrapper(dialogueSound, dialogueSoundInfo, () =>
{
instance.activeDialogue.Remove(key);
callback?.Invoke();
});
GCHandle soundWrapperHandle = GCHandle.Alloc(soundWrapper, GCHandleType.Pinned);
dialogueInstance.setUserData(GCHandle.ToIntPtr(soundWrapperHandle));
// Set Callback
dialogueInstance.setCallback(instance.dialogueCallback,
FMOD.Studio.EVENT_CALLBACK_TYPE.CREATE_PROGRAMMER_SOUND
| FMOD.Studio.EVENT_CALLBACK_TYPE.CREATE_PROGRAMMER_SOUND
| FMOD.Studio.EVENT_CALLBACK_TYPE.DESTROYED
| FMOD.Studio.EVENT_CALLBACK_TYPE.STOPPED);
// Play One Shot
dialogueInstance.start();
dialogueInstance.release();
}
[AOT.MonoPInvokeCallback(typeof(FMOD.Studio.EVENT_CALLBACK))]
static FMOD.RESULT DialogueCallback(FMOD.Studio.EVENT_CALLBACK_TYPE type, IntPtr instancePtr, IntPtr parameterPtr)
{
// Get Instance
FMOD.Studio.EventInstance instance = new FMOD.Studio.EventInstance(instancePtr);
// Retrieve the user data FMODDialogueParameterWrapper
IntPtr dialogueParameterWrapperPtr;
FMOD.RESULT result = instance.getUserData(out dialogueParameterWrapperPtr);
if (result != FMOD.RESULT.OK)
{
Debug.LogError("Failed to fetch user data for dialogue callback: " + result);
}
else if (dialogueParameterWrapperPtr != IntPtr.Zero)
{
GCHandle dialogueParameterWrapperHandle = GCHandle.FromIntPtr(dialogueParameterWrapperPtr);
FMODDialogueParameterWrapper dialogueParameterWrapper =
(FMODDialogueParameterWrapper)dialogueParameterWrapperHandle.Target;
switch (type)
{
case FMOD.Studio.EVENT_CALLBACK_TYPE.CREATE_PROGRAMMER_SOUND:
{
FMOD.Studio.PROGRAMMER_SOUND_PROPERTIES programmerSoundProperties =
(FMOD.Studio.PROGRAMMER_SOUND_PROPERTIES)Marshal.PtrToStructure(
parameterPtr, typeof(FMOD.Studio.PROGRAMMER_SOUND_PROPERTIES));
programmerSoundProperties.sound = dialogueParameterWrapper.sound.handle;
programmerSoundProperties.subsoundIndex = dialogueParameterWrapper.soundInfo.subsoundindex;
Marshal.StructureToPtr(programmerSoundProperties, parameterPtr, false);
break;
}
case FMOD.Studio.EVENT_CALLBACK_TYPE.DESTROY_PROGRAMMER_SOUND:
{
FMOD.Studio.PROGRAMMER_SOUND_PROPERTIES parameter =
(FMOD.Studio.PROGRAMMER_SOUND_PROPERTIES)Marshal.PtrToStructure(
parameterPtr, typeof(FMOD.Studio.PROGRAMMER_SOUND_PROPERTIES));
FMOD.Sound sound = new FMOD.Sound(parameter.sound);
sound.release();
break;
}
case FMOD.Studio.EVENT_CALLBACK_TYPE.DESTROYED:
{
// Now the event has been destroyed, unpin the string memory so it can be garbage collected
Debug.Log("Freeing");
dialogueParameterWrapperHandle.Free();
break;
}
case FMOD.Studio.EVENT_CALLBACK_TYPE.STOPPED:
{
dialogueParameterWrapper.onStopCallback?.Invoke();
break;
}
}
}
return FMOD.RESULT.OK;
}
[StructLayout(LayoutKind.Sequential)]
class FMODDialogueParameterWrapper
{
public FMOD.Sound sound;
public FMOD.Studio.SOUND_INFO soundInfo;
public Action onStopCallback;
public FMODDialogueParameterWrapper(FMOD.Sound sound, FMOD.Studio.SOUND_INFO soundInfo, Action onStopCallback)
{
this.sound = sound;
this.soundInfo = soundInfo;
this.onStopCallback = onStopCallback;
}
}

What is the difference between mono_assembly_open and mono_image_open_from_data_with_name?

I want load a .net assembly module, when i use mono_assembly_open is fine. But when i use mono_image_open_from_data_with_name, it's not work, can't traverse the module I want to load.
void *load_image_from_file(const char *full_file_path)
{
if (full_file_path == NULL)
{
return NULL;
}
if (!PathFileExistsA(full_file_path))
{
return NULL;
}
HANDLE file = CreateFileA(full_file_path, FILE_READ_ACCESS, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (file == INVALID_HANDLE_VALUE)
{
return NULL;
}
DWORD file_size = GetFileSize(file, NULL);
if (file_size == INVALID_FILE_SIZE)
{
CloseHandle(file);
return NULL;
}
byte *file_data = reinterpret_cast<byte *>(malloc(file_size));
if (file_data == NULL)
{
CloseHandle(file);
return NULL;
}
DWORD read = 0;
ReadFile(file, file_data, file_size, &read, NULL);
if (file_size != read)
{
free(file_data);
CloseHandle(file);
return NULL;
}
MonoImageOpenStatus status;
void *image = mono_image_open_from_data_with_name(reinterpret_cast<char *>(file_data), file_size, MONO_TRUE, &status, MONO_FALSE, full_file_path);
free(file_data);
return image;
}
After call mono_image_open_from_data_with_name, you should call mono_assembly_load_from_full.
if (status != MONO_IMAGE_OK)
{
RPCS_ERROR("Open Image Failed %s", full_file_path);
return NULL;
}
void *assembly = mono_image_get_assembly_(image);
if (assembly == NULL)
{
assembly = mono_assembly_load_from_full_(image, full_file_path, &status, MONO_FALSE);
}
mono_image_close_(image);
return assembly;

Cloud load failed with error code 7 using Unity GoolePlayGames plugin

I get the following log during on-device debugging
Error:
*** [Play Games Plugin DLL] ERROR: Cloud load failed with status code 7
Basically the OnStateLoaded() callback function always returns the boolean success = false and I can't figure out the reason why.
All that the plugin debugging logs mention is "Cloud load failed with status code 7".
According to the android doc, 7 is a generic "developer error", see https://developer.android.com/reference/com/google/android/gms/appstate/AppStateStatusCodes.html#STATUS_DEVELOPER_ERROR
I tried a quick sample and everything worked ok. Here are my steps:
Created a new game in the play console
(https://play.google.com/apps/publish)
Made sure Saved Games is set
to ON
Linked an Android Application Remembering the application ID
(the number after the title) and the package ID
Created a new project in Unity
Added the play games plugin (Assets/Import Package.../Custom
Package)
Set the application ID (Google Play Games/Android Setup...)
Switched the platform to Android (File/Build Settings...)
Set the player settings (bundle identifier and the keystore info)
Added a new script component to the camera
Saved everything and hit build and run.
Here are the contents:
using UnityEngine;
using System.Collections;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using System;
public class SaveSample : MonoBehaviour {
System.Action<bool> mAuthCallback;
GameData slot0;
void Start () {
slot0 = new GameData(0,"waiting for login....");
mAuthCallback = (bool success) => {
if (success) {
Debug.Log("Authentication was successful!");
slot0.Data =" loading....";
slot0.LoadState();
}
else {
Debug.LogWarning("Authentication failed!");
}
};
// make Play Games the default social implementation
PlayGamesPlatform.Activate();
// enable debug logs
PlayGamesPlatform.DebugLogEnabled = true;
//Login explicitly for this sample, usually this would be silent
PlayGamesPlatform.Instance.Authenticate(mAuthCallback, false);
}
protected void OnGUI() {
Screen.fullScreen = true;
int buttonHeight = Screen.height / 20;
int buttonWidth = Screen.width / 5;
GUI.skin.label.fontSize = 60;
GUI.skin.button.fontSize = 60;
Rect statusRect = new Rect(10,20,Screen.width,100);
Rect dataRect = new Rect( 10, 150, Screen.width,100);
Rect b1Rect = new Rect(10, 400, buttonWidth, buttonHeight);
Rect b2Rect = new Rect(b1Rect.x + 20 + buttonWidth,
b1Rect.y, buttonWidth, buttonHeight);
if(!Social.localUser.authenticated) {
if(GUI.Button(b1Rect, "Signin")) {
Social.localUser.Authenticate(mAuthCallback);
}
}
else {
// logged in, so show the load button and the contents of the saved data.
if(GUI.Button(b1Rect, "Load")) {
slot0.LoadState();
}
GUI.Label(dataRect, slot0.Data);
}
if(GUI.Button(b2Rect, "Save")) {
// just save a string, incrementing the number on the end.
int idx = slot0.Data.IndexOf("_");
if (idx > 0) {
int val = Convert.ToInt32(slot0.Data.Substring(idx+1));
val++;
slot0.Data = "Save_" + val;
}
else {
slot0.Data = "Save_0";
}
slot0.SaveState();
}
GUI.Label(statusRect, slot0.State);
}
// Class to handle save/load callbacks.
public class GameData : OnStateLoadedListener {
int slot;
string data;
string state;
public GameData(int slot, string data) {
this.slot = slot;
this.data = data;
this.state = "Initialized, modified";
}
public void LoadState() {
this.state += ", loading";
((PlayGamesPlatform)Social.Active).LoadState(0, this);
}
public void SaveState() {
byte[] bytes = new byte[data.Length * sizeof(char)];
System.Buffer.BlockCopy(data.ToCharArray(), 0, bytes, 0, bytes.Length);
this.state += ", saving";
((PlayGamesPlatform) Social.Active).UpdateState(slot, bytes, this);
}
public void OnStateLoaded(bool success, int slot, byte[] data) {
if (success) {
Debug.Log ("Save game slot : " + slot + " loaded: " + data);
if (data != null) {
char[] chars = new char[data.Length / sizeof(char)];
System.Buffer.BlockCopy(data, 0, chars, 0, data.Length);
this.data = new string(chars);
this.state = "loaded";
} else {
Debug.Log ("Saved data is null");
this.data = "";
this.state = "loaded, but empty";
}
} else {
// handle failure
Debug.LogWarning ("Save game slot : " + slot + " failed!: ");
this.data = "";
this.state = "loading failed!";
}
}
public byte[] OnStateConflict(int slot, byte[] local, byte[] server) {
// resolve conflict and return a byte[] representing the
// resolved state.
Debug.LogWarning("Conflict in saved data!");
state = "conflicted";
// merge or resolve using app specific logic, here
byte[] resolved = local.Length > server.Length ? local : server;
char[] chars = new char[resolved.Length / sizeof(char)];
System.Buffer.BlockCopy(resolved, 0, chars, 0, resolved.Length);
this.data = new string(chars);
return resolved;
}
public void OnStateSaved(bool success, int slot) {
Debug.Log ("Save game slot : " + slot + " success: " + success);
state = "saved";
}
public string Data {
get {
return data;
}
set {
data = value;
state += ", modified";
}
}
public int Slot {
get {
return slot;
}
}
public string State {
get {
return state;
}
}
}
}
The error code 7 is because the Cloud Save API has been deprecated and is only currently accessible to existing games that have used the API. The Unity plugin version 0.9.11 has been updated to use the SavedGames API.
I tried a quick sample and everything worked ok. Here are my steps:
Created a new game in the play console
(https://play.google.com/apps/publish)
Made sure Saved Games is set to ON
Linked an Android Application Remembering the application ID
(the number after the title) and the package ID Created a new
project in Unity
Added the play games plugin (Assets/Import
Package.../Custom Package)
Set the application ID (Google Play
Games/Android Setup...)
Switched the platform to Android (File/Build
Settings...)
Set the player settings (bundle identifier and the
keystore info)
Added a new script component to the camera Saved
everything and hit build and run.
Here is my script:
using UnityEngine;
using System.Collections;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using System;
using GooglePlayGames.BasicApi.SavedGame;
public class SaveSample : MonoBehaviour {
System.Action<bool> mAuthCallback;
GameData slot0;
bool mSaving;
private Texture2D mScreenImage;
// Use this for initialization
void Start () {
slot0 = new GameData("New game");
mAuthCallback = (bool success) => {
if (success) {
Debug.Log("Authentication was successful!");
slot0.State = "Click load or save";
}
else {
Debug.LogWarning("Authentication failed!");
}
};
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
.EnableSavedGames()
.Build();
PlayGamesPlatform.InitializeInstance(config);
// Activate the Play Games platform. This will make it the default
// implementation of Social.Active
PlayGamesPlatform.Activate();
// enable debug logs (note: we do this because this is a sample; on your production
// app, you probably don't want this turned on by default, as it will fill the user's
// logs with debug info).
PlayGamesPlatform.DebugLogEnabled = true;
//Login explicitly for this sample, usually this would be silent
PlayGamesPlatform.Instance.Authenticate(mAuthCallback, false);
}
public void CaptureScreenshot() {
mScreenImage = new Texture2D(Screen.width, Screen.height);
mScreenImage.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
mScreenImage.Apply();
}
protected virtual void OnGUI() {
Screen.fullScreen = true;
int buttonHeight = Screen.height / 20;
int buttonWidth = Screen.width / 5;
GUI.skin.label.fontSize = 60;
GUI.skin.button.fontSize = 60;
Rect statusRect = new Rect(10,20,Screen.width,200);
Rect dataRect = new Rect( 10, 250, Screen.width,100);
Rect b1Rect = new Rect(10, 800, buttonWidth, buttonHeight);
Rect b2Rect = new Rect(b1Rect.x + 20 + buttonWidth, b1Rect.y, buttonWidth, buttonHeight);
if(!Social.localUser.authenticated) {
if(GUI.Button(b1Rect, "Signin")) {
Social.localUser.Authenticate(mAuthCallback);
}
}
else {
if(GUI.Button(b1Rect, "Load")) {
mSaving = false;
((PlayGamesPlatform)Social.Active).SavedGame.ShowSelectSavedGameUI("Select game to load",
4,false,false,SavedGameSelected);
}
GUI.Label(dataRect, slot0.Data);
}
if(GUI.Button(b2Rect, "Save")) {
int idx = slot0.Data.IndexOf("_");
if (idx > 0) {
int val = Convert.ToInt32(slot0.Data.Substring(idx+1));
val++;
slot0.Data = "Save_" + val;
}
else {
slot0.Data = "Save_0";
}
mSaving = true;
CaptureScreenshot();
((PlayGamesPlatform)Social.Active).SavedGame.ShowSelectSavedGameUI("Save game progress",
4,true,true,SavedGameSelected);
}
GUI.Label(statusRect, slot0.State);
}
public void SavedGameSelected(SelectUIStatus status, ISavedGameMetadata game) {
if (status == SelectUIStatus.SavedGameSelected) {
string filename = game.Filename;
Debug.Log("opening saved game: " + game);
if(mSaving && (filename == null || filename.Length == 0)) {
filename = "save" + DateTime.Now.ToBinary();
}
if (mSaving) {
slot0.State = "Saving to " + filename;
}
else {
slot0.State = "Loading from " + filename;
}
//open the data.
((PlayGamesPlatform)Social.Active).SavedGame.OpenWithAutomaticConflictResolution(filename,
DataSource.ReadCacheOrNetwork,
ConflictResolutionStrategy.UseLongestPlaytime,
SavedGameOpened);
} else {
Debug.LogWarning("Error selecting save game: " + status);
}
}
public void SavedGameOpened(SavedGameRequestStatus status, ISavedGameMetadata game) {
if(status == SavedGameRequestStatus.Success) {
if( mSaving) {
slot0.State = "Opened, now writing";
byte[] pngData = (mScreenImage!=null) ?mScreenImage.EncodeToPNG():null;
Debug.Log("Saving to " + game);
byte[] data = slot0.ToBytes();
TimeSpan playedTime = slot0.TotalPlayingTime;
SavedGameMetadataUpdate.Builder builder = new
SavedGameMetadataUpdate.Builder()
.WithUpdatedPlayedTime(playedTime)
.WithUpdatedDescription("Saved Game at " + DateTime.Now);
if (pngData != null) {
Debug.Log("Save image of len " + pngData.Length);
builder = builder.WithUpdatedPngCoverImage(pngData);
}
else {
Debug.Log ("No image avail");
}
SavedGameMetadataUpdate updatedMetadata = builder.Build();
((PlayGamesPlatform)Social.Active).SavedGame.CommitUpdate(game,updatedMetadata,data,SavedGameWritten);
} else {
slot0.State = "Opened, reading...";
((PlayGamesPlatform)Social.Active).SavedGame.ReadBinaryData(game,SavedGameLoaded);
}
} else {
Debug.LogWarning("Error opening game: " + status);
}
}
public void SavedGameLoaded(SavedGameRequestStatus status, byte[] data) {
if (status == SavedGameRequestStatus.Success) {
Debug.Log("SaveGameLoaded, success=" + status);
slot0 = GameData.FromBytes(data);
} else {
Debug.LogWarning("Error reading game: " + status);
}
}
public void SavedGameWritten(SavedGameRequestStatus status, ISavedGameMetadata game) {
if(status == SavedGameRequestStatus.Success) {
Debug.Log ("Game " + game.Description + " written");
slot0.State = "Saved!";
} else {
Debug.LogWarning("Error saving game: " + status);
}
}
public class GameData {
private TimeSpan mPlayingTime;
private DateTime mLoadedTime;
string mData;
string mState;
static readonly string HEADER = "GDv1";
public GameData(string data) {
mData = data;
mState = "Initialized, modified";
mPlayingTime = new TimeSpan();
mLoadedTime = DateTime.Now;
}
public TimeSpan TotalPlayingTime {
get {
TimeSpan delta = DateTime.Now.Subtract(mLoadedTime);
return mPlayingTime.Add(delta);
}
}
public override string ToString () {
string s = HEADER + ":" + mData;
s += ":" + TotalPlayingTime.TotalMilliseconds;
return s;
}
public byte[] ToBytes() {
return System.Text.ASCIIEncoding.Default.GetBytes(ToString());
}
public static GameData FromBytes (byte[] bytes) {
return FromString(System.Text.ASCIIEncoding.Default.GetString(bytes));
}
public static GameData FromString (string s) {
GameData gd = new GameData("initializing from string");
string[] p = s.Split(new char[] { ':' });
if (!p[0].StartsWith(HEADER)) {
Debug.LogError("Failed to parse game data from: " + s);
return gd;
}
gd.mData = p[1];
double val = Double.Parse(p[2]);
gd.mPlayingTime = TimeSpan.FromMilliseconds(val>0f?val:0f);
gd.mLoadedTime = DateTime.Now;
gd.mState = "Loaded successfully";
return gd;
}
public string Data {
get {
return mData;
}
set {
mData = value;
mState += ", modified";
}
}
public string State {
get {
return mState;
}
set {
mState = value;
}
}
}
}

How to implement boolean retrieval using hitcollector in below scenario

I am running my code on TREC documents and right now implementing scoring scheme to get number of relevant documents. However now i want to implement boolean retrieval, I am trying to use HitCollector.
below is my code..
public class BatchSearch {
private BatchSearch() {}
/** Simple command-line based search demo. */
public static void main(String[] args) throws Exception {
String usage =
"Usage:\tjava BatchSearch [-index dir] [-simfn similarity] [-field f] [-queries file]";
if (args.length > 0 && ("-h".equals(args[0]) || "-help".equals(args[0]))) {
System.out.println(usage);
System.out.println("Supported similarity functions:\ndefault: DefaultSimilary (tfidf)\n");
System.exit(0);
}
String index = "index";
String field = "contents";
String queries = null;
String simstring = "default";
for(int i = 0;i < args.length;i++) {
if ("-index".equals(args[i])) {
index = args[i+1];
i++;
} else if ("-field".equals(args[i])) {
field = args[i+1];
i++;
} else if ("-queries".equals(args[i])) {
queries = args[i+1];
i++;
} else if ("-simfn".equals(args[i])) {
simstring = args[i+1];
i++;
}
}
Similarity simfn = null;
if ("default".equals(simstring)) {
simfn = new DefaultSimilarity();
} else if ("bm25".equals(simstring)) {
simfn = new BM25Similarity();
} else if ("dfr".equals(simstring)) {
simfn = new DFRSimilarity(new BasicModelP(), new AfterEffectL(), new NormalizationH2());
} else if ("lm".equals(simstring)) {
simfn = new LMDirichletSimilarity();
}
if (simfn == null) {
System.out.println(usage);
System.out.println("Supported similarity functions:\ndefault: DefaultSimilary (tfidf)");
System.out.println("bm25: BM25Similarity (standard parameters)");
System.out.println("dfr: Divergence from Randomness model (PL2 variant)");
System.out.println("lm: Language model, Dirichlet smoothing");
System.exit(0);
}
IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(index)));
IndexSearcher searcher = new IndexSearcher(reader);
searcher.setSimilarity(simfn);
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_41);
BufferedReader in = null;
if (queries != null) {
in = new BufferedReader(new InputStreamReader(new FileInputStream(queries), "UTF-8"));
} else {
in = new BufferedReader(new InputStreamReader(new FileInputStream("queries"), "UTF-8"));
}
QueryParser parser = new QueryParser(Version.LUCENE_41, field, analyzer);
while (true) {
String line = in.readLine();
if (line == null || line.length() == -1) {
break;
}
line = line.trim();
if (line.length() == 0) {
break;
}
String[] pair = line.split(" ", 2);
Query query = parser.parse(pair[1]);
doBatchSearch(in, searcher, pair[0], query, simstring);
}
reader.close();
}
/**
* This function performs a top-1000 search for the query as a basic TREC run.
*/
public static void doBatchSearch(BufferedReader in, IndexSearcher searcher, String qid, Query query, String runtag)
throws IOException {
// Collect enough docs to show 5 pages
TopDocs results = searcher.search(query, 1000);
ScoreDoc[] hits = results.scoreDocs;
HashMap<String, String> seen = new HashMap<String, String>(1000);
int numTotalHits = results.totalHits;
int start = 0;
int end = Math.min(numTotalHits, 1000);
for (int i = start; i < end; i++) {
Document doc = searcher.doc(hits[i].doc);
String docno = doc.get("docno");
// There are duplicate document numbers in the FR collection, so only output a given
// docno once.
if (seen.containsKey(docno)) {
continue;
}
seen.put(docno, docno);
System.out.println(qid+" Q0 "+docno+" "+i+" "+hits[i].score+" "+runtag);
}
}
}
The scoring is done in doBatchSearch and now i want to implement HitCollector here.

contacts insert ,app died ,no save state

this is log:
08-28 13:50:47.648: A/libc(1010): ### ABORTING: INVALID HEAP ADDRESS IN dlfree addr=0x2a26bc90
08-28 13:50:47.648: A/libc(1010): Fatal signal 11 (SIGSEGV) at 0xdeadbaad (code=1), thread 1020 (FinalizerDaemon)
08-28 13:50:48.698: W/ActivityManager(149): Scheduling restart of crashed service com.android.KnowingLife/.PushNotification.NotificationService in 5000ms
08-28 13:50:48.698: W/ActivityManager(149): Force removing ActivityRecord{412a2c70 com.android.KnowingLife/.PhoneSynActivity}: app died, no saved state
08-28 13:50:48.807: W/GpsLocationProvider(149): Unneeded remove listener for uid 1000
08-28 13:50:49.257: E/Trace(1064): error opening trace file: No such file or directory (2)
08-28 13:50:50.017: W/GpsLocationProvider(149): Duplicate add listener for uid 10044
08-28 13:50:52.827: W/InputMethodManagerService(149): Got RemoteException sending setActive(false) notification to pid 1010 uid 10044
I run it in my emulator( version 4.1),and I am bulk inserting contacts to local .It works well usual,but I got 600 more contacts to
insert to local ,it doesn't work when insert to about 6%.I don't know
how to show it to you ,this is my code ,look this, you will see the
problem,thank
/**
* insert
*/
class InsertContactsTask extends AsyncTask<Void, Integer, Integer> {
String detail;
public InsertContactsTask(String detail) {
this.detail = detail;
}
#SuppressWarnings("deprecation")
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(PROGRESS_DIALOG);
}
#Override
protected Integer doInBackground(Void... params) {
String[] itemRecord = detail.split(ParseData.getInstance()
.getRecordSplitFalg(), -1);
int count = itemRecord.length;
wait_Dialog.setMax(count);
ArrayList<ContentProviderOperation> contentOper = null;
contentOper = new ArrayList<ContentProviderOperation>();
for (int i = 0; i < itemRecord.length; i++) {
int rawContactInsertIndex = contentOper.size();
String[] item = null;
try {
item = itemRecord[i].split(ParseData.getInstance()
.getFiledSplitFlag(), -1);
contentOper.add(ContentProviderOperation
.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE, null)
.withValue(RawContacts.ACCOUNT_NAME, null).build());
contentOper.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID,
rawContactInsertIndex)
.withValue(Data.MIMETYPE,
StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME, item[0])
.build());
for (int j = 1; j < item.length; j++) {
if (item[j].startsWith("1")) {
String phoneType = item[j].substring(1, 2);
int iType;
String label = null;
if (phoneType.compareToIgnoreCase("a") >= 0)
iType = phoneType.compareToIgnoreCase("a") + 10;
else
iType = Integer.parseInt(phoneType);
if (iType == 0)
label = item[j + 1];
contentOper
.add(ContentProviderOperation
.newInsert(
android.provider.ContactsContract.Data.CONTENT_URI)
.withValueBackReference(
Data.RAW_CONTACT_ID,
rawContactInsertIndex)
.withValue(Data.MIMETYPE,
Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER,
item[j].substring(2))
// "data1"
.withValue(Phone.TYPE, iType)
.withValue(Phone.LABEL, label)
.build());
if (iType == 0)
j++;
} else {
String emailType = item[j].substring(1, 2);
int iEmailType = Integer.parseInt(emailType);
String emailLabel = null;
if (iEmailType == 0)
emailLabel = item[j + 1];
contentOper
.add(ContentProviderOperation
.newInsert(
android.provider.ContactsContract.Data.CONTENT_URI)
.withValueBackReference(
Data.RAW_CONTACT_ID,
rawContactInsertIndex)
.withValue(Data.MIMETYPE,
Email.CONTENT_ITEM_TYPE)
.withValue(Email.DATA,
item[j].substring(2))
.withValue(Email.TYPE, iEmailType)
.withValue(Email.LABEL, emailLabel)
.build());
if (iEmailType == 0)
j++;
}
}
int iUpdate = i + 1;
if (iUpdate % 20 == 0 || iUpdate == itemRecord.length) {
try {
#SuppressWarnings("unused")
ContentProviderResult[] results = PhoneSynActivity.this
.getContentResolver().applyBatch(
ContactsContract.AUTHORITY,
contentOper);
contentOper.clear();
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
publishProgress(i);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
return count;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
wait_Dialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer count) {
super.onPostExecute(count);
wait_Dialog.dismiss();
txt_count.setText( count+ "");
Toast.makeText(PhoneSynActivity.this,
R.string.string_download_suc, Toast.LENGTH_LONG).show();
}
}