How can I get a progress report from an async write to an output stream? - windows-runtime

In my app, I have to write an IBuffer to an IOutputStream. I'd like to show my user the progress of this operation, so I'm trying with the following code:
auto writeOp = strm->WriteAsync(buff);
writeOp->Progress = ref new AsyncOperationProgressHandler<unsigned int, unsigned int>(
[=](IAsyncOperationWithProgress<unsigned int, unsigned int>^ op, unsigned int progress)
{
MyViewModel->Insert("WriteProgress", progress);
});
auto writeToFileTask = create_task(writeOp);
writeToFileTask.then([this](unsigned int c)
{
(void)c; // Unused parameter
});
However, MyViewModel->Insert("WriteProgress", progress) is never reached when I set a breakpoint. I don't know what I'd do differently to get this to work and I can't use C++/WinRT, so, any ideas?

Related

Serial monitor problem instantly finishing

int pinRed=2;
int pinBlue=4;
int pinWhite=6;
String Color;
String question="Which LED would you like to light up Red,Blue or White?";
int delayTime=1000;
void setup() {
Serial.begin(9600);
pinMode(pinRed,OUTPUT);
pinMode(pinBlue,OUTPUT);
pinMode(pinWhite,OUTPUT);
}
void loop() {
Serial.print(question);
while(Serial.available()==0){
}
Color=Serial.readString();
if(Color=="Red" || Color=="red"){
digitalWrite(pinRed,HIGH);
digitalWrite(pinBlue,LOW);
digitalWrite(pinWhite,LOW);
delay(delayTime);
}
if(Color=="Blue" || Color=="blue"){
digitalWrite(pinBlue,HIGH);
digitalWrite(pinRed,LOW);
digitalWrite(pinWhite,LOW);
delay(delayTime);
}
if(Color=="White" || Color=="white"){
digitalWrite(pinWhite,HIGH);
digitalWrite(pinBlue,LOW);
digitalWrite(pinRed,LOW);
delay(delayTime);
}
delay(delayTime);
}
This is my code, but is not working, when I enter a color the serial monitor ask the question again instantly and not led is turning on, I checked the pins and the LEDs work completely fine but I think I have a problem with my serial monitor cause I am having problem with every project using the serial monitor despite even copying codes from the internet, so anyone have any idea what can be the problem(I am on version Arduino 1.8.18)
I do not know for sure as I am not familiar with the particular language/library that you are using. However, the symptoms you describe indicate that your input string does not match any of your targets ('red', 'RED') etc.
I would re-read the description of the Serial.available() function. Is it returning non-zero as soon as the first character is available? If so then your input string from
Color=Serial.readString() will always be aone-character string, eg 'r'.
To test this you could try matching against 'r', 'g', 'b' as strings.....

How to ensure that updating to database on certain interval

I am working in a application Spring java8
I have one function that generate Labels(pdf generation) asynchronously.
it contains a loop, usually it will run more than 1000, it generate more than 1000 pdf labels.
after every loop ends we need to update the database, so that we just saving the status, ie initially it save numberOfgeneratedCount=0 , after each label we just increment the variable and update the table.
It is not Necessary to save this incremented count to db at every loop ends, what we need is in a fixed intervals only we need to update the database to reduce load on dataBase inserts.
currently my code is like
// Label is a database model class labeldb is variable of that
//commonDao.saveLabelToDb function to save Label object
int numberOfgeneratedCount =0;
labeldb.setProcessedOrderCount(numberOfgeneratedCount);
commonDao.saveLabelToDb(labeldb);
for(Order order: orders){
generated = true;
try{
// pdf generation code
}catch Exception e{
// catch block here
generated = false;
}
if(generated){
numberOfgeneratedCount++;
deliveryLabeldb.setProcessedOrderCount(numberOfgeneratedCount);
commonDao.saveLabelToDb(labeldb );
}
}
to improve the performance we need to update database only an interval of 10 seconds. Any help would appreciated
I have done this using the following code, I am not sure about whether this is a good solution, Some one please improve this using some built in functions
int numberOfgeneratedCount =0;
labeldb.setProcessedOrderCount(numberOfgeneratedCount);
commonDao.saveLabelToDb(labeldb);
int nowSecs =LocalTime.now().toSecondOfDay();
int lastSecs = nowSecs;
for(Order order: orders){
nowSecs = LocalTime.now().toSecondOfDay();
generated = true;
try{
// pdf generation code
}catch Exception e{
// catch block here
generated = false;
}
if(generated){
numberOfgeneratedCount++;
deliveryLabeldb.setProcessedOrderCount(numberOfgeneratedCount);
if(nowSecs-lastSecs > 10){
lastSecs=nowSecs;
commonDao.saveLabelToDb(labeldb );
}
}
}

How to convert large UTF-8 encoded char* string to CStringW (UTF-16)?

I have a problem with converting a UTF-8 encoded string to a UTF-16 encoded CStringW.
Here is my source code:
CStringW ConvertUTF8ToUTF16( __in const CHAR * pszTextUTF8 )
{
_wsetlocale( LC_ALL, L"Korean" );
if ( (pszTextUTF8 == NULL) || (*pszTextUTF8 == '\0') )
{
return L"";
}
const size_t cchUTF8Max = INT_MAX - 1;
size_t cchUTF8;
HRESULT hr = ::StringCbLengthA( pszTextUTF8, cchUTF8Max, &cchUTF8 );
if ( FAILED( hr ) )
{
AtlThrow( hr );
}
++cchUTF8;
int cbUTF8 = static_cast<int>( cchUTF8 );
int cchUTF16 = ::MultiByteToWideChar(
CP_UTF8,
MB_ERR_INVALID_CHARS,
pszTextUTF8,
-1,
NULL,
0
);
CString strUTF16;
strUTF16.GetBufferSetLength(cbUTF8);
WCHAR * pszUTF16 = new WCHAR[cchUTF16];
int result = ::MultiByteToWideChar(
CP_UTF8,
0,
pszTextUTF8,
cbUTF8,
pszUTF16,
cchUTF16
);
ATLASSERT( result != 0 );
if ( result == 0 )
{
AtlThrowLastWin32();
}
strUTF16.Format(_T("%s"), pszUTF16);
return strUTF16;
}
pszTextUTF8 is htm file's content in UTF-8.
When htm file's volume is less than 500kb, this code works well.
but, when converting over 500kb htm file, (ex 648KB htm file that I have.)
pszUTF16 has all content of file, but strUTF16 is not. (about half)
I guess File open is not wrong.
In strUTF16 m_pszData has all content how to I get that?
strUTF16.Getbuffer(); dosen't work.
The code in the question is stock full of bugs, somewhere in the order of 1 bug per 1-2 lines of code.
Here is a short summary:
_wsetlocale( LC_ALL, L"Korean" );
Changing a global setting in a conversion function is unexpected, and will break code calling that. It's not even necessary either; you aren't using the locale for the encoding conversion.
HRESULT hr = ::StringCbLengthA( pszTextUTF8, cchUTF8Max, &cchUTF8 );
This is passing the wrong cchUTF8Max value (according to the documentation), and counts the number of bytes (vs. the number of characters, i.e. code units). Besides all that, you do not even need to know the number of code units, as you never use it (well, you are, but that is just another bug).
int cbUTF8 = static_cast<int>( cchUTF8 );
While that fixes the prefix (count of bytes as opposed to count of characters), it won't save you from using it later on for something that has an unrelated value.
strUTF16.GetBufferSetLength(cbUTF8);
This resizes the string object that should eventually hold the UTF-16 encoded characters. But it doesn't use the correct number of characters (the previous call to MultiByteToWideChar would have provided that value), but rather chooses a completely unrelated value: The number of bytes in the UTF-8 encoded source string.
But it doesn't just stop there, that line of code also throws away the pointer to the internal buffer, that was ready to be written to. Failure to call ReleaseBuffer is only a natural consequence, since you decided against reading the documentation.
WCHAR * pszUTF16 = new WCHAR[cchUTF16];
While not a bug in itself, it needlessly allocates another buffer (this time passing the correct size). You already allocated a buffer of the required size (albeit wrong) in the previous call to GetBufferSetLength. Just use that, that's what the member function is for.
strUTF16.Format(_T("%s"), pszUTF16);
That is probably the anti-pattern associated with the printf family of functions. It is the convoluted way to write CopyChars (or Append).
Now that that's cleared up, here is the correct way to write that function (or at least one way to do it):
CStringW ConvertUTF8ToUTF16( __in const CHAR * pszTextUTF8 ) {
// Allocate return value immediately, so that (N)RVO can be applied
CStringW strUTF16;
if ( (pszTextUTF8 == NULL) || (*pszTextUTF8 == '\0') ) {
return strUTF16;
}
// Calculate the required destination buffer size
int cchUTF16 = ::MultiByteToWideChar( CP_UTF8,
MB_ERR_INVALID_CHARS,
pszTextUTF8,
-1,
nullptr,
0 );
// Perform error checking
if ( cchUTF16 == 0 ) {
throw std::runtime_error( "MultiByteToWideChar failed." );
}
// Resize the output string size and use the pointer to the internal buffer
wchar_t* const pszUTF16 = strUTF16.GetBufferSetLength( cchUTF16 );
// Perform conversion (return value ignored, since we just checked for success)
::MultiByteToWideChar( CP_UTF8,
MB_ERR_INVALID_CHARS, // Use identical flags
pszTextUTF8,
-1,
pszUTF16,
cchUTF16 );
// Perform required cleanup
strUTF16.ReleaseBuffer();
// Return converted string
return strUTF16;
}

Show Mysql result with C in Gtktreeview

I try to use GtktreeView to show results of mysql query in C with following code which is called from change handler of gtkentry for getting "search as you type" efect:
...
result = mysql_store_result(conn);
if (result)
{
while ((row = mysql_fetch_row(result)))
{
gtk_list_store_append(store, &iter);
gtk_list_store_set(store, &iter, cID, row[0],
cCity, row[1],
cState, row[2],
cPop, atoi(row[3]),
cLast, "", -1);
}
}
etc...
Problem is that result can contain much data, to few thousand rows and while mysql is fast enough, that amount of data makes GtkTreeView unacceptable slow (much slower than typing and often shock computer). When I put LIMIT 20 in query this code works OK but then only first 20 rows of matched data are achievable. I think this is so slow because of all redrawing of gtktreeview is active.
In some toolkits it is possible to turn of all refreshes while list loads and then simple show results when finish with loading. Is something like that possible in GtkTreeView?
Or can I do something else? Like put this function in thread?
Or any other solution?
Thanks for advice in advanced!
I am not quite sure what your requirement is. Unfortunenately I have no prior experience with mysql either. But regarding using GtkEntryCompletion with GtkEntry to have a "search as you type" effect, you have to create a GtkEntryCompletion and set it to GtkEntry. Then you can set a model to entry completion from which completion data is picked. Here is a sample code based on gtk-demo source & coding.debuntu.org code:
#include <gtk/gtk.h>
#include <string.h>
static gboolean
on_match_select(GtkEntryCompletion *widget, GtkTreeModel *model,GtkTreeIter *iter, gpointer user_data)
{
GValue value = {0, };
GValue id = {0, };
gtk_tree_model_get_value(model, iter, 1, &value);
gtk_tree_model_get_value(model, iter, 0, &id);
fprintf(stdout, "You have selected value=\"%s\" with id = %d\n",
g_value_get_string(&value),
g_value_get_int(&id));
g_value_unset(&value);
g_value_unset(&id);
return FALSE;
}
/* Creates a tree model containing the completions */
static GtkTreeModel *
create_completion_model (void)
{
GtkListStore *store;
GtkTreeIter iter;
int id = 0;
char buffer[1024]={0,};
store = gtk_list_store_new (2, G_TYPE_INT, G_TYPE_STRING);
/* Here we add the data to be shown for completion */
/* Add 10000 strings */
for(id = 0; id < 10000; id++)
{
if(id%2)
snprintf(buffer, sizeof buffer -1, "homer #%d with %d", id/2, id);
else
snprintf(buffer, sizeof buffer -1, "marge #%d with %d", id/2, id);
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter, 0, id, 1, buffer, -1);
}
return GTK_TREE_MODEL (store);
}
int main (void)
{
GtkWidget *window;
GtkWidget *vbox;
GtkWidget *label;
GtkWidget *entry;
GtkEntryCompletion *completion;
GtkTreeModel *completion_model;
gtk_init (NULL, NULL);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window),"Sample entry completion");
g_signal_connect (window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
vbox = gtk_vbox_new (FALSE, 5);
gtk_container_set_border_width (GTK_CONTAINER (window), 5);
gtk_container_add(GTK_CONTAINER(window), vbox);
label = gtk_label_new (NULL);
gtk_label_set_markup (GTK_LABEL (label),
"Completion demo, try writing <b>homer/marge #...</b>; replace ... by a number b/w 0 & 9999.");
gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, FALSE, 0);
/* Create our entry */
entry = gtk_entry_new ();
gtk_box_pack_start (GTK_BOX (vbox), entry, FALSE, FALSE, 0);
/* Create the completion object */
completion = gtk_entry_completion_new ();
/* Assign the completion to the entry */
gtk_entry_set_completion (GTK_ENTRY (entry), completion);
g_object_unref (completion);
/* Create a tree model and use it as the completion model */
completion_model = create_completion_model ();
gtk_entry_completion_set_model (completion, completion_model);
/* Connect callback for match selection */
g_signal_connect(G_OBJECT (completion), "match-selected", G_CALLBACK (on_match_select), NULL);
g_object_unref (completion_model);
/* Use model column 1 (i.e. 2nd column) as the text column */
/* Model currently used has int (id) in 1st column & string (data) in 2nd column */
gtk_entry_completion_set_text_column (completion, 1);
gtk_widget_show_all (window);
gtk_main();
return 0;
}
Hopefully this is a bit faster than you current method.
Hope this helps!

Under what circumstances would a LINQ-to-SQL Entity "lose" a changed field?

I'm going nuts over what should be a very simple situation. In an ASP.NET MVC 2 app (not that I think this matters), I have an edit action which takes a very small entity and makes a few changes. The key portion (outside of error handling/security) looks like this:
Todo t = Repository.GetTodoByID(todoID);
UpdateModel(t);
Repository.Save();
Todo is the very simple, small entity with the following fields: ID (primary key), FolderID (foreign key), PercentComplete, TodoText, IsDeleted and SaleEffortID (foreign key). Each of these obviously corresponds to a field in the database.
When UpdateModel(t) is called, t does get correctly updated for all fields which have changed.
When Repository.Save() is called, by the time the SQL is written out, FolderID reverts back to its original value. The complete code to Repository.Save():
public void Save()
{
myDataContext.SubmitChanges();
}
myDataContext is an instance of the DataContext class created by the LINQ-to-SQL designer. Nothing custom has been done to this aside from adding some common interfaces to some of the entities.
I've validated that the FolderID is getting lost before the call to Repository.Save() by logging out the generated SQL:
UPDATE [Todo].[TD_TODO]
SET
[TD_PercentComplete] = #p4,
[TD_TodoText] = #p5,
[TD_IsDeleted] = #p6
WHERE
([TD_ID] = #p0) AND
([TD_TDF_ID] = #p1) AND /* Folder ID */
([TD_PercentComplete] = #p2) AND
([TD_TodoText] = #p3) AND
(NOT ([TD_IsDeleted] = 1)) AND
([TD_SE_ID] IS NULL) /* SaleEffort ID */
-- #p0: Input BigInt (Size = -1; Prec = 0; Scale = 0) [5]
-- #p1: Input BigInt (Size = -1; Prec = 0; Scale = 0) [1] /* this SHOULD be 4 and in the update list */
-- #p2: Input TinyInt (Size = -1; Prec = 0; Scale = 0) [90]
-- #p3: Input NVarChar (Size = 4000; Prec = 0; Scale = 0) [changing text]
-- #p4: Input TinyInt (Size = -1; Prec = 0; Scale = 0) [0]
-- #p5: Input NVarChar (Size = 4000; Prec = 0; Scale = 0) [changing text foo]
-- #p6: Input Bit (Size = -1; Prec = 0; Scale = 0) [True]
-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 4.0.30319.1
So somewhere between UpdateModel(t) (where I've validated in the debugger that FolderID updated) and the output of this SQL, the FolderID reverts. The other fields all save. (Well, OK, I haven't validated SaleEffortID yet, because that subsystem isn't really ready yet, but everything else saves.)
I've exhausted my own means of research on this: Does anyone know of conditions which would cause a partial entity reset (EG, something to do with long foreign keys?), and/or how to work around this?
The only thing I can think of, is if something forces the datacontext to load the related entity (which would be Folder in this case, I think) before the call to UpdateModel.
If you try to change FolderID after the Folder entity has been loaded, it will silently fail and retain it's old value. This can be kindof annoying. I don't know if this is the case here, however as you appear positive that the values are updated by the UpdateModel call.
Normally, if the foreign key is changed before the datacontext tries to load the related entity, then the correct entity will be loaded (the one with the new key), but somehow, maybe something happens that triggers a mysterious behaviour in this case - I know it's not much to go on, but I would definitely expect this to have something to do with deferred loading of the related entity.