问:
Service fabric upgrade created a error on VSTS build server
We have upgraded our Service Fabric SDK and tools from 2.5.216 to 2.6.210.

Now when we run a build on the VSTS hosted agent, the build fails during the acceptance test stage, which runs specflow acceptance tests via vstest.exe.

The error is:

Could not load type 'Microsoft.ServiceFabric.Data.Collections.IReliableConcurrentQueue`1' from assembly 'Microsoft.ServiceFabric.Data.Interfaces, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.","exceptionType":"System.TypeLoadException"

The tests work locally (with Microsoft Azure Service Fabric SDK and Tools 2.6.210 (VS2015) installed) using the same vstest.exe command.

Having looked at the specification of the hosted agent (https://www.visualstudio.com/en-us/docs/build/concepts/agents/hosted)
we've noted that the versions installed on the agent are Service Fabric 5.4.164.9494 / Service Fabric SDK 2.4.164, and suspect these
need to be updated.

Longer version of the error

2017-06-20T15:11:00.0331094Z Failed   I can make a request to change
  the allocation of a game type 2017-06-20T15:11:00.0331094Z

[error]Error Message: 2017-06-20T15:11:00.0341044Z ##[error]   System.Exception : Non matching response code: InternalServerError -

{"message":"An error has occurred.","exceptionMessage":"Could not load
  type
  'Microsoft.ServiceFabric.Data.Collections.IReliableConcurrentQueue1'
  from assembly 'Microsoft.ServiceFabric.Data.Interfaces,
  Version=5.0.0.0, Culture=neutral,
  PublicKeyToken=31bf3856ad364e35'.","exceptionType":"System.TypeLoadException","stackTrace":"
  at Infrastructure.ExceptionHandling.ExceptionHelper.ThrowIfUnhandled()
  in
  d:\\a\\1\\s\\Infrastructure\\Infrastructure.ExceptionHandling\\ExceptionHelper.cs:line
  45\r\n   at
  xwx.WebApi.Controllers.gameTypesController.<UpdategameType>d__8.MoveNext()
  in
  d:\\a\\1\\s\\Orchestration\\xwx\\xwx.WebApi\\Controllers\\gameTypesController.cs:line
  142\r\n--- End of stack trace from previous location where exception
  was thrown ---\r\n   at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)\r\n   at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)\r\n   at
  System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__31.MoveNext()\r\n---
  End of stack trace from previous location where exception was thrown
  ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)\r\n   at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)\r\n   at
  System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext()\r\n---
  End of stack trace from previous location where exception was thrown
  ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)\r\n   at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)\r\n   at
  System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext()\r\n---
  End of stack trace from previous location where exception was thrown
  ---\r\n   at System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext()\r\n---
  End of stack trace from previous location where exception was thrown
  ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)\r\n   at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)\r\n   at
  System.Web.Http.Filters.ActionFilterAttribute.d__0.MoveNext()\r\n---
  End of stack trace from previous location where exception was thrown
  ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)\r\n   at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)\r\n   at
  System.Web.Http.Controllers.ActionFilterResult.d__2.MoveNext()\r\n---
  End of stack trace from previous location where exception was thrown
  ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)\r\n   at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)\r\n   at
  System.Web.Http.Filters.AuthorizationFilterAttribute.d__2.MoveNext()\r\n---
  End of stack trace from previous location where exception was thrown
  ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)\r\n   at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)\r\n   at
  System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()"}
  2017-06-20T15:11:00.0341044Z ##[error]Stack Trace:
  2017-06-20T15:11:00.0341044Z ##[error]   at
  Infrastructure.TestHelpers.AcceptanceTests.ResponseHelper.AssertResponseHadExpectedStatusCode(Int32
  expectedStatusCode) in
  d:\a\1\s\Infrastructure\Infrastructure.TestHelpers\AcceptanceTests\ResponseHelper.cs:line
  25 2017-06-20T15:11:00.0341044Z ##[error]   at
  xwx.AcceptanceTests.ResponseSteps.ThenIShouldReceiveAHttpStatusCode(Int32
  expectedStatusCode) in
  d:\a\1\s\Tests\Orchestration\xwx\xwx.AcceptanceTests\ResponseSteps.cs:line
  12 2017-06-20T15:11:00.0341044Z ##[error]   at
  TechTalk.SpecFlow.Bindings.BindingInvoker.InvokeBinding(IBinding
  binding, IContextManager contextManager, Object[] arguments,
  ITestTracer testTracer, TimeSpan& duration)
  2017-06-20T15:11:00.0351049Z ##[error]   at
  TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.ExecuteStepMatch(BindingMatch
  match, Object[] arguments) 2017-06-20T15:11:00.0351049Z ##[error]   at
  TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.ExecuteStep(StepInstance
  stepInstance) 2017-06-20T15:11:00.0351049Z ##[error]   at
  TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.OnAfterLastStep()
  2017-06-20T15:11:00.0351049Z ##[error]   at
  xwx.AcceptanceTests.gameTypes.ChangeAllocation3532Feature.ScenarioCleanup()
  2017-06-20T15:11:00.0351049Z ##[error]   at
  xwx.AcceptanceTests.gameTypes.ChangeAllocation3532Feature.ICanMakeARequestToChangeTheAllocationOfAgameType()
  in
  d:\a\1\s\Tests\Orchestration\xwx\xwx.AcceptanceTests\gameTypes\ChangeAllocation.feature:line
  43Error Message: 2017-06-20T15:11:00.0351049Z ##[error]

  System.Exception : Non matching response code: NoContent -
  2017-06-20T15:11:00.0351049Z ##[error]Stack Trace:
  2017-06-20T15:11:00.0351049Z ##[error]   at
  Infrastructure.TestHelpers.AcceptanceTests.ResponseHelper.AssertResponseHadExpectedStatusCode(Int32
  expectedStatusCode) in
  d:\a\1\s\Infrastructure\Infrastructure.TestHelpers\AcceptanceTests\ResponseHelper.cs:line
  25 2017-06-20T15:11:00.0351049Z ##[error]   at
  xwx.AcceptanceTests.gameTypes.gameTypesSteps.WhenTheChangeHasCompleted()
  in
  d:\a\1\s\Tests\Orchestration\xwx\xwx.AcceptanceTests\gameTypes\gameTypesSteps.cs:line
  167 2017-06-20T15:11:00.0351049Z ##[error]   at
  TechTalk.SpecFlow.Bindings.BindingInvoker.InvokeBinding(IBinding
  binding, IContextManager contextManager, Object[] arguments,
  ITestTracer testTracer, TimeSpan& duration)
  2017-06-20T15:11:00.0351049Z ##[error]   at
  TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.ExecuteStepMatch(BindingMatch
  match, Object[] arguments) 2017-06-20T15:11:00.0351049Z ##[error]   at
  TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.ExecuteStep(StepInstance
  stepInstance) 2017-06-20T15:11:00.0351049Z ##[error]   at
  TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.OnAfterLastStep()
  2017-06-20T15:11:00.0351049Z ##[error]   at
  xwx.AcceptanceTests.gameTypes.ChangeAllocation3532Feature.ScenarioCleanup()
  2017-06-20T15:11:00.0361050Z  2017-06-20T15:11:00.0361050Z Failed   I
  can increase the allocation 2017-06-20T15:11:00.0361050Z
  2017-06-20T15:11:01.5390956Z ##[error]   at
  xwx.AcceptanceTests.gameTypes.ChangeAllocation3532Feature.ICanIncreaseTheAllocation()
  in
  d:\a\1\s\Tests\Orchestration\xwx\xwx.AcceptanceTests\gameTypes\ChangeAllocation.feature:line
  52Error Message: 2017-06-20T15:11:01.5400956Z ##[error]

  System.Exception : Non matching response code: NoContent -
  2017-06-20T15:11:01.5400956Z ##[error]Stack Trace:
  2017-06-20T15:11:01.5400956Z ##[error]   at
  Infrastructure.TestHelpers.AcceptanceTests.ResponseHelper.AssertResponseHadExpectedStatusCode(Int32
  expectedStatusCode) in
  d:\a\1\s\Infrastructure\Infrastructure.TestHelpers\AcceptanceTests\ResponseHelper.cs:line
  25 2017-06-20T15:11:01.5400956Z ##[error]   at
  xwx.AcceptanceTests.gameTypes.gameTypesSteps.WhenTheChangeHasCompleted()
  in
  d:\a\1\s\Tests\Orchestration\xwx\xwx.AcceptanceTests\gameTypes\gameTypesSteps.cs:line
  167 2017-06-20T15:11:01.5400956Z ##[error]   at
  TechTalk.SpecFlow.Bindings.BindingInvoker.InvokeBinding(IBinding
  binding, IContextManager contextManager, Object[] arguments,
  ITestTracer testTracer, TimeSpan& duration)
  2017-06-20T15:11:01.5400956Z ##[error]   at
  TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.ExecuteStepMatch(BindingMatch
  match, Object[] arguments) 2017-06-20T15:11:01.5400956Z ##[error]   at
  TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.ExecuteStep(StepInstance
  stepInstance) 2017-06-20T15:11:01.5400956Z ##[error]   at
  TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.OnAfterLastStep()
  2017-06-20T15:11:01.5400956Z ##[error]   at
  xwx.AcceptanceTests.gameTypes.ChangeAllocation3532Feature.ScenarioCleanup()
  2017-06-20T15:11:01.5400956Z Failed   If I try to reduce the
  allocation below the number of games available I can only reduce the
  allocation to the total available 2017-06-20T15:11:01.5400956Z
  2017-06-20T15:11:03.0426998Z ##[error]   at
  xwx.AcceptanceTests.gameTypes.ChangeAllocation3532Feature.IfITryToReduceTheAllocationBelowTheNumberOfgamesAvailableICanOnlyReduceTheAllocationToTheTotalAvailable()
  in
  d:\a\1\s\Tests\Orchestration\xwx\xwx.AcceptanceTests\gameTypes\ChangeAllocation.feature:line
  70Error Message: 2017-06-20T15:11:03.0426998Z ##[error]

  System.Exception : Non matching response code: NoContent -
  2017-06-20T15:11:03.0426998Z ##[error]Stack Trace:
  2017-06-20T15:11:03.0426998Z ##[error]   at
  Infrastructure.TestHelpers.AcceptanceTests.ResponseHelper.AssertResponseHadExpectedStatusCode(Int32
  expectedStatusCode) in
  d:\a\1\s\Infrastructure\Infrastructure.TestHelpers\AcceptanceTests\ResponseHelper.cs:line
  25 2017-06-20T15:11:03.0437002Z ##[error]   at
  xwx.AcceptanceTests.gameTypes.gameTypesSteps.WhenTheChangeHasCompleted()
  in
  d:\a\1\s\Tests\Orchestration\xwx\xwx.AcceptanceTests\gameTypes\gameTypesSteps.cs:line
  167 2017-06-20T15:11:03.0437002Z ##[error]   at
  TechTalk.SpecFlow.Bindings.BindingInvoker.InvokeBinding(IBinding
  binding, IContextManager contextManager, Object[] arguments,
  ITestTracer testTracer, TimeSpan& duration)
  2017-06-20T15:11:03.0437002Z ##[error]   at
  TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.ExecuteStepMatch(BindingMatch
  match, Object[] arguments) 2017-06-20T15:11:03.0437002Z ##[error]   at
  TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.ExecuteStep(StepInstance
  stepInstance) 2017-06-20T15:11:03.0437002Z ##[error]   at
  TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.OnAfterLastStep()
  2017-06-20T15:11:03.0437002Z ##[error]   at
  xwx.AcceptanceTests.gameTypes.ChangeAllocation3532Feature.ScenarioCleanup()
  2017-06-20T15:11:03.0437002Z ##[error]   at
  xwx.AcceptanceTests.gameTypes.ChangeAllocation3532Feature.ICanReduceTheAllocationByTheNumberOfgamesStillAvailable()
  in
  d:\a\1\s\Tests\Orchestration\xwx\xwx.AcceptanceTests\gameTypes\ChangeAllocation.feature:line
  61Error Message: 2017-06-20T15:11:03.0437002Z ##[error]

  System.Exception : Non matching response code: NoContent -
  2017-06-20T15:11:03.0437002Z ##[error]Stack Trace:
  2017-06-20T15:11:03.0437002Z ##[error]   at
  Infrastructure.TestHelpers.AcceptanceTests.ResponseHelper.AssertResponseHadExpectedStatusCode(Int32
  expectedStatusCode) in
  d:\a\1\s\Infrastructure\Infrastructure.TestHelpers\AcceptanceTests\ResponseHelper.cs:line
  25 2017-06-20T15:11:03.0437002Z ##[error]   at
  xwx.AcceptanceTests.gameTypes.gameTypesSteps.WhenTheChangeHasCompleted()
  in
  d:\a\1\s\Tests\Orchestration\xwx\xwx.AcceptanceTests\gameTypes\gameTypesSteps.cs:line
  167 2017-06-20T15:11:03.0437002Z ##[error]   at
  TechTalk.SpecFlow.Bindings.BindingInvoker.InvokeBinding(IBinding
  binding, IContextManager contextManager, Object[] arguments,
  ITestTracer testTracer, TimeSpan& duration)
  2017-06-20T15:11:03.0437002Z ##[error]   at
  TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.ExecuteStepMatch(BindingMatch
  match, Object[] arguments) 2017-06-20T15:11:03.0437002Z ##[error]   at
  TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.ExecuteStep(StepInstance
  stepInstance) 2017-06-20T15:11:03.0437002Z ##[error]   at
  TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.OnAfterLastStep()
  2017-06-20T15:11:03.0437002Z ##[error]   at
  xwx.AcceptanceTests.gameTypes.ChangeAllocation3532Feature.ScenarioCleanup()
  2017-06-20T15:11:03.0437002Z Failed   I can reduce the allocation by
  the number of games still available 2017-06-20T15:11:03.0437002Z

答:
Even if you're specifying platform target x64 on the build server, check your project build configuration to see if Release is set to platform target x64.

Also ensure the build server has the latest Service Fabric SDK installed. It's possible that the problematic build is picking up old assemblies from the GAC.

Here's the error I was getting,

```<code>System.TypeLoadException: Could not load type 'Microsoft.ServiceFabric.Data.IReliableStateManagerReplica2' from assembly 'Microsoft.ServiceFabric.Data.Interfaces, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
</code>```

Body:
Even if you're specifying platform target x64 on the build server, check your project build configuration to see if Release is set to platform target x64.

Also ensure the build server has the latest Service Fabric SDK installed. It's possible that the problematic build is picking up old assemblies from the GAC.

Here's the error I was getting,

System.TypeLoadException: Could not load type 'Microsoft.ServiceFabric.Data.IReliableStateManagerReplica2' from assembly 'Microsoft.ServiceFabric.Data.Interfaces, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'


来源: stackexchange

问:
C: Loop pops out even when condition is still satisfied
this is a demo of linklist written in C.

Description: The code is about manipulating the linkist like insert, delete, display the linked list.

problem:

I choose 1 to insert value to node (ex: 1) then value; 2,3,4...

Then I delete the head element the code exit. It's supposed to continue running as the condition of the loop is still satisfied.

same problem if you intend to display the linked list.

```<code>// ==============================
// Linked List Demo
// ==============================
// 1. Insert to head
// 2. Delete elements by value
// 3. Display all elements
// 4. Search an element
// 5. Delete an element by position
// 6. Exit
// ==============================
// Your choice:

#include<stdio.h>
#include<stdlib.h>

struct Node{
    int value;
    struct Node *next;
};
typedef struct Node intLinkedList;

int insertToHead();
void display(intLinkedList *head);
void displayForLoop(intLinkedList *head);
int deleteFromHead(intLinkedList **head);
int delete(int value, intLinkedList **head);
int indexOf(int value, intLinkedList *head);

void menu();
void menu(){
    char* mainMenu[] = {"Insert to head", "Delete", "Display", \
                         "Search Element", "Delete by position", "Exit"};
    printf("=====================================\n");
    for(int i = 0; i < 6; i++)
    {
        printf("%d. %s \n", i + 1,  mainMenu[i]);
    }
    printf("=====================================\n");
}
int main(){
    int choice;
    int value;
    intLinkedList *head;

    do{
        menu();
        printf("#Choice: ");
        scanf("%d", &choice);
        printf("--> %d", choice);
        switch(choice){
            case 1:
                printf("Input new Value to Linked List: ");
                scanf("%d", &value);
                insertToHead(value, &head);
                break;
            case 2:
                printf("Input new Value to delete : ");
                scanf("%d", &value);
                if(delete(value, &head)){
                    printf("%d removed from linked list \n", value);
                }else{
                    printf(" %d not in linked  list \n", value);
                }
                break;
            case 3:
                printf("Display all elements \n");
                display(head);
                break;
            case 4:
                printf("Input value to search: ");
                scanf("%d", &value);
                int found = indexOf(value, head);
                if( found < 0){
                    printf("%d is isn't in linked list ", value);
                }else{
                    printf("%d is in linked list at %d positino \n", value, found);
                }
                break;
            case 5:
                printf("Delete by position : ");
                break;
            case 6:
                printf("EXIT..");
                return 0;

            default:
                printf(": \n");
                break;
        }
    }while(choice != 6);
}

int insertToHead(int value, intLinkedList **head){
    intLinkedList *newElement;
    newElement = (intLinkedList*)malloc(sizeof(intLinkedList));
    newElement -> value = value;
    newElement -> next = *head;
    *head = newElement;
    return 1;
}

void displayForLoop(intLinkedList *head){
    intLinkedList *iterator;
    for(iterator=head; iterator!=NULL; iterator=iterator->next){
        printf("|value: %d| ->", iterator->value);
    }
    printf(" NULL\n");
}

void display(intLinkedList *head){
    intLinkedList *iterator;
    iterator = head;
    while( iterator != NULL){
        printf("|value : %d| -> ", iterator -> value);
        iterator = iterator -> next;
    }
    printf("NULL \n");
}
int deleteFromHead(intLinkedList **head){
    if( *head == NULL){
        return 0;
    }
    intLinkedList *del;
    del = *head;
    *head = del -> next;
    free(del);
    return 1;
}
int delete(int value, intLinkedList **head){
    intLinkedList *current;
    intLinkedList *pre;
    current = *head;
    pre = *head;
    int deleted = 0;

    if(current->value == value){
        printf("get here\n");
        deleteFromHead(head);
        return 1;
    }

    while(current != NULL){
        if(current->value == value){
            deleted = 1;
            if(current==*head){
                deleteFromHead(head);
                current = *head;
                pre = *head;
            }else{
                pre->next = current->next;
                free(current);
                current = pre->next;
            }
            continue;
        }
        pre = current;
        current = current->next;
    }
    return deleted;
}

int indexOf(int value, intLinkedList *head){
    intLinkedList *iterator;
    int i;
    for( iterator = head, i = 0; iterator != NULL; iterator = iterator -> next, i++){
        if(iterator -> value = value){
            return i;
        }
    }
    return -1;
}
</code>```

答: You're invoking undefined behavior by not initializing head. Consider the first time you insert an element, you call insertToHead .. then you execute newElement -> next = *head;.  head was not initialized, so *head is garbage, and your first element ->next value is "initialized" to some indeterminate value.  Your displayForLoop function, for instance, keeps looping until ->next is NULL.  This may not be the only problem but it is certainly a problem.  Whenever you traverse your linked-list looking for ->next == NULL as the marker for the end of the list, this is going to cause problems.  Initialize head with intLinkedList *head = NULL; to fix this problem.

ContentLicense: CC BY-SA 3.0

Body:
this is a demo of linklist written in C.

Description: The code is about manipulating the linkist like insert, delete, display the linked list.

problem:

I choose 1 to insert value to node (ex: 1) then value; 2,3,4...

Then I delete the head element the code exit. It's supposed to continue running as the condition of the loop is still satisfied.

same problem if you intend to display the linked list.

// ==============================
// Linked List Demo
// ==============================
// 1. Insert to head
// 2. Delete elements by value
// 3. Display all elements
// 4. Search an element
// 5. Delete an element by position
// 6. Exit
// ==============================
// Your choice:

#include<stdio.h>
#include<stdlib.h>

struct Node{
    int value;
    struct Node *next;
};
typedef struct Node intLinkedList;

int insertToHead();
void display(intLinkedList *head);
void displayForLoop(intLinkedList *head);
int deleteFromHead(intLinkedList **head);
int delete(int value, intLinkedList **head);
int indexOf(int value, intLinkedList *head);

void menu();
void menu(){
    char* mainMenu[] = {"Insert to head", "Delete", "Display", \
                         "Search Element", "Delete by position", "Exit"};
    printf("=====================================\n");
    for(int i = 0; i < 6; i++)
    {
        printf("%d. %s \n", i + 1,  mainMenu[i]);
    }
    printf("=====================================\n");
}
int main(){
    int choice;
    int value;
    intLinkedList *head;

    do{
        menu();
        printf("#Choice: ");
        scanf("%d", &choice);
        printf("--> %d", choice);
        switch(choice){
            case 1:
                printf("Input new Value to Linked List: ");
                scanf("%d", &value);
                insertToHead(value, &head);
                break;
            case 2:
                printf("Input new Value to delete : ");
                scanf("%d", &value);
                if(delete(value, &head)){
                    printf("%d removed from linked list \n", value);
                }else{
                    printf(" %d not in linked  list \n", value);
                }
                break;
            case 3:
                printf("Display all elements \n");
                display(head);
                break;
            case 4:
                printf("Input value to search: ");
                scanf("%d", &value);
                int found = indexOf(value, head);
                if( found < 0){
                    printf("%d is isn't in linked list ", value);
                }else{
                    printf("%d is in linked list at %d positino \n", value, found);
                }
                break;
            case 5:
                printf("Delete by position : ");
                break;
            case 6:
                printf("EXIT..");
                return 0;

            default:
                printf(": \n");
                break;
        }
    }while(choice != 6);
}

int insertToHead(int value, intLinkedList **head){
    intLinkedList *newElement;
    newElement = (intLinkedList*)malloc(sizeof(intLinkedList));
    newElement -> value = value;
    newElement -> next = *head;
    *head = newElement;
    return 1;
}

void displayForLoop(intLinkedList *head){
    intLinkedList *iterator;
    for(iterator=head; iterator!=NULL; iterator=iterator->next){
        printf("|value: %d| ->", iterator->value);
    }
    printf(" NULL\n");
}

void display(intLinkedList *head){
    intLinkedList *iterator;
    iterator = head;
    while( iterator != NULL){
        printf("|value : %d| -> ", iterator -> value);
        iterator = iterator -> next;
    }
    printf("NULL \n");
}
int deleteFromHead(intLinkedList **head){
    if( *head == NULL){
        return 0;
    }
    intLinkedList *del;
    del = *head;
    *head = del -> next;
    free(del);
    return 1;
}
int delete(int value, intLinkedList **head){
    intLinkedList *current;
    intLinkedList *pre;
    current = *head;
    pre = *head;
    int deleted = 0;

    if(current->value == value){
        printf("get here\n");
        deleteFromHead(head);
        return 1;
    }

    while(current != NULL){
        if(current->value == value){
            deleted = 1;
            if(current==*head){
                deleteFromHead(head);
                current = *head;
                pre = *head;
            }else{
                pre->next = current->next;
                free(current);
                current = pre->next;
            }
            continue;
        }
        pre = current;
        current = current->next;
    }
    return deleted;
}

int indexOf(int value, intLinkedList *head){
    intLinkedList *iterator;
    int i;
    for( iterator = head, i = 0; iterator != NULL; iterator = iterator -> next, i++){
        if(iterator -> value = value){
            return i;
        }
    }
    return -1;
}


问:
AndroidViewModel - Making duplicate calls doesn't return data in observe function
My question is related to ViewModel second time returns null wherein I am not getting callback inobserve function if I make a repeated call to server. Following is the code I am using -

```<code>@Singleton
public class NetworkInformationViewModel extends AndroidViewModel {
  private LiveData<Resource<NetworkInformation>> networkInfoObservable;
  private final APIClient apiClient;

  @Inject
  NetworkInformationViewModel(@NonNull APIClient apiClient, @NonNull Application application) {
    super(application);
    this.apiClient = apiClient;
    getNetworkInformation();
  }

  public LiveData<Resource<NetworkInformation>> getNetworkInfoObservable() {
    return networkInfoObservable;
  }

  // making API calls and adding it to Observable
  public void getNetworkInformation() {
    networkInfoObservable = apiClient.getNetworkInformation();
  }
}
</code>```

In Activity, the ViewModel is defined as followed -

```<code>final NetworkInformationViewModel networkInformationViewModel =
      ViewModelProviders.of(this, viewModelFactory).get(NetworkInformationViewModel.class);
    observeViewModel(networkInformationViewModel);
</code>```

The observeViewModel function is used to add observable on ViewModel.

```<code>public void observeViewModel(final NetworkInformationViewModel networkInformationViewModel) {
    networkInformationViewModel.getNetworkInfoObservable()
      .observe(this, networkInformationResource -> {
        if (networkInformationResource != null) {
          if (networkInformationResource.status == APIClientStatus.Status.SUCCESS) {
            Timber.d("Got network information data");
          } else {
            final Throwable throwable = networkInformationResource.throwable;
            if (throwable instanceof SocketTimeoutException) {
              final NetworkInformation networkInformation = networkInformationResource.data;
              String error = null;
              if (networkInformation != null) {
                error = TextUtils.isEmpty(networkInformation.error) ? networkInformation.reply : networkInformation.error;
              }
              Timber.e("Timeout error occurred %s %s", networkInformationResource.message, error);

            } else {
              Timber.e("Error occurred %s", networkInformationResource.message);
            }
            if (count != 4) {
              networkInformationViewModel.getNetworkInformation();
              count++;
              // Uncommenting following line enables callback to be received every time
              //observeViewModel(networkInformationViewModel);
            }
          }
        }
      });
  }
</code>```

Uncommenting the following line in above function allows the callback to come everytime, but there has to be a proper way of doing this.

```<code>//observeViewModel(networkInformationViewModel);
</code>```

Please note:-
I don't need RxJava implementation for implementing this.

答:
Right now in getNetworkInformation() you are:

Creating a new LiveData

Updating the the LiveData using setValue

Instead, you should have a single LiveData for APIClient created as a member variable, then in getNetworkInformation() just update that member LiveData.

More generally, your APIClient is a data source. For data sources, you can have them contain member LiveData objects that update when the data changes. You can provide getters to those LiveData objects to make them accessible in ViewModels, and ultimately listen to them in your Activities/Fragments. This is similar how you might take another data source, such as Room, and listen to a LiveData returned by Room.

So the code in this case would look like:

```<code>@Singleton
public class APIClient {
    private final MutableLiveData<Resource<NetworkInformation>> mNetworkData = new MutableLiveData<>(); // Note this needs to be MutableLiveData so that you can call setValue

    // This is basically the same code as the original getNetworkInformation, instead this returns nothing and just updates the LiveData
    public void fetchNetworkInformation() {
        apiInterface.getNetworkInformation().enqueue(new Callback<NetworkInformation>() {
          @Override
          public void onResponse(
            @NonNull Call<NetworkInformation> call, @NonNull Response<NetworkInformation> response
          ) {
            if (response.body() != null && response.isSuccessful()) {
              mNetworkData.setValue(new Resource<>(APIClientStatus.Status.SUCCESS, response.body(), null));
            } else {
              mNetworkData.setValue(new Resource<>(APIClientStatus.Status.ERROR, null, response.message()));
            }
          }

          @Override
          public void onFailure(@NonNull Call<NetworkInformation> call, @NonNull Throwable throwable) {
            mNetworkData.setValue(
              new Resource<>(APIClientStatus.Status.ERROR, null, throwable.getMessage(), throwable));
          }
        });
    }

    // Use a getter method so that you can return immutable LiveData since nothing outside of this class will change the value in mNetworkData
    public LiveData<Resource<NetworkInformation>> getNetworkData(){
        return mNetworkData;
    }

}
</code>```

Then in your ViewModel...

```<code>// I don't think this should be a Singleton; ViewModelProviders will keep more than one from being instantiate for the same Activity/Fragment lifecycle
public class SplashScreenViewModel extends AndroidViewModel {

private LiveData<Resource<NetworkInformation>> networkInformationLiveData;

  @Inject
  SplashScreenViewModel(@NonNull APIClient apiClient, @NonNull Application application) {
    super(application);
    this.apiClient = apiClient;

    // Initializing the observable with empty data
    networkInfoObservable = apiClient.getNetworkData()

  }

  public LiveData<Resource<NetworkInformation>> getNetworkInfoObservable() {
    return networkInformationLiveData;
  }

}
</code>```

Your activity can be the same as you originally coded it; it will just get and observe the LiveData from the ViewModel.

So what is Transformations.switchMap for?

switchMap isn't necessary here because you don't need to change the underlying LiveData instance in APIClient. This is because there's really only one piece of changing data. Let's say instead your APIClient needed 4 different LiveData for some reason, and you wanted to change which LiveData you observed:

```<code>public class APIClient {
    private MutableLiveData<Resource<NetworkInformation>> mNetData1, mNetData2, mNetData3, mNetData4;

    ...
}
</code>```

Then let's say that your fetchNetworkInformation would refer to different LiveData to observe depending on the situation. It might look like this:

```<code>public  LiveData<Resource<NetworkInformation>> getNetworkInformation(int keyRepresentingWhichLiveDataToObserve) {
    LiveData<Resource<NetworkInformation>> currentLiveData = null;
    switch (keyRepresentingWhichLiveDataToObserve) {
        case 1:
            currentLiveData = mNetData1;
            break;
        case 2:
            currentLiveData = mNetData2;
            break;
        //.. so on
    }

    // Code that actually changes the LiveData value if needed here

    return currentLiveData;
}
</code>```

In this case the actual LiveData coming from getNetworkInformation is changes, and you're also using some sort of parameter to determine which LiveData you want. In this case, you'd use a switchMap, because you want to make sure that the observe statement you called in your Activity/Fragment observes the LiveData returned from your APIClient, even if you change the underlying LiveData instance. And you don't want to call observe again.

Now this is a bit of an abstract example, but it's basically what your calls to a Room Dao do -- if you have a Dao method that queries your RoomDatabase based on an id and returns a LiveData, it will return a different LiveData instance based on the id.

Body:
My question is related to ViewModel second time returns null wherein I am not getting callback inobserve function if I make a repeated call to server. Following is the code I am using -

@Singleton
public class NetworkInformationViewModel extends AndroidViewModel {
  private LiveData<Resource<NetworkInformation>> networkInfoObservable;
  private final APIClient apiClient;

  @Inject
  NetworkInformationViewModel(@NonNull APIClient apiClient, @NonNull Application application) {
    super(application);
    this.apiClient = apiClient;
    getNetworkInformation();
  }

  public LiveData<Resource<NetworkInformation>> getNetworkInfoObservable() {
    return networkInfoObservable;
  }

  // making API calls and adding it to Observable
  public void getNetworkInformation() {
    networkInfoObservable = apiClient.getNetworkInformation();
  }
}

In Activity, the ViewModel is defined as followed -

final NetworkInformationViewModel networkInformationViewModel =
      ViewModelProviders.of(this, viewModelFactory).get(NetworkInformationViewModel.class);
    observeViewModel(networkInformationViewModel);

The observeViewModel function is used to add observable on ViewModel.

public void observeViewModel(final NetworkInformationViewModel networkInformationViewModel) {
    networkInformationViewModel.getNetworkInfoObservable()
      .observe(this, networkInformationResource -> {
        if (networkInformationResource != null) {
          if (networkInformationResource.status == APIClientStatus.Status.SUCCESS) {
            Timber.d("Got network information data");
          } else {
            final Throwable throwable = networkInformationResource.throwable;
            if (throwable instanceof SocketTimeoutException) {
              final NetworkInformation networkInformation = networkInformationResource.data;
              String error = null;
              if (networkInformation != null) {
                error = TextUtils.isEmpty(networkInformation.error) ? networkInformation.reply : networkInformation.error;
              }
              Timber.e("Timeout error occurred %s %s", networkInformationResource.message, error);

            } else {
              Timber.e("Error occurred %s", networkInformationResource.message);
            }
            if (count != 4) {
              networkInformationViewModel.getNetworkInformation();
              count++;
              // Uncommenting following line enables callback to be received every time
              //observeViewModel(networkInformationViewModel);
            }
          }
        }
      });
  }

Uncommenting the following line in above function allows the callback to come everytime, but there has to be a proper way of doing this.

//observeViewModel(networkInformationViewModel);

Please note:-
I don't need RxJava implementation for implementing this.

Body:
Right now in getNetworkInformation() you are:

Creating a new LiveData

Updating the the LiveData using setValue

Instead, you should have a single LiveData for APIClient created as a member variable, then in getNetworkInformation() just update that member LiveData.

More generally, your APIClient is a data source. For data sources, you can have them contain member LiveData objects that update when the data changes. You can provide getters to those LiveData objects to make them accessible in ViewModels, and ultimately listen to them in your Activities/Fragments. This is similar how you might take another data source, such as Room, and listen to a LiveData returned by Room.

So the code in this case would look like:

@Singleton
public class APIClient {
    private final MutableLiveData<Resource<NetworkInformation>> mNetworkData = new MutableLiveData<>(); // Note this needs to be MutableLiveData so that you can call setValue

    // This is basically the same code as the original getNetworkInformation, instead this returns nothing and just updates the LiveData
    public void fetchNetworkInformation() {
        apiInterface.getNetworkInformation().enqueue(new Callback<NetworkInformation>() {
          @Override
          public void onResponse(
            @NonNull Call<NetworkInformation> call, @NonNull Response<NetworkInformation> response
          ) {
            if (response.body() != null && response.isSuccessful()) {
              mNetworkData.setValue(new Resource<>(APIClientStatus.Status.SUCCESS, response.body(), null));
            } else {
              mNetworkData.setValue(new Resource<>(APIClientStatus.Status.ERROR, null, response.message()));
            }
          }

          @Override
          public void onFailure(@NonNull Call<NetworkInformation> call, @NonNull Throwable throwable) {
            mNetworkData.setValue(
              new Resource<>(APIClientStatus.Status.ERROR, null, throwable.getMessage(), throwable));
          }
        });
    }

    // Use a getter method so that you can return immutable LiveData since nothing outside of this class will change the value in mNetworkData
    public LiveData<Resource<NetworkInformation>> getNetworkData(){
        return mNetworkData;
    }

}

Then in your ViewModel...

// I don't think this should be a Singleton; ViewModelProviders will keep more than one from being instantiate for the same Activity/Fragment lifecycle
public class SplashScreenViewModel extends AndroidViewModel {

private LiveData<Resource<NetworkInformation>> networkInformationLiveData;

  @Inject
  SplashScreenViewModel(@NonNull APIClient apiClient, @NonNull Application application) {
    super(application);
    this.apiClient = apiClient;

    // Initializing the observable with empty data
    networkInfoObservable = apiClient.getNetworkData()

  }

  public LiveData<Resource<NetworkInformation>> getNetworkInfoObservable() {
    return networkInformationLiveData;
  }

}

Your activity can be the same as you originally coded it; it will just get and observe the LiveData from the ViewModel.

So what is Transformations.switchMap for?

switchMap isn't necessary here because you don't need to change the underlying LiveData instance in APIClient. This is because there's really only one piece of changing data. Let's say instead your APIClient needed 4 different LiveData for some reason, and you wanted to change which LiveData you observed:

public class APIClient {
    private MutableLiveData<Resource<NetworkInformation>> mNetData1, mNetData2, mNetData3, mNetData4;

    ...
}

Then let's say that your fetchNetworkInformation would refer to different LiveData to observe depending on the situation. It might look like this:

public  LiveData<Resource<NetworkInformation>> getNetworkInformation(int keyRepresentingWhichLiveDataToObserve) {
    LiveData<Resource<NetworkInformation>> currentLiveData = null;
    switch (keyRepresentingWhichLiveDataToObserve) {
        case 1:
            currentLiveData = mNetData1;
            break;
        case 2:
            currentLiveData = mNetData2;
            break;
        //.. so on
    }

    // Code that actually changes the LiveData value if needed here

    return currentLiveData;
}

In this case the actual LiveData coming from getNetworkInformation is changes, and you're also using some sort of parameter to determine which LiveData you want. In this case, you'd use a switchMap, because you want to make sure that the observe statement you called in your Activity/Fragment observes the LiveData returned from your APIClient, even if you change the underlying LiveData instance. And you don't want to call observe again.

Now this is a bit of an abstract example, but it's basically what your calls to a Room Dao do -- if you have a Dao method that queries your RoomDatabase based on an id and returns a LiveData, it will return a different LiveData instance based on the id.


问:
how do i wait to get the response from img.onload
THE CHECKSIZE FUNCTION RETURNS UNDEFINED---
    immediately it hits img.onload it jumps to the end of checksize</p>

```<code>function checksize(files)
{
    var img = new Image();
    img.onload = function () {
    var sizes = {
        width: this.width,
        height: this.height
    };
    if (sizes.width != 600 || sizes.height != 800)
    {
        alert("Error: Image size should be 600 x 800px");
        return false;

    }
    else
    {
        return true;
    }
    img.src = _URL.createObjectURL(files[0]);
};
</code>```

答:
you are missing closing braces for the main function due to which your img.src is inside the img.load which is wrong, change it to look like following and you are comparing exact length so only the exact dimension image would return true i have changed the code a little bit to append the images to the body once they are loaded and i changed the condition if (sizes.width != 600 || sizes.height != 800) to if (sizes.width <= 600 || sizes.height <= 800) { so the images that are smaller than the 800 x 600 are not appended to the body and the error is thrown on the console you can change the condition back

```<code>function checksize(files) {
  var img = new Image();

  img.onload = function() {
    var sizes = {
      width: img.width,
      height: img.height
    };

    if (sizes.width <= 600 || sizes.height <= 800) {
      console.log("Error: Image size should be greater 600 x 800px , image " + img.src + ' could not be loaded');
      return false;
    } else {
      $('body').append(img);
      return true;
    }

  };
  img.src = files;

}
</code>```

function checksize(files) {
  var img = new Image();

  img.onload = function() {
    var sizes = {
      width: img.width,
      height: img.height
    };

    if (sizes.width <= 600 || sizes.height <= 800) {
      console.log("Error: Image size should be greater 600 x 800px , image " + img.src + ' could not be loaded');
      return false;
    } else {
      $('body').append(img);
      return true;
    }

  };
  img.src = files;

}

var files = ['https://www.animalfriends.co.uk/app/uploads/2017/04/21150218/iStock-524369488.jpg', 'https://static.pexels.com/photos/356378/pexels-photo-356378.jpeg', 'https://www.pets4homes.co.uk/images/articles/238/large/44186f3f7c3e962827e462a95d7206bc.jpg'];

for (var i = 0; i < files.length; i++) {
  checksize(files[i]);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>img {
  width: 250px;
  height: 250px;
}</code>```

```

Body:
THE CHECKSIZE FUNCTION RETURNS UNDEFINED---
    immediately it hits img.onload it jumps to the end of checksize

function checksize(files)
{
    var img = new Image();
    img.onload = function () {
    var sizes = {
        width: this.width,
        height: this.height
    };
    if (sizes.width != 600 || sizes.height != 800)
    {
        alert("Error: Image size should be 600 x 800px");
        return false;

    }
    else
    {
        return true;
    }
    img.src = _URL.createObjectURL(files[0]);
};

Body:
you are missing closing braces for the main function due to which your img.src is inside the img.load which is wrong, change it to look like following and you are comparing exact length so only the exact dimension image would return true i have changed the code a little bit to append the images to the body once they are loaded and i changed the condition if (sizes.width != 600 || sizes.height != 800) to if (sizes.width <= 600 || sizes.height <= 800) { so the images that are smaller than the 800 x 600 are not appended to the body and the error is thrown on the console you can change the condition back

function checksize(files) {
  var img = new Image();

  img.onload = function() {
    var sizes = {
      width: img.width,
      height: img.height
    };

    if (sizes.width <= 600 || sizes.height <= 800) {
      console.log("Error: Image size should be greater 600 x 800px , image " + img.src + ' could not be loaded');
      return false;
    } else {
      $('body').append(img);
      return true;
    }

  };
  img.src = files;

}

function checksize(files) {
  var img = new Image();

  img.onload = function() {
    var sizes = {
      width: img.width,
      height: img.height
    };

    if (sizes.width <= 600 || sizes.height <= 800) {
      console.log("Error: Image size should be greater 600 x 800px , image " + img.src + ' could not be loaded');
      return false;
    } else {
      $('body').append(img);
      return true;
    }

  };
  img.src = files;

}

var files = ['https://www.animalfriends.co.uk/app/uploads/2017/04/21150218/iStock-524369488.jpg', 'https://static.pexels.com/photos/356378/pexels-photo-356378.jpeg', 'https://www.pets4homes.co.uk/images/articles/238/large/44186f3f7c3e962827e462a95d7206bc.jpg'];

for (var i = 0; i < files.length; i++) {
  checksize(files[i]);
}

img {
  width: 250px;
  height: 250px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
RxJava2. Process different properties of the object from the list
Assume

There is a class User with two properties name and age

We get a list of users

We need to process both properties of every user.

Is it possible at all to process both properties of every user?

The following code is not correct, I know. but how to make it correct? Maybe there are any operators to get it work?

```<code>Observable.fromIterable(users)
    .map(user -> user.name)
    .map(string -> new NameVM(string))
    .map(user -> user.age)
    .map(int -> new AgeVM(int))
</code>```

I have only one idea, but I don't like it much

```<code>Observable.fromIterable(users)
    .doOnNext(user -> new NameVM(string))
    .map(user -> user.age)
    .map(int -> new AgeVM(int))
</code>```

答:
I ended up with a container solution</p>

```<code>class ContainerVM {
    public NameVM nameVM;
    public AgeVM ageVM;
}

Observable.fromIterable(users)
    .map(user -> buildContainerVM(user));

private ContainerVM buildContainerVM(User user) {
    ContainerVM containerVM = new ContainerVM();
    containerVM.nameVM = new NameVM(user.name);
    containerVM.ageVM = new AgeVM(user.age);
}
</code>```

Body:
Assume

There is a class User with two properties name and age

We get a list of users

We need to process both properties of every user.

Is it possible at all to process both properties of every user?

The following code is not correct, I know. but how to make it correct? Maybe there are any operators to get it work?

Observable.fromIterable(users)
    .map(user -> user.name)
    .map(string -> new NameVM(string))
    .map(user -> user.age)
    .map(int -> new AgeVM(int))

I have only one idea, but I don't like it much

Observable.fromIterable(users)
    .doOnNext(user -> new NameVM(string))
    .map(user -> user.age)
    .map(int -> new AgeVM(int))

Body:
I ended up with a container solution

class ContainerVM {
    public NameVM nameVM;
    public AgeVM ageVM;
}

Observable.fromIterable(users)
    .map(user -> buildContainerVM(user));

private ContainerVM buildContainerVM(User user) {
    ContainerVM containerVM = new ContainerVM();
    containerVM.nameVM = new NameVM(user.name);
    containerVM.ageVM = new AgeVM(user.age);
}


问:
Cannot resolve method success.unapply when working with a Future[Unit]
I'm trying to execute some code in a Future, which persists some data to a REST endpoint, which, itself makes a DB call. I'm trying to execute it in a Future so it doesn't hold up the other code around it, which may be time-sensitive. I don't really care what happens in the Future code if it's successful, so I'm trying to execute a Future[Unit]. However, when I try to write the following code, IntelliJ underlines my Success(_) saying

cannot resolve method success.unapply

Here's my code:

```<code>def persistProgress():Unit = {
    val result:Future[Unit] = Future {
      //API Rest Call here with a case class
    }
    result.onComplete {
      case Success (_) => // do nothing if successful
      case Failure(e) => logger.info("Unable to persist" + e.getMessage)
    }

}
</code>```

Any idea how to do this?

答: Are you sure you get proper imports? Particularly that Success and Failure come from Try i.e. scala.util.Success and scala.util.Failure. Your code with proper imports seems to work Ok as you can see here.

Body:
I'm trying to execute some code in a Future, which persists some data to a REST endpoint, which, itself makes a DB call. I'm trying to execute it in a Future so it doesn't hold up the other code around it, which may be time-sensitive. I don't really care what happens in the Future code if it's successful, so I'm trying to execute a Future[Unit]. However, when I try to write the following code, IntelliJ underlines my Success(_) saying

cannot resolve method success.unapply

Here's my code:

def persistProgress():Unit = {
    val result:Future[Unit] = Future {
      //API Rest Call here with a case class
    }
    result.onComplete {
      case Success (_) => // do nothing if successful
      case Failure(e) => logger.info("Unable to persist" + e.getMessage)
    }

}

Any idea how to do this?


问:
WxPython Window Splitter
I am trying to use window splitter to get 6 different subwindows. Three columns and two rows. So far I am trying to use nested splitters, but it is not working.

This is the code I have:

```<code>import wx

########################################################################
class RandomPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent, color):
        """Constructor"""
        wx.Panel.__init__(self, parent)
        self.SetBackgroundColour(color)

########################################################################
class MainPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)

        topSplitter = wx.SplitterWindow(self)
        vSplitter = wx.SplitterWindow(topSplitter)

        panelOne = RandomPanel(vSplitter, "blue")
        panelTwo = RandomPanel(vSplitter, "red")
        vSplitter.SplitVertically(panelOne, panelTwo)
        vSplitter.SetSashGravity(0.5)

        panelThree = RandomPanel(topSplitter, "green")
        topSplitter.SplitHorizontally(vSplitter, panelThree)
        topSplitter.SetSashGravity(0.5)

        panelFour=RandomPanel(hSplitter, "yellow")
        hSplitter.SplitVertically(topSplitter, panelFour)
        hSplitter.SetSashGravity(0.5)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(topSplitter, 1, wx.EXPAND)
        self.SetSizer(sizer)
</code>```

#

```<code>class MainFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="Nested Splitters",
                          size=(800,600))
        panel = MainPanel(self)
        self.Show()
</code>```

----------------------------------------------------------------------

```<code>if __name__ == "__main__":
    app = wx.App(False)
    frame = MainFrame()
    app.MainLoop()
</code>```

For this I am just trying to get 4 subwindows not 6, and I still get an error.

答:
You might want to check out the MultiSplitterWindow widget:

https://wxpython.org/Phoenix/docs/html/wx.lib.splitter.MultiSplitterWindow.html

It allows you to have more than two windows in a splitter window widget. I actually wrote a bit about the various splitter windows that wxPython supports over on my blog, so you might want to check that out too.

Anyway, here is a simple example that uses that widget:

```<code>import wx
from wx.lib.splitter import MultiSplitterWindow

class SplitterPanel(wx.Panel):

    def __init__(self, parent, color):
        """Constructor"""
        wx.Panel.__init__(self, parent)
        main_sizer = wx.BoxSizer(wx.VERTICAL)

        splitter = MultiSplitterWindow(self, style=wx.SP_LIVE_UPDATE)
        for col in range(3):
            panel = wx.Panel(splitter, size=(200, 200))
            panel.SetBackgroundColour(color)
            splitter.AppendWindow(panel)

        main_sizer.Add(splitter, 1, wx.ALL|wx.EXPAND)
        self.SetSizer(main_sizer)

class MainFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, title='Splitters')
        panel = wx.Panel(self)
        main_sizer = wx.BoxSizer(wx.VERTICAL)

        splitter_panel = SplitterPanel(panel, color='blue')
        main_sizer.Add(splitter_panel, 1, wx.ALL|wx.EXPAND)

        splitter_panel_two = SplitterPanel(panel, color='red')
        main_sizer.Add(splitter_panel_two, 1, wx.ALL|wx.EXPAND)

        panel.SetSizer(main_sizer)

        self.Show()

if __name__ == '__main__':
    app = wx.App(False)
    frame = MainFrame()
    app.MainLoop()
</code>```

Title: WxPython Window Splitter

Body:
I am trying to use window splitter to get 6 different subwindows. Three columns and two rows. So far I am trying to use nested splitters, but it is not working.

This is the code I have:

import wx

########################################################################
class RandomPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent, color):
        """Constructor"""
        wx.Panel.__init__(self, parent)
        self.SetBackgroundColour(color)

########################################################################
class MainPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)

        topSplitter = wx.SplitterWindow(self)
        vSplitter = wx.SplitterWindow(topSplitter)

        panelOne = RandomPanel(vSplitter, "blue")
        panelTwo = RandomPanel(vSplitter, "red")
        vSplitter.SplitVertically(panelOne, panelTwo)
        vSplitter.SetSashGravity(0.5)

        panelThree = RandomPanel(topSplitter, "green")
        topSplitter.SplitHorizontally(vSplitter, panelThree)
        topSplitter.SetSashGravity(0.5)

        panelFour=RandomPanel(hSplitter, "yellow")
        hSplitter.SplitVertically(topSplitter, panelFour)
        hSplitter.SetSashGravity(0.5)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(topSplitter, 1, wx.EXPAND)
        self.SetSizer(sizer)

#

class MainFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="Nested Splitters",
                          size=(800,600))
        panel = MainPanel(self)
        self.Show()

----------------------------------------------------------------------

if __name__ == "__main__":
    app = wx.App(False)
    frame = MainFrame()
    app.MainLoop()

For this I am just trying to get 4 subwindows not 6, and I still get an error.

Body:
You might want to check out the MultiSplitterWindow widget:

https://wxpython.org/Phoenix/docs/html/wx.lib.splitter.MultiSplitterWindow.html

It allows you to have more than two windows in a splitter window widget. I actually wrote a bit about the various splitter windows that wxPython supports over on my blog, so you might want to check that out too.

Anyway, here is a simple example that uses that widget:

import wx
from wx.lib.splitter import MultiSplitterWindow

class SplitterPanel(wx.Panel):

    def __init__(self, parent, color):
        """Constructor"""
        wx.Panel.__init__(self, parent)
        main_sizer = wx.BoxSizer(wx.VERTICAL)

        splitter = MultiSplitterWindow(self, style=wx.SP_LIVE_UPDATE)
        for col in range(3):
            panel = wx.Panel(splitter, size=(200, 200))
            panel.SetBackgroundColour(color)
            splitter.AppendWindow(panel)

        main_sizer.Add(splitter, 1, wx.ALL|wx.EXPAND)
        self.SetSizer(main_sizer)

class MainFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, title='Splitters')
        panel = wx.Panel(self)
        main_sizer = wx.BoxSizer(wx.VERTICAL)

        splitter_panel = SplitterPanel(panel, color='blue')
        main_sizer.Add(splitter_panel, 1, wx.ALL|wx.EXPAND)

        splitter_panel_two = SplitterPanel(panel, color='red')
        main_sizer.Add(splitter_panel_two, 1, wx.ALL|wx.EXPAND)

        panel.SetSizer(main_sizer)

        self.Show()

if __name__ == '__main__':
    app = wx.App(False)
    frame = MainFrame()
    app.MainLoop()


问:
Python - loop through subfolders and files in a directory without ignoring the subfolder
I have read all the stack exchange help files on looping through subfolders, as as well as the os documentation, but I am still stuck. I am trying to loop over files in subfolders, open each file, extract the first number in the first line, copy the file to a different subfolder(with the same name but in the output directory) and rename the file copy with the number as a suffix.

```<code>import os
import re
outputpath = "C:/Users/Heather/Dropbox/T_Files/Raw_FRUS_Data/Wisconsin_Copies_With_PageNumbers"
inputpath = "C:/Users/Heather/Dropbox/T_Files/Raw_FRUS_Data/FRUS_Wisconsin"
suffix=".txt"
for root, dirs, files  in os.walk(inputpath):
    for file in files:
        file_path = os.path.join(root, file)
        foldername=os.path.split(os.path.dirname(file_path))[1]
        filebname=os.path.splitext(file)[0]
        filename=filebname + "_"
        f=open(os.path.join(root,file),'r')
        data=f.readlines()
        if data is None:
            f.close()
        else:
            with open(os.path.join(root,file),'r') as f:
                for line in f:
                    s=re.search(r'\d+',line)
                    if s:
                        pagenum=(s.group())
                        break
        with open(os.path.join(outputpath, foldername,filename+pagenum+suffix), 'w') as f1:
            with open(os.path.join(root,file),'r') as f:
                for line in f:
                    f1.write(line)
</code>```

I expect the result to be copies of the files in the input directory placed in the corresponding subfolder in the output directory, renamed with a suffix, such as "005_2", where 005 is the original file name, and 2 is the number the python code extracted from it.

The error I get seems to indicates that I am not looping through files correctly. I know the code for extracting the first number and renaming the file works because I tested it on a single file. But using os.walk to loop through multiple subfolders is not working, and I can't figure out what I am doing wrong. Here is the error:

```<code>File "<ipython-input-1-614e2851f16a>", line 23, in <module>
    with open(os.path.join(outputpath, foldername,filename+pagenum+suffix), 'w') as f1:
IOError: [Errno 2] No such file or directory: 'C:/Users/Heather/Dropbox/T_Files/Raw_FRUS_Data/Wisconsin_Copies_With_PageNumbers\\FRUS_Wisconsin\\.dropbox_1473986809.txt'
</code>```

答:
Well, this isn't eloquent, but it worked</p>

```<code>from glob import glob
folderlist=glob("C:\\...FRUS_Wisconsin*\\")
outputpath = "C:\\..\Wisconsin_Copies_With_PageNumbers"
for folder in folderlist:
    foldername = str(folder.split('\\')[7])
    for root, dirs, files in os.walk(folder):
        for file in files:
            filebname=os.path.splitext(file)[0]
            filename=filebname + "_"
            if not filename.startswith('._'):
                with open(os.path.join(root,file),'r') as f:
                    for line in f:
                        s=re.search(r'\d+',line)
                        if s:
                           pagenum=(s.group())
                           break
                     with open(os.path.join(outputpath, foldername,filename+pagenum+suffix), 'w') as f1:
                        with open(os.path.join(root,file),'r') as f:
                            for line in f:
                                f1.write(line)
</code>```

Body:
I have read all the stack exchange help files on looping through subfolders, as as well as the os documentation, but I am still stuck. I am trying to loop over files in subfolders, open each file, extract the first number in the first line, copy the file to a different subfolder(with the same name but in the output directory) and rename the file copy with the number as a suffix.

import os
import re
outputpath = "C:/Users/Heather/Dropbox/T_Files/Raw_FRUS_Data/Wisconsin_Copies_With_PageNumbers"
inputpath = "C:/Users/Heather/Dropbox/T_Files/Raw_FRUS_Data/FRUS_Wisconsin"
suffix=".txt"
for root, dirs, files  in os.walk(inputpath):
    for file in files:
        file_path = os.path.join(root, file)
        foldername=os.path.split(os.path.dirname(file_path))[1]
        filebname=os.path.splitext(file)[0]
        filename=filebname + "_"
        f=open(os.path.join(root,file),'r')
        data=f.readlines()
        if data is None:
            f.close()
        else:
            with open(os.path.join(root,file),'r') as f:
                for line in f:
                    s=re.search(r'\d+',line)
                    if s:
                        pagenum=(s.group())
                        break
        with open(os.path.join(outputpath, foldername,filename+pagenum+suffix), 'w') as f1:
            with open(os.path.join(root,file),'r') as f:
                for line in f:
                    f1.write(line)

I expect the result to be copies of the files in the input directory placed in the corresponding subfolder in the output directory, renamed with a suffix, such as "005_2", where 005 is the original file name, and 2 is the number the python code extracted from it.

The error I get seems to indicates that I am not looping through files correctly. I know the code for extracting the first number and renaming the file works because I tested it on a single file. But using os.walk to loop through multiple subfolders is not working, and I can't figure out what I am doing wrong. Here is the error:

File "<ipython-input-1-614e2851f16a>", line 23, in <module>
    with open(os.path.join(outputpath, foldername,filename+pagenum+suffix), 'w') as f1:
IOError: [Errno 2] No such file or directory: 'C:/Users/Heather/Dropbox/T_Files/Raw_FRUS_Data/Wisconsin_Copies_With_PageNumbers\\FRUS_Wisconsin\\.dropbox_1473986809.txt'

Body:
Well, this isn't eloquent, but it worked

from glob import glob
folderlist=glob("C:\\...FRUS_Wisconsin*\\")
outputpath = "C:\\..\Wisconsin_Copies_With_PageNumbers"
for folder in folderlist:
    foldername = str(folder.split('\\')[7])
    for root, dirs, files in os.walk(folder):
        for file in files:
            filebname=os.path.splitext(file)[0]
            filename=filebname + "_"
            if not filename.startswith('._'):
                with open(os.path.join(root,file),'r') as f:
                    for line in f:
                        s=re.search(r'\d+',line)
                        if s:
                           pagenum=(s.group())
                           break
                     with open(os.path.join(outputpath, foldername,filename+pagenum+suffix), 'w') as f1:
                        with open(os.path.join(root,file),'r') as f:
                            for line in f:
                                f1.write(line)


问:
error C2244 unable to match function definition to an existing declaration in cpp /// operator overloading
I am trying to overload =+ operator. there are two of it. One for the linkedlist+=linkedlist, other for the linkedlist+=templated type. But vs gives me an error.

```<code>template <class T>
const DList<T>& DList<T>::operator += (const DList & rhs)
{
    Node<T> temp=head;
while(temp->next!=NULL)
{
    temp=temp->next;
}

rhs.head->prev=temp;
temp->next=rhs.head;

return *this;
}

template <class T>
 DList<T>& DList<T>::operator += (T n)
 {

    Node<T> * temp= new Node<T>(n, NULL, head);

    head=temp;

return *this;
 }
</code>```

Here the entire header:

```<code>#ifndef _DList_H
#define _DList_H

template <class T>

struct Node
{
T val;
Node<T>* next;
Node<T>* prev;
Node(T el, Node<T>* p=NULL, Node<T>* n=NULL ): val(el), prev(p), next(n)
{};
};
template <class T>

 class DList
 {
 private:

 Node<T>* head;
 int size;

 public:
const DList & DList::operator += (const DList & rhs);

DList();
DList(const DList&);
~DList();
bool isEmpty();
void printList() const;
void addToBeginning(T n);
void deleteList ();

const DList<T> & DList::operator = (const DList & rhs);

const DList<T> & DList::operator += (T);
const DList<T> & DList::operator -= (T);
bool  DList<T>::operator < (const DList & rhs);
bool  DList<T>::operator > (const DList & rhs);
bool  DList<T>::operator == (const DList & rhs);
Node<T> * createClone () const;
};
#include "DList.cpp"
#endif
</code>```

Btw, it's my first question. I hope that asked it clearly and used the format correctly.

The full error message:
Error   1   error C2244: 'DList::+=' : unable to match function definition to an existing declaration

+= operator used like this:

list4 += list1 += list2;

```<code>list1 -= 5;

 list1 -= 6;
</code>```

答:
If you are using templates, you cannot separate function defintion from declaration.

The DList:: prefix may not be in the function declaration within the class body.

You should not inculde cpp files. These files should include header files to make declarations available for the compiler.

Body:
I am trying to overload =+ operator. there are two of it. One for the linkedlist+=linkedlist, other for the linkedlist+=templated type. But vs gives me an error.

template <class T>
const DList<T>& DList<T>::operator += (const DList & rhs)
{
    Node<T> temp=head;
while(temp->next!=NULL)
{
    temp=temp->next;
}

rhs.head->prev=temp;
temp->next=rhs.head;

return *this;
}

template <class T>
 DList<T>& DList<T>::operator += (T n)
 {

    Node<T> * temp= new Node<T>(n, NULL, head);

    head=temp;

return *this;
 }

Here the entire header:

#ifndef _DList_H
#define _DList_H

template <class T>

struct Node
{
T val;
Node<T>* next;
Node<T>* prev;
Node(T el, Node<T>* p=NULL, Node<T>* n=NULL ): val(el), prev(p), next(n)
{};
};
template <class T>

 class DList
 {
 private:

 Node<T>* head;
 int size;

 public:
const DList & DList::operator += (const DList & rhs);

DList();
DList(const DList&);
~DList();
bool isEmpty();
void printList() const;
void addToBeginning(T n);
void deleteList ();

const DList<T> & DList::operator = (const DList & rhs);

const DList<T> & DList::operator += (T);
const DList<T> & DList::operator -= (T);
bool  DList<T>::operator < (const DList & rhs);
bool  DList<T>::operator > (const DList & rhs);
bool  DList<T>::operator == (const DList & rhs);
Node<T> * createClone () const;
};
#include "DList.cpp"
#endif

Btw, it's my first question. I hope that asked it clearly and used the format correctly.

The full error message:
Error   1   error C2244: 'DList::+=' : unable to match function definition to an existing declaration

+= operator used like this:

list4 += list1 += list2;

list1 -= 5;

 list1 -= 6;


问:
Programmatically execute VACUUM command using Sqlite3 and C++?
I am trying to programmatically execute the VACUUM command in C++ using the Sqlite3 library for C++. See reference at C-language Interface Specification for SQLite.

Can someone give a code snippet of how to do this? I tried calling this but it gives an exception:

This code is in my SqliteDb.cpp helper class.

```<code>void SqliteDb::executeSql(const string& sqlStatement) {
  char* errMsg = NULL;
  sqlite3_exec(db, sqlStatement.c_str(), NULL, NULL, &errMsg);
  if (errMsg != NULL) {
    string reason = string("Error in") + sqlStatement + " " + errMsg;
    sqlite3_free(errMsg);
    __throw_sqlitedb(reason);
  }
}
</code>```

In my main class I did:

```<code>try{
    db = new SqliteDb(filepath);
    db->executeSql("VACUUM;");
} catch (std::exception e) {
    printf("EXCEPTION occurred %s", e.what());
}
</code>```

The output is

```<code>EXCEPTION occurred std::exception
</code>```

The SqliteDb.cpp is a tested class and works well for other components that use this class.

答:
```<code>PRAGMA auto_vacuum = FULL;
</code>```

Then you won't have to worry about it.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to programmatically execute the VACUUM command in C++ using the Sqlite3 library for C++. See reference at C-language Interface Specification for SQLite.

Can someone give a code snippet of how to do this? I tried calling this but it gives an exception:

This code is in my SqliteDb.cpp helper class.

void SqliteDb::executeSql(const string& sqlStatement) {
  char* errMsg = NULL;
  sqlite3_exec(db, sqlStatement.c_str(), NULL, NULL, &errMsg);
  if (errMsg != NULL) {
    string reason = string("Error in") + sqlStatement + " " + errMsg;
    sqlite3_free(errMsg);
    __throw_sqlitedb(reason);
  }
}

In my main class I did:

try{
    db = new SqliteDb(filepath);
    db->executeSql("VACUUM;");
} catch (std::exception e) {
    printf("EXCEPTION occurred %s", e.what());
}

The output is

EXCEPTION occurred std::exception

The SqliteDb.cpp is a tested class and works well for other components that use this class.

Body:
PRAGMA auto_vacuum = FULL;

Then you won't have to worry about it.


问:
C# Sybase AseClient Invalid amount of parameters
I'm using prepared statement for the sql below

```<code>SELECT
t.baseSystem 'source',
count(t.filenumber) 'fileCount'
FROM orders t JOIN customer c ON t.customer = c.customerid
WHERE
t.entrydate = @loaddate
AND (t.baseSystem in ('GFQWE','GHOTR','EFXSDE','EBDBDL','AUTO','MDFX')
            OR t.baseSystem LIKE 'STPALLOC_%')
AND t.trdsource in (0,22)
AND t.refType NOT LIKE '%Far%'
AND c.type IN ('BANK','NBNK','BFAC')
AND t.reference NOT IN ('QDisk', 'DSSDOL', 'DEFG', 'FGYT')
GROUP BY t.baseSystem

UNION

SELECT
CASE
            WHEN t.baseSystem = 'GFQWE' THEN 'FGQC'
            WHEN t.baseSystem = 'GHOTR' THEN 'OUY UI'
            ELSE t.baseSystem
END 'source',
count(t.filenumber) 'fileCount'
FROM orders t JOIN customer c ON t.customer = c.customerid
WHERE
t.entrydate = @loaddate
AND t.baseSystem in ('GFQWE','GHOTR')
AND t.broker = 'P'
AND t.trdsource in (0,22)
AND t.refType NOT LIKE '%Far%'
AND c.type IN ('BANK','NBNK','BFAC')
AND t.reference NOT IN ('QDisk', 'DSSDOL', 'DEFG', 'FGYT')
GROUP BY
CASE
                WHEN t.baseSystem = 'GFQWE' THEN 'FGQC'
                WHEN t.baseSystem = 'GHOTR' THEN 'OUY UI'
                ELSE t.baseSystem
END
</code>```

C# code

```<code>DataTable result = new DataTable();
AseConnection aseConnection = GetAseConnection(connection);
try
{
      AseCommand command = new AseCommand(sql, aseConnection);
      command.CommandText = sql;
      AseParameter parameter = new AseParameter("@loaddate", strDate);
      command.Parameters.Add(param);
      command.Prepare();
      using (AseDataAdapter adapter = new AseDataAdapter(command))
      {
          adapter.Fill(result);
      }
 }
 finally
 {
      aseConnection.Close();
  }
  return result;
</code>```

This code works fine on my local, but throws the below error on server. Having a hard time since i cannot reproduce the same error on my local.

Sybase.Data.AseClient.AseException: Invalid amount of parameters.
   at Sybase.Data.AseClient1.AseCommand.CheckResult(Int32 res)
   at Sybase.Data.AseClient1.AseCommand.SetCommandStatement(CommandBehavior commandBehavior)
   at Sybase.Data.AseClient1.AseCommand.Execute(CommandBehavior commandBehavior)
   at Sybase.Data.AseClient1.AseCommand._ExecuteReader(CommandBehavior commandBehavior)
   at Sybase.Data.AseClient1.AseCommand.ExecuteReader(CommandBehavior commandBehavior)
   at Sybase.Data.AseClient.AseCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)

答:
Adding ;NamedParameters=false to the connection string as mentioned in the link below worked for me

Problems with running Sybase SQL Script from C# - too many parameters

Body:
I'm using prepared statement for the sql below

SELECT
t.baseSystem 'source',
count(t.filenumber) 'fileCount'
FROM orders t JOIN customer c ON t.customer = c.customerid
WHERE
t.entrydate = @loaddate
AND (t.baseSystem in ('GFQWE','GHOTR','EFXSDE','EBDBDL','AUTO','MDFX')
            OR t.baseSystem LIKE 'STPALLOC_%')
AND t.trdsource in (0,22)
AND t.refType NOT LIKE '%Far%'
AND c.type IN ('BANK','NBNK','BFAC')
AND t.reference NOT IN ('QDisk', 'DSSDOL', 'DEFG', 'FGYT')
GROUP BY t.baseSystem

UNION

SELECT
CASE
            WHEN t.baseSystem = 'GFQWE' THEN 'FGQC'
            WHEN t.baseSystem = 'GHOTR' THEN 'OUY UI'
            ELSE t.baseSystem
END 'source',
count(t.filenumber) 'fileCount'
FROM orders t JOIN customer c ON t.customer = c.customerid
WHERE
t.entrydate = @loaddate
AND t.baseSystem in ('GFQWE','GHOTR')
AND t.broker = 'P'
AND t.trdsource in (0,22)
AND t.refType NOT LIKE '%Far%'
AND c.type IN ('BANK','NBNK','BFAC')
AND t.reference NOT IN ('QDisk', 'DSSDOL', 'DEFG', 'FGYT')
GROUP BY
CASE
                WHEN t.baseSystem = 'GFQWE' THEN 'FGQC'
                WHEN t.baseSystem = 'GHOTR' THEN 'OUY UI'
                ELSE t.baseSystem
END

C# code

DataTable result = new DataTable();
AseConnection aseConnection = GetAseConnection(connection);
try
{
      AseCommand command = new AseCommand(sql, aseConnection);
      command.CommandText = sql;
      AseParameter parameter = new AseParameter("@loaddate", strDate);
      command.Parameters.Add(param);
      command.Prepare();
      using (AseDataAdapter adapter = new AseDataAdapter(command))
      {
          adapter.Fill(result);
      }
 }
 finally
 {
      aseConnection.Close();
  }
  return result;

This code works fine on my local, but throws the below error on server. Having a hard time since i cannot reproduce the same error on my local.

Sybase.Data.AseClient.AseException: Invalid amount of parameters.
   at Sybase.Data.AseClient1.AseCommand.CheckResult(Int32 res)
   at Sybase.Data.AseClient1.AseCommand.SetCommandStatement(CommandBehavior commandBehavior)
   at Sybase.Data.AseClient1.AseCommand.Execute(CommandBehavior commandBehavior)
   at Sybase.Data.AseClient1.AseCommand._ExecuteReader(CommandBehavior commandBehavior)
   at Sybase.Data.AseClient1.AseCommand.ExecuteReader(CommandBehavior commandBehavior)
   at Sybase.Data.AseClient.AseCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)


问:
Always run a processing thread if a message queue is not empty
Whenever the server receives a message from a client, the message will be put in a queue. Multiple threads can input data in the queue, but only one thread should read/process from it at a time. As long as there are messages in the queue, the processing thread should be alive. How do I make this work?

If I put the processing logic in a synchronized method, and start a new thread calling this method for every request, won't it be a waste of resources having all those threads in memory, waiting their turn?

On the other hand, if I use a single processing thread, with each request trying to start it if it's not already running:

```<code>public void onMessage(String message) {
    addToQueue(message);
    synchronized (lock) {
        if (!processingThread.isAlive())
            processingThread.start();
    }
}

// processing thread
public void process() {
    while (true) {
        String message = queue.poll();
        synchronized (lock) {
            if (message == null)
                return;
        }
        // process message
    }
}
</code>```

How can I make sure I don't run into this scenario:

Processing thread polls the queue for the next element. It gets the shared lock and enters a synchronized block. It checks and sees the element it read from the queue is null, so the queue is empty. The thread releases the lock, but its isAlive flag hasn't been set to false yet.

Client request arrives, adding a message in the queue. The receiving method gets the lock, and enters its synchronized block. The processing thread is still alive, so it doesn't need to be started. The method releases the lock.

The processing thread has now released the lock and dies.

In this case, there will be one unprocessed message in the queue. Can this scenario happen? As the bold sentence suggests, can the lock be released before the thread dies?

答: This is a consumer/producer problem.  There is no need to stop/start the processing thread (consumer).  It can block, waiting for a message in the queue.  The client threads (producers) fill the queue and notify() the consumer thread which unblocks, removes the message and waits again.  Here is an example https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html.

Body:
Whenever the server receives a message from a client, the message will be put in a queue. Multiple threads can input data in the queue, but only one thread should read/process from it at a time. As long as there are messages in the queue, the processing thread should be alive. How do I make this work?

If I put the processing logic in a synchronized method, and start a new thread calling this method for every request, won't it be a waste of resources having all those threads in memory, waiting their turn?

On the other hand, if I use a single processing thread, with each request trying to start it if it's not already running:

public void onMessage(String message) {
    addToQueue(message);
    synchronized (lock) {
        if (!processingThread.isAlive())
            processingThread.start();
    }
}

// processing thread
public void process() {
    while (true) {
        String message = queue.poll();
        synchronized (lock) {
            if (message == null)
                return;
        }
        // process message
    }
}

How can I make sure I don't run into this scenario:

Processing thread polls the queue for the next element. It gets the shared lock and enters a synchronized block. It checks and sees the element it read from the queue is null, so the queue is empty. The thread releases the lock, but its isAlive flag hasn't been set to false yet.

Client request arrives, adding a message in the queue. The receiving method gets the lock, and enters its synchronized block. The processing thread is still alive, so it doesn't need to be started. The method releases the lock.

The processing thread has now released the lock and dies.

In this case, there will be one unprocessed message in the queue. Can this scenario happen? As the bold sentence suggests, can the lock be released before the thread dies?


问:
Insert Multiple Rows If Not Exists
I have two tables. Table A and Table B. Table A has some unique id's already existing. I want to insert a new custom row into Table A where those rows for my condition exist in Table B and not in Table A. How do I insert all rows from Table B that don't exist in Table A? I am looking for MSSQL solution.

I have tried the following two forms but neither seem to work:

Example A:

```<code>INSERT into TableA
(
    Id,
    Selection1,
    Selection2,
    Selection3
)
SELECT
(
    Id,  /* this field comes from TableB */
     0,
     0,
     1
)
from TableB
where NOT EXISTS ( SELECT * FROM TableA
                INNER JOIN TableB
                ON TableA.Id = TableB.ID)
</code>```

Example B

```<code>IF NOT EXISTS ( SELECT * FROM TableA
        INNER JOIN TableB
        ON TableA.Id = TableB.Id)

    INSERT into TableA
    (
        Id,
        Selection1,
        Selection2,
        Selection3
    )
    SELECT
    (
        Id,  /* this field comes from TableB */
         0,
         0,
         1
    )
    from TableB
</code>```

答:
Using EXCEPT could be performance improvement, because MERGE needs data to be sorted.

```<code>INSERT into TableA
(
    Id,
    Selection1,
    Selection2,
    Selection3
)
SELECT Id,0,0,1
from TableB
EXCEPT
SELECT Id,0,0,1
FROM TableA INNER JOIN TableB
                ON TableA.Id = TableB.ID
</code>```

only thing is number and types of columns have to match in both SELECTs

Title: Insert Multiple Rows If Not Exists

Body:
I have two tables. Table A and Table B. Table A has some unique id's already existing. I want to insert a new custom row into Table A where those rows for my condition exist in Table B and not in Table A. How do I insert all rows from Table B that don't exist in Table A? I am looking for MSSQL solution.

I have tried the following two forms but neither seem to work:

Example A:

INSERT into TableA
(
    Id,
    Selection1,
    Selection2,
    Selection3
)
SELECT
(
    Id,  /* this field comes from TableB */
     0,
     0,
     1
)
from TableB
where NOT EXISTS ( SELECT * FROM TableA
                INNER JOIN TableB
                ON TableA.Id = TableB.ID)

Example B

IF NOT EXISTS ( SELECT * FROM TableA
        INNER JOIN TableB
        ON TableA.Id = TableB.Id)

    INSERT into TableA
    (
        Id,
        Selection1,
        Selection2,
        Selection3
    )
    SELECT
    (
        Id,  /* this field comes from TableB */
         0,
         0,
         1
    )
    from TableB

Body:
Using EXCEPT could be performance improvement, because MERGE needs data to be sorted.

INSERT into TableA
(
    Id,
    Selection1,
    Selection2,
    Selection3
)
SELECT Id,0,0,1
from TableB
EXCEPT
SELECT Id,0,0,1
FROM TableA INNER JOIN TableB
                ON TableA.Id = TableB.ID

only thing is number and types of columns have to match in both SELECTs


问:
Display second form if radio button is checked not working
I have this assignment where I am supposed to display a second form if a radio button is checked.

It is called Piano Festival. The form is supposed to have First and Last name, the student ID of the student, and 3 radio buttons with the options "Solo", "Duet" and "Concerto".

If "Duet" is selected, it is supposed to display the same form next to it, but only with first and last name, and the student ID.

This is my html file:

```<code><form id="myForm" action="" onsubmit="validateForm()">
        <fieldset>
            Performance Type:
            <br>
            <input type="radio" name="performanceType" id="solo" value="Solo">Solo<br>
            <input type="radio" name="performanceType" id="duet" onclick="checkType()" value="Duet">Duet<br>
            <input type="radio" name="performanceType" id="concerto" value="Concerto">Concerto<br><br>
            First Name:
            <input type="text" name="firstName"><br><br>
            Last Name:
            <input type="text" name="lastName"><br><br>
            Student ID:
            <input type="text" name="studentID"><br><br>
            <input type="submit" value="Register Student">
            <input type="reset" value="Clear Form">

        </fieldset>
    </form>
    <div id="duetSelected" style="display: none">
        <form id="myForm1" action="" onsubmit="validateForm()">
            <fieldset>
                First Name:
                <input type="text" name="firstName"><br><br>
                Last Name:
                <input type="text" name="lastName"><br><br>
                Student ID:
                <input type="text" name="studentID"><br><br>
                <input type="submit" value="Register Student">
                <input type="reset" value="Clear Form">

            </fieldset>
        </form>
    </div>
</code>```

And this is what I have in my javascript file:

```<code>function validateForm()
{
    var a = document.forms["myForm"]["firstName"].value;
    var b = document.forms["myForm"]["lastName"].value;
    var c = document.forms["myForm"]["studentID"].value;

    if (a == "" || b == "" || c == "")
    {
        alert("First name, last name and Student ID must be filled.");
        return false;
    }
    else
    {
        return true;
    }

    $("input[type='radio'][id='duet']").on("change",function()
    {
        if($(this).is(':checked'))
        {
            $("#duetSelected").show();
        }
        else
        {
           $("#duetSelected").hide();
    }
  });

}
</code>```

Any ideas?

Thanks in advance.

答:
Well, first you have to put out the function for the radio outside the submit function.

I erase the return true because by logic if is not false, is true, and valid the id when change the radio button.

Hope it works for you!

https://codepen.io/mackiechan/pen/dZBzEa

function validateForm()
{
    var a = document.forms["myForm"]["firstName"].value;
    var b = document.forms["myForm"]["lastName"].value;
    var c = document.forms["myForm"]["studentID"].value;

    if (a == "" || b == "" || c == "")
    {
        alert("First name, last name and Student ID must be filled.");
        return false;
    }
}

$("input[type=radio]").on("change",function()
    {
      var thisid = $(this).attr('id');
        if(thisid==='duet')
        {
            $("#duetSelected").show();
        }else{
          $("#duetSelected").hide();
        }
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm" action="" onsubmit="validateForm()">
        <fieldset>
            Performance Type:
            <br>
            <input type="radio" name="performanceType" id="solo" value="Solo">Solo<br>
            <input type="radio" name="performanceType" id="duet"  value="Duet">Duet<br>
            <input type="radio" name="performanceType" id="concerto" value="Concerto">Concerto<br><br>
            First Name:
            <input type="text" name="firstName"><br><br>
            Last Name:
            <input type="text" name="lastName"><br><br>
            Student ID:
            <input type="text" name="studentID"><br><br>
            <input type="submit" value="Register Student">
            <input type="reset" value="Clear Form">

        </fieldset>
    </form>
    <div id="duetSelected" style="display: none">
        <form id="myForm1" action="" onsubmit="validateForm()">
            <fieldset>
                First Name:
                <input type="text" name="firstName"><br><br>
                Last Name:
                <input type="text" name="lastName"><br><br>
                Student ID:
                <input type="text" name="studentID"><br><br>
                <input type="submit" value="Register Student">
                <input type="reset" value="Clear Form">

            </fieldset>
        </form>
    </div></code>```

Body:
I have this assignment where I am supposed to display a second form if a radio button is checked.

It is called Piano Festival. The form is supposed to have First and Last name, the student ID of the student, and 3 radio buttons with the options "Solo", "Duet" and "Concerto".

If "Duet" is selected, it is supposed to display the same form next to it, but only with first and last name, and the student ID.

This is my html file:

<form id="myForm" action="" onsubmit="validateForm()">
        <fieldset>
            Performance Type:

            <input type="radio" name="performanceType" id="solo" value="Solo">Solo

            <input type="radio" name="performanceType" id="duet" onclick="checkType()" value="Duet">Duet

            <input type="radio" name="performanceType" id="concerto" value="Concerto">Concerto

            First Name:
            <input type="text" name="firstName">

            Last Name:
            <input type="text" name="lastName">

            Student ID:
            <input type="text" name="studentID">

            <input type="submit" value="Register Student">
            <input type="reset" value="Clear Form">

        </fieldset>
    </form>

        <form id="myForm1" action="" onsubmit="validateForm()">
            <fieldset>
                First Name:
                <input type="text" name="firstName">

                Last Name:
                <input type="text" name="lastName">

                Student ID:
                <input type="text" name="studentID">

                <input type="submit" value="Register Student">
                <input type="reset" value="Clear Form">

            </fieldset>
        </form>

And this is what I have in my javascript file:

function validateForm()
{
    var a = document.forms["myForm"]["firstName"].value;
    var b = document.forms["myForm"]["lastName"].value;
    var c = document.forms["myForm"]["studentID"].value;

    if (a == "" || b == "" || c == "")
    {
        alert("First name, last name and Student ID must be filled.");
        return false;
    }
    else
    {
        return true;
    }

    $("input[type='radio'][id='duet']").on("change",function()
    {
        if($(this).is(':checked'))
        {
            $("#duetSelected").show();
        }
        else
        {
           $("#duetSelected").hide();
    }
  });

}

Any ideas?

Thanks in advance.

Body:
Well, first you have to put out the function for the radio outside the submit function.

I erase the return true because by logic if is not false, is true, and valid the id when change the radio button.

Hope it works for you!

https://codepen.io/mackiechan/pen/dZBzEa

function validateForm()
{
    var a = document.forms["myForm"]["firstName"].value;
    var b = document.forms["myForm"]["lastName"].value;
    var c = document.forms["myForm"]["studentID"].value;

    if (a == "" || b == "" || c == "")
    {
        alert("First name, last name and Student ID must be filled.");
        return false;
    }
}

$("input[type=radio]").on("change",function()
    {
      var thisid = $(this).attr('id');
        if(thisid==='duet')
        {
            $("#duetSelected").show();
        }else{
          $("#duetSelected").hide();
        }
  });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm" action="" onsubmit="validateForm()">
        <fieldset>
            Performance Type:
            <br>
            <input type="radio" name="performanceType" id="solo" value="Solo">Solo<br>
            <input type="radio" name="performanceType" id="duet"  value="Duet">Duet<br>
            <input type="radio" name="performanceType" id="concerto" value="Concerto">Concerto<br><br>
            First Name:
            <input type="text" name="firstName"><br><br>
            Last Name:
            <input type="text" name="lastName"><br><br>
            Student ID:
            <input type="text" name="studentID"><br><br>
            <input type="submit" value="Register Student"> &nbsp;&nbsp;&nbsp;&nbsp;
            <input type="reset" value="Clear Form">

        </fieldset>
    </form>
    <div id="duetSelected" style="display: none">
        <form id="myForm1" action="" onsubmit="validateForm()">
            <fieldset>
                First Name:
                <input type="text" name="firstName"><br><br>
                Last Name:
                <input type="text" name="lastName"><br><br>
                Student ID:
                <input type="text" name="studentID"><br><br>
                <input type="submit" value="Register Student"> &nbsp;&nbsp;&nbsp;&nbsp;
                <input type="reset" value="Clear Form">

            </fieldset>
        </form>
    </div>


问:
How do I style a WordPress PHP link?
```<code><div class="past-page"><?php previous_posts_link( '« Previous Page' ); ?></div>
</code>```

Hello! I'm having a bit of troubles trying to solve the styling of a pagination button. I tried styling the past-page div, but that made a white box show up when no link was there... which was not the result I wanted.

So, I'm wondering if I can somehow add styling in the php tag here?
The style I want to add is

```<code>font-size: 10pt;
text-transform: uppercase;
font-weight: bold;
background: #fff;
padding: 10px;
</code>```

答:
use :not(:empty) to add style to a div that is 'not empty'; otherwise, when it is blank, it reverts back to the default CSS:

```<code><style>
.past-page:not(:empty) {
 font-size: 10pt;
 text-transform: uppercase;
 font-weight: bold;
 background: #fff;
 padding: 10px;
}
</style>
</code>```

Alternatively, you could apply the style always unless empty then make it invisible:

```<code><style>
.past-page {
 font-size: 10pt;
 text-transform: uppercase;
 font-weight: bold;
 background: #fff;
 padding: 10px;
}

.past-page:empty {
 display: none !important;
}
</style>
</code>```

Title: How do I style a WordPress PHP link?

Body:
<?php previous_posts_link( '« Previous Page' ); ?>

Hello! I'm having a bit of troubles trying to solve the styling of a pagination button. I tried styling the past-page div, but that made a white box show up when no link was there... which was not the result I wanted.

So, I'm wondering if I can somehow add styling in the php tag here?
The style I want to add is

font-size: 10pt;
text-transform: uppercase;
font-weight: bold;
background: #fff;
padding: 10px;

Body:
use :not(:empty) to add style to a div that is 'not empty'; otherwise, when it is blank, it reverts back to the default CSS:

<style>
.past-page:not(:empty) {
 font-size: 10pt;
 text-transform: uppercase;
 font-weight: bold;
 background: #fff;
 padding: 10px;
}
</style>

Alternatively, you could apply the style always unless empty then make it invisible:

<style>
.past-page {
 font-size: 10pt;
 text-transform: uppercase;
 font-weight: bold;
 background: #fff;
 padding: 10px;
}

.past-page:empty {
 display: none !important;
}
</style>


答:
You are trying to add an event handler to the load event of an image element. Do this instead

```<code>  var img = new Image();
  $(img).on("load",function(){
      var sizes = {
       width: this.width,
       height: this.height
       };
      if (sizes.width != 600 || sizes.height != 800)
      {
         alert("Error: Image size should be 600 x 800px");
         return false;

      }
     else
     {
       return true;
     }

    });
   img.src = _URL.createObjectURL(files[0]);
</code>```

Note that you need to place the img.src after the event function if you want to trigger the function when the image is set. Placing it inside the function will cause recursion

Title: how do i wait to get the response from img.onload

Body:
THE CHECKSIZE FUNCTION RETURNS UNDEFINED---
    immediately it hits img.onload it jumps to the end of checksize

function checksize(files)
{
    var img = new Image();
    img.onload = function () {
    var sizes = {
        width: this.width,
        height: this.height
    };
    if (sizes.width != 600 || sizes.height != 800)
    {
        alert("Error: Image size should be 600 x 800px");
        return false;

    }
    else
    {
        return true;
    }
    img.src = _URL.createObjectURL(files[0]);
};

Body:
You are trying to add an event handler to the load event of an image element. Do this instead

  var img = new Image();
  $(img).on("load",function(){
      var sizes = {
       width: this.width,
       height: this.height
       };
      if (sizes.width != 600 || sizes.height != 800)
      {
         alert("Error: Image size should be 600 x 800px");
         return false;

      }
     else
     {
       return true;
     }

    });
   img.src = _URL.createObjectURL(files[0]);

Note that you need to place the img.src after the event function if you want to trigger the function when the image is set. Placing it inside the function will cause recursion