text:
Q: Dynamic memory addressing and deallocation I'm trying to solve a problem for a web tutorial (non-marked) where I'm implementing a dynamic array. However, it fails in two places:

*

*Where I try to delete a dynamic array in function ResizeDynamicArray(...)

*It is outputting incorrect data. I expect to see:
10 20 30 40 50
10 30 40 50
10 30 50

...but I get this instead:
8723216 8716480 701955994 201375930 10
8723216 701955994 201375930 10
8723216 701955994 10

Requirements of the solution are:

*

*Use pointer to pointer instead of reference to pointer (btw I have successfully implemented a reference to pointer solution, but I am trying to figure out the pointer to pointer solution)

*No use of malloc/free

*No use of vectors

*Must use the declarations as shown

Could someone please suggest what I'm doing wrong?
int* CreateDynamicArray(int capacity, int &size);
void DeleteDynamicArray(int* dynamicArray, int &size);
void InsertElement(int* dynamicArray, int element, int &size, int &capacity);
void DeleteElement(int* dynamicArray, int elementIndex, int &size);
void ResizeDynamicArray(int** dynamicArray, int newCapacity);
void PrintArray(int *ptrArray, int capacity);

#include <iostream>

int main()
{
    int size = 0;
    int capacity = 0;

    int* ptrArray = CreateDynamicArray(capacity, size);

    InsertElement(ptrArray, 10, size, capacity);
    InsertElement(ptrArray, 20, size, capacity);
    InsertElement(ptrArray, 30, size, capacity);
    InsertElement(ptrArray, 40, size, capacity);
    InsertElement(ptrArray, 50, size, capacity);
    PrintArray(ptrArray, size);

    DeleteElement(ptrArray, 1, size);
    PrintArray(ptrArray, size);
    DeleteElement(ptrArray, 2, size);
    PrintArray(ptrArray, size);

    DeleteDynamicArray(ptrArray, size);

    ptrArray = nullptr;

    return 0;
}

int* CreateDynamicArray(int capacity, int &size)
{
    size = 0;
    return new int[capacity];
}

void DeleteDynamicArray(int* dynamicArray, int &size)
{
    if (dynamicArray != nullptr) {
        delete[] dynamicArray;
        dynamicArray = nullptr;
    }
    size = 0;
}

void InsertElement(int* dynamicArray, int element, int &size, int &capacity)
{
    if (size > capacity)
        capacity += 2;
    else
        capacity += 1;
    ResizeDynamicArray(&dynamicArray, capacity);
    dynamicArray[size] = element;
    size++;
}

void DeleteElement(int* dynamicArray, int elementIndex, int &size)
{
    for(int i = elementIndex + 1; i < size; i++)
        dynamicArray[i - 1] = dynamicArray[i];
    size--;
}

void ResizeDynamicArray(int** dynamicArray, int newCapacity)
{
    int *newArray = new int[newCapacity];
    for(int i = 0; i < newCapacity; i++) {
        newArray[i] = (*dynamicArray)[i];
    }
//  if (*dynamicArray != nullptr) {
//      delete [] *dynamicArray;
//  }
    *dynamicArray = newArray;
}

void PrintArray(int *dynamicArray, int size)
{
    for (int i = 0; i < size; i++) {
        std::cout << dynamicArray[i] << " ";
    }
    std::cout << std::endl;
}

A: Let's look at the problem in InsertElement. You have:
void InsertElement(int* dynamicArray, int element, int &size, int &capacity)
{
    ...
    ResizeDynamicArray(&dynamicArray, capacity);
    ...
}

In this function, you modify what dynamicArray points locally in the function. That does not change what the pointer points to in the calling function. As a consequence, you have the following problems.

*

*The variable in the calling function does not point to the newly allocated memory you expected it to have.

*The calling function uses memory it doesn't have, causing undefined behavior.

*You have a memory leak. The memory acquired in the function is lost to the program as soon as you return from InsertElement.

The way to fix it would be to pass the pointer by reference.
void InsertElement(int*& dynamicArray, int element, int &size, int &capacity)
{
    ...
    ResizeDynamicArray(&dynamicArray, capacity);
    ...
}

I would recommend changing ResizeDynamicArray to also accept a pointer by reference. Using a int** is C-style, not C++ style. If you did change that, you can use
    ResizeDynamicArray(dynamicArray, capacity);

above.
Here's my suggestion for the function declarations. I take it that you can update the implementations accordingly.
int* CreateDynamicArray(int capacity, int &size);
void DeleteDynamicArray(int*& dynamicArray, int &size);
void InsertElement(int*& dynamicArray, int element, int &size, int &capacity);
void DeleteElement(int* dynamicArray, int elementIndex, int &size);
void ResizeDynamicArray(int*& dynamicArray, int newCapacity);
void PrintArray(int *ptrArray, int capacity);

I noticed that you have a bug in ResizeDynamicArray. You are using:
int *newArray = new int[newCapacity];
for(int i = 0; i < newCapacity; i++) {
    newArray[i] = (*dynamicArray)[i];
}

to copy values from the old array to the new array. However, the old array does not have as many elements as the new array. You end up copying values from memory that you are not supposed to access. It will be necessary to pass the old capacity to the function as an argument so you can copy the old values correctly.

A: I believe I have the solution, thanks to R Sahu.
int* CreateDynamicArray(int capacity, int &size);
void DeleteDynamicArray(int* dynamicArray, int &size);
void InsertElement(int** dynamicArray, int element, int &size, int &capacity);
void DeleteElement(int** dynamicArray, int elementIndex, int &size);
void ResizeDynamicArray(int** dynamicArray, int newCapacity);
void PrintArray(int *ptrArray, int capacity);

#include <iostream>

int main()
{
    int size = 0;
    int capacity = 0;

    int* ptrArray = CreateDynamicArray(capacity, size);

    InsertElement(&ptrArray, 10, size, capacity);
    InsertElement(&ptrArray, 20, size, capacity);
    InsertElement(&ptrArray, 30, size, capacity);
    InsertElement(&ptrArray, 40, size, capacity);
    InsertElement(&ptrArray, 50, size, capacity);
    PrintArray(ptrArray, size);

    DeleteElement(&ptrArray, 1, size);
    PrintArray(ptrArray, size);
    DeleteElement(&ptrArray, 2, size);
    PrintArray(ptrArray, size);

    DeleteDynamicArray(ptrArray, size);

    ptrArray = nullptr;

    return 0;
}

int* CreateDynamicArray(int capacity, int &size)
{
    size = 0;
    return new int[capacity];
}

void DeleteDynamicArray(int* dynamicArray, int &size)
{
    if (dynamicArray != nullptr) {
        delete[] dynamicArray;
        dynamicArray = nullptr;
    }
    size = 0;
}

void InsertElement(int** dynamicArray, int element, int &size, int &capacity)
{
    if (size > capacity)
        capacity += 2;
    else
        capacity += 1;
    ResizeDynamicArray(dynamicArray, capacity);
    (*dynamicArray)[size] = element;
    size++;
}

void DeleteElement(int** dynamicArray, int elementIndex, int &size)
{
    for (int i = elementIndex + 1; i < size; i++)
        (*dynamicArray)[i - 1] = (*dynamicArray)[i];
    size--;
}

void ResizeDynamicArray(int** dynamicArray, int newCapacity)
{
    int *newArray = new int[newCapacity];
    for (int i = 0; i < newCapacity; i++) {
        newArray[i] = (*dynamicArray)[i];
    }
    if (*dynamicArray != nullptr)
        delete[] * dynamicArray;
    *dynamicArray = newArray;
}

void PrintArray(int *dynamicArray, int size)
{
    for (int i = 0; i < size; i++) {
        std::cout << dynamicArray[i] << " ";
    }
    std::cout << std::endl;
}


text:
Q: How can I remove this item from 3 different React states? I'm making a to-do app that allows you to create multiple lists with their own to-do items. On my main app component I have a state for all of the todos, all of the lists, and the current list. On deleting an item I need the item to be removed from all 3 states. I can easily remove it from the array of all to-do items and the current list. The trouble is removing it from the list in the lists array. Here is the component code that relates to this issue:
class TodoApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      todos: [],
      lists: [],
      currentList: ''
    };
    this.deleteItem = this.deleteItem.bind(this);
    //...
  }

  //...

  deleteItem(itemId) {
    this.setState(prevState => ({
      todos: prevState.todos.filter(item => itemId !== item.id),
      lists: prevState.lists.find(list => list.id === this.state.currentList.id).todos.filter(item => itemId !== item.id),
      currentList: prevState.currentList.todos.filter(item => itemId !== item.id)
    }));
  }

  render() {
    //...
  }
}

Currently, trying to delete an item removes all lists from the lists array.
Here is a screenshot of the React dev tool to give you an idea of what each state looks like...

Please let me know if I left out any critical information.

A: I believe you need to use .map on the lists substate:
lists: prevState.lists.map(list => ({
  ...list, // or "id: list.id, text: list.text," if you are not ok with spread operator
  todos: list.todos.filter(item => itemId !== item.id)
}))

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android app crashes on bank authentication but works perfectly on iOS Describe the bug
When I try to do handle next action on android, after tapping "Complete Authentication", app crashes. It's working perfectly for iOS.
Smartphone / tablet

*

*Device: Pixel 5, Pixel 5a

*OS: Android 12, Android 13 respectively

*Flutter stripe package version: 7.0.0

*Flutter version 3.3.6

Logs:
W/m.flutter.app(24941): Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (unsupported, reflection, allowed)
D/EGL_emulation(24941): app_time_stats: avg=4.56ms min=2.54ms max=32.65ms count=54
I/WebViewFactory(24941): Loading com.google.android.webview version 91.0.4472.114 (code 447211484)
W/m.flutter.app(24941): Accessing hidden method Landroid/os/Trace;->isTagEnabled(J)Z (unsupported, reflection, allowed)
W/m.flutter.app(24941): Accessing hidden method Landroid/os/Trace;->traceBegin(JLjava/lang/String;)V (unsupported, reflection, allowed)
W/m.flutter.app(24941): Accessing hidden method Landroid/os/Trace;->traceEnd(J)V (unsupported, reflection, allowed)
W/m.flutter.app(24941): Accessing hidden method Landroid/os/Trace;->asyncTraceBegin(JLjava/lang/String;I)V (unsupported, reflection, allowed)
W/m.flutter.app(24941): Accessing hidden method Landroid/os/Trace;->asyncTraceEnd(JLjava/lang/String;I)V (unsupported, reflection, allowed)
I/cr_VariationsUtils(24941): Failed reading seed file "/data/user/0/com.flutter.app/app_webview/variations_seed_new"
I/cr_VariationsUtils(24941): Failed reading seed file "/data/user/0/com.flutter.app/app_webview/variations_seed"
I/cr_LibraryLoader(24941): Loaded native library version number "91.0.4472.114"
I/cr_CachingUmaRecorder(24941): Flushed 6 samples from 6 histograms.
D/CompatibilityChangeReporter(24941): Compat change id reported: 171228096; UID 10147; state: ENABLED
W/m.flutter.app(24941): Accessing hidden method Landroid/media/AudioManager;->getOutputLatency(I)I (unsupported, reflection, allowed)
D/HostConnection(24941): createUnique: call
D/HostConnection(24941): HostConnection::get() New Host Connection established 0xb400007a9fc68a50, tid 25118
D/HostConnection(24941): HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_vulkan_queue_submit_with_commands ANDROID_EMU_sync_buffer_data ANDROID_EMU_read_color_buffer_dma GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_3_0
D/EGL_emulation(24941): eglCreateContext: 0xb400007a9fc69e90: maj 3 min 0 rcv 3
D/EGL_emulation(24941): eglMakeCurrent: 0xb400007a9fc69e90: ver 3 0 (tinfo 0x7cb9f5d280) (first time)
W/cr_media(24941): Requires BLUETOOTH permission
D/EGL_emulation(24941): eglCreateContext: 0xb400007a9fc69e90: maj 3 min 0 rcv 3
I/m.flutter.app(24941): Background young concurrent copying GC freed 87362(5543KB) AllocSpace objects, 7(268KB) LOS objects, 38% free, 8123KB/12MB, paused 2.388ms,24us total 239.450ms
D/EGL_emulation(24941): app_time_stats: avg=9.59ms min=3.06ms max=72.46ms count=51
D/EGL_emulation(24941): eglCreateContext: 0xb400007a9fc69410: maj 3 min 0 rcv 3
D/EGL_emulation(24941): app_time_stats: avg=7.94ms min=2.42ms max=102.91ms count=51
I/chromium(24941): [INFO:CONSOLE(273)] "Refused to load the stylesheet 'https://fast.fonts.net/t/1.css?apiType=css&projectid=4414faae-0f1e-48be-9319-851fc710f613' because it violates the following Content Security Policy directive: "style-src 'unsafe-inline' 'self' https://b.stripecdn.com https://files.stripe.com https://cloud.typography.com/711858/764882/css/fonts.css". Note that 'style-src-elem' was not explicitly set, so 'style-src' is used as a fallback.
I/chromium(24941): ", source: https://stripe.com/sources/test_source_3ds?livemode=false&type=three_d_secure&pass_through=&return_url=https%3A%2F%2Fhooks.stripe.com%2Fthree_d_secure%2Fredirect_complete%2Facct_1LZgSeFacQ1hP4w9%2Ftdsrc_1MA9aOFacQ1hP4w9e1eeTtey&source_slug=CBsaFwoVYWNjdF8xTFpnU2VGYWNRMWhQNHc5KIj3oZwGMgZp0Na4AfU6LdjiM6IoF-ZBmZ0j1OXrTrb6CHAUzdJrrLu_R3ZPY7BhjL70yed34h6cFRQl1w&amount=899&currency=eur&usage=single_use (273)
D/EGL_emulation(24941): app_time_stats: avg=47.16ms min=2.32ms max=2027.11ms count=46
D/EGL_emulation(24941): app_time_stats: avg=618.62ms min=104.85ms max=1132.39ms count=2
D/EGL_emulation(24941): app_time_stats: avg=4.33ms min=3.77ms max=9.48ms count=57
D/EGL_emulation(24941): app_time_stats: avg=54.08ms min=3.73ms max=1570.99ms count=32
D/EGL_emulation(24941): app_time_stats: avg=37.96ms min=4.36ms max=596.02ms count=21
W/cr_AwContents(24941): Application attempted to call on a destroyed WebView
W/cr_AwContents(24941): java.lang.Throwable
W/cr_AwContents(24941):     at org.chromium.android_webview.AwContents.r(chromium-TrichromeWebViewGoogle6432.apk-stable-447211484:2)
W/cr_AwContents(24941):     at Sa.loadingStateChanged(chromium-TrichromeWebViewGoogle6432.apk-stable-447211484:2)
W/cr_AwContents(24941):     at android.os.MessageQueue.nativePollOnce(Native Method)
W/cr_AwContents(24941):     at android.os.MessageQueue.next(MessageQueue.java:335)
W/cr_AwContents(24941):     at android.os.Looper.loopOnce(Looper.java:161)
W/cr_AwContents(24941):     at android.os.Looper.loop(Looper.java:288)
W/cr_AwContents(24941):     at android.app.ActivityThread.main(ActivityThread.java:7839)
W/cr_AwContents(24941):     at java.lang.reflect.Method.invoke(Native Method)
W/cr_AwContents(24941):     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
W/cr_AwContents(24941):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
E/AndroidRuntime(24941): FATAL EXCEPTION: DefaultDispatcher-worker-2
E/AndroidRuntime(24941): Process: com.flutter.app, PID: 24941
E/AndroidRuntime(24941): java.lang.NoSuchFieldError: No static field UpiAwaitNotification of type Lcom/stripe/android/model/StripeIntent$NextActionType; in class Lcom/stripe/android/model/StripeIntent$NextActionType; or its superclasses (declaration of 'com.stripe.android.model.StripeIntent$NextActionType' appears in /data/app/~~GkKIlIbnVXuMUbLPLntfcw==/com.flutter.app-jrAPKxRXCpeFvIoJmZqhgg==/base.apk!classes8.dex)
E/AndroidRuntime(24941):    at com.reactnativestripesdk.MappersKt$WhenMappings.<clinit>(Unknown Source:679)
E/AndroidRuntime(24941):    at com.reactnativestripesdk.MappersKt.mapIntentStatus(Mappers.kt:34)
E/AndroidRuntime(24941):    at com.reactnativestripesdk.MappersKt.mapFromPaymentIntentResult(Mappers.kt:407)
E/AndroidRuntime(24941):    at com.reactnativestripesdk.PaymentLauncherFragment$retrievePaymentIntent$1.onSuccess(PaymentLauncherFragment.kt:223)
E/AndroidRuntime(24941):    at com.reactnativestripesdk.PaymentLauncherFragment$retrievePaymentIntent$1.onSuccess(PaymentLauncherFragment.kt:211)
E/AndroidRuntime(24941):    at com.stripe.android.Stripe$dispatchResult$2.invokeSuspend(Stripe.kt:1801)
E/AndroidRuntime(24941):    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
E/AndroidRuntime(24941):    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
E/AndroidRuntime(24941):    at android.os.Handler.handleCallback(Handler.java:938)
E/AndroidRuntime(24941):    at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(24941):    at android.os.Looper.loopOnce(Looper.java:201)
E/AndroidRuntime(24941):    at android.os.Looper.loop(Looper.java:288)
E/AndroidRuntime(24941):    at android.app.ActivityThread.main(ActivityThread.java:7839)
E/AndroidRuntime(24941):    at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(24941):    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
E/AndroidRuntime(24941):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
E/AndroidRuntime(24941):    Suppressed: kotlinx.coroutines.DiagnosticCoroutineContextException: [StandaloneCoroutine{Cancelling}@2570279, Dispatchers.IO]
I/Process (24941): Sending signal. PID: 24941 SIG: 9
Lost connection to device.

To Reproduce
Steps to reproduce the behavior:

*

*Entering number 4000002760003184 into the cardfield.

*Tapping the confirm button.

*Tapping complete authentication button

Code used after retrieving client secret:
final paymentIntent =
            await Stripe.instance.handleNextAction(clientSecret);
        if (paymentIntent.status == PaymentIntentsStatus.RequiresConfirmation) {
          Map<String, dynamic> results = await _callPayEndpointIntentId(
            paymentIntentId: paymentIntent.id,
          );
        }

Expected behavior
User authenticates and the payment is accepted


text:
Q: Deploy both back-end and front-end React App Suppose I have written a simple registration form app that stores user information on backend database. My frontend is hosted on localhost:3000, and my server is on localhost:4000. It works perfectly. I initialized a boilerplate with create-react-app. My structure is the following:
project/
    |
    |-- client/
    |   | ...
    |   | package.json
    |
    |-- server/
    |   | ...
    |   | package.json

The thing is that I want to set it up for everyone else on the Internet, and show my progress to a friend. Can I use any free hosting to achieve that, i.e. Github Pages or Heroku? Or do they only support front-end apps?
What I want to have running is when someone fills forms and presses submit my database document would receive new entries. And I could monitor it just like I monitor my database on localhost:27017.
I am not at all familiar with deployment. What is the approach to set everything right and sound? Do I need to configure everything from scratch (i.e. tinkering with Babel and Webpack in the beginning) in order to have a fully operational backend and frontend website?
Thank you.


text:
Q: Execute Oracle stored procedure in operation manager configuration I have a stored procedure with 3 parameters. I want to execute this from configuration in operation manager. I used like this :
begin
saman_test.CONVERTHISTORY('$Config/JobType$','$Config/HostFQDN$','$Config/Environment$'); end;

but it does not work without any error.
And I used this code:
exec
saman_test.CONVERTHISTORY('$Config/JobType$','$Config/HostFQDN$','$Config/Environment$')

but I get this error :

ORA-00900: invalid SQL statement

How do I execute my procedure?

A: I find the keyword for execute my procedure.
call
saman_test.CONVERTHISTORY('$Config/JobType$','$Config/HostFQDN$','$Config/Environment$')


text:
Q: Consuming MapServer service using ArcGIS API for Silverlight? Is it possible to use a service published from MapServer using ArcGIS API for Silverlight?
For example:
<esri:FeatureLayer ID="Schools Without Attendance Areas"
                               MouseEnter="FeatureLayer_MouseEnter"
                               MouseLeave="FeatureLayer_MouseLeave"
                               Visible="False"
                               Url="http://webaddress"
                               OutFields="SCHNAME, ADDRESS, PHONE, URL"/>

A: Expose your data using a WMS service from Mapserver. You can then consume it as a WMSlayer in the silverlight application.


text:
Q: Cannot access nfs share On my Debian 8.4 system, I would like to run a postgres database. The data should reside on an NFS mounted folder.
# cat /etc/fstab
xxx.xxx.xxx.xxx:/volume1/srvPostgres on /var/lib/postgresql type nfs (rw,relatime,vers=3,rsize=131072,wsize=131072,namlen=255,hard,proto=tcp,timeo=600,retrans=2,sec=sys,mountaddr=xxx.xxx.xxx.xxx,mountvers=3,mountport=892,mountproto=udp,local_lock=none,addr=xxx.xxx.xxx.xxx)

I installed postgres using apt-get, therefore it creates a user. The destination folder has the correct ownership:
# ls -la /var/lib/postgresql/
total 12
drwxrwxrwx  3 postgres postgres 4096 May  2 12:12 .
drwxr-xr-x 44 root     root     4096 May  2 10:14 ..
drwxrwxrwx  3 postgres postgres 4096 May  2 12:12 9.4

Somehow, postgres is not allowed to write into the folder:
# su postgres
bash: /var/lib/postgresql/.bashrc: Permission denied

postgres$ touch /var/lib/postgresql/test
touch: cannot touch '/var/lib/postgresql/test': Permission denied

What can I do to troubleshoot this issue?
And what is the correct way (if even supported) to have postgres' data on an NFS share?


text:
Q: Parameter mismatch in DLL procedure using delphi I am working with Delphi 2007 and with DLLs and I have programmed a procedure that uses as parameter an integer and a String. I load the dll dynamically in a program in order to test it and printing the parameters on screen as the first instruction of the procedure. The passed values are 0 for the integer and "" for the string but when printing them they become something like 14532 and a trash string. I am aware that I have to use a concrete string type for dll calling and I can fix it but the case of the integer seems pretty mysterious for me. Any idea?
I do not have access to the code right now but I'll try to reproduce it:
My procedure is something like
procedure proc(Code: integer; cod: String);stdcall;
begin;
     showmessage(inttostr(code)+ " "+cod);
end;

And the other side is:
type
call: TCall(Code: integer; cod:String)
handler: THandler
end
....
....
procedure onClickEvent(...)
begin;
handler := loadlibrary(.../library.dll);
if handler <> 0 then
begin
    @call := getprocaddress(handler, "proc");
    if call <> nil then
         call(0,"");
end
freelibrary(handler)
end

A:
Note: the code you posted cannot be your real code. It would not
  compile. Please only post code copied and pasted directly from your
  editor. Do not retype it or make it up.

As the comments say, don't use string. This is a Delphi-specific type, and it is not even always the same. Other languages will not know how to use it. Use PWideChar or PAnsiChar, depending on what your needs are.
Also, your declaration of Call is wrong (you must declare it as stdcall, since then, parameters will be passed on the stack. If you forget that, parameters will be passed in registers, but the DLL expects them on the stack):
type
  TCall = procedure(Code: Integer; Cod: PWideChar) stdcall;

var
  Call: TCall;

Implementation in the DLL:
procedure proc(Code: integer; Cod: PWideChar); stdcall;
begin
  ShowMessage(IntToStr(Code)+ " " + Cod);
end;

Now you can call it like:
MyString := 'Hello';
Call(0, PWideChar(MyString));

A: Use PChar inside dll, not string.
More information in http://delphi.wikia.com/wiki/Creating_DLLs


text:
Q: What is the purpose of application-name and keywords in meta tag? What is the purpose or need of the below tags?
<meta name="application-name" content="StackOverflow">
<meta name="keywords" content="questions, answers"> <!-- SEO tells keywords aren't given importance these days -->

A: From W3Schools.com:

*

*application-name: Specifies the name of the Web application that the page represents

*keywords: Specifies a comma-separated list of keywords - relevant to the page (Informs search engines what the page is about).

A: According to HTML5 LC, a meta tag with name=application-name shall have value (in the content attribute) that is "short free-form string giving the name of the Web application that the page represents"; if the page is not an application, such a tag must not be used. Browsers "may use the application name in UI in preference to the page's title, since the title might include status messages and the like relevant to the status of the page at a particular moment in time instead of just being the name of the application."
A meta tag with name=keywords specifies "a set of comma-separated tokens, each of which is a keyword relevant to the page". It is normally ignored by search engines these days (and has never had an impact on browsers, as you can read between lines from the following note in HTML5 LC: "Many search engines do not consider such keywords, because this feature has historically been used unreliably and even misleadingly as a way to spam search engine results in a way that is not helpful for users."

A: The text in these tags is not displayed, but parsable and tells the browsers (or other web services) specific information about the page. Simply, it "explains" the page so a browser can understand it.


text:
Q: JPQL Inserting new entity violates foreign key constraint UPDATE: Changed code to be coherent to db model and changed details of the model itself. Also added code of the section that causes the error.
I am trying to implement a small database consulting system in Hibernate with PostgreSQL and having issues with one specific pair of tables. As you can see, it's a system for car rental services, and the tables store drivers and rentals. A driver is supposed to be able to have multiple rentals (but not the other way around).
Problem Tables
CREATE TABLE Driver(
cod_driver SERIAL PRIMARY KEY,
cod_client INTEGER,
num_license BIGINT UNIQUE,
expiration_license DATE,
ident_driver BIGINT,

FOREIGN KEY (cod_client)
    REFERENCES Client(cod_client)
    ON UPDATE CASCADE
    ON DELETE CASCADE
);

CREATE TABLE Rental(
cod_rental SERIAL PRIMARY KEY,
cod_plate VARCHAR(10),
cod_dest VARCHAR(10),
cod_driver INTEGER,
date_delivery DATE,

FOREIGN KEY (cod_plate)
    REFERENCES Vehicle(cod_plate)
    ON UPDATE CASCADE
    ON DELETE NO ACTION,

FOREIGN KEY (cod_dest)
    REFERENCES Location(cod_location)
    ON UPDATE CASCADE
    ON DELETE NO ACTION,

FOREIGN KEY (cod_driver)
    REFERENCES Driver(cod_driver)
    ON UPDATE CASCADE
    ON DELETE CASCADE
);

I did my implementation using Hibernate as follows (short of getters/setters for brevity):
Driver
@Entity
public class Driver {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer cod_driver;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "cod_client")
private Client client;

private Long num_license;
private Long ident_driver;
private LocalDate expiration_license;
}

Rental
@Entity
public class Rental {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer cod_rental;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "cod_plate")
private Vehicle vehicle;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "cod_dest")
private Location location_dest;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "cod_driver")
private Driver driver;

private LocalDate date_delivery;

Context of PSQLException
Persist function call in Main.java (clientGet is obtained through successfull queries, and inserts is just a class for queries):
            Driver d = new Driver(clientGet, 3294324792L, 321312931L, LocalDate.of(2030, 10, 01));

    inserts.insertEntity(d);

insertEntity function:
   public void insertEntity(Object o) // Basic insertion of any persistent object
{
    em.getTransaction().begin();
    em.persist(o);
    em.getTransaction().commit();
}

Error
The error I get is this:
Caused by: org.postgresql.util.PSQLException:
ERROR: insert or update on table "driver" violates foreign key
constraint "fkdfq0qhvpkw1dqguk6dv1dsj0t"
Detail: Key (cod_driver)=(3) is not present in table "rental".
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2497)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2233)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:310)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:446)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:370)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:149)
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:124)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:175)

What I've Considered
From my understanding, the relationship didn't need to be bidirectional (though I did try to use mappedBy), given that I don't store rentals in driver table.
I just don't understand what constraint could possibly be violated by this. It's as if it expects the value of cod_driver to be already in the rentals table, but a rental entity depends on the pre-existence of the driver existence. SQL for the database doesn't seem to have any constraint like that.
Can someone help me understand what I'm doing wrong? I tried all things I found, but nothing shed any light on this.

A: use many to many relationship between rental and driver.the same problem i faced once in my PurchaseOrder and PaymentMethods relationship.
@ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE })
    @JoinTable(name = "rental_driver", joinColumns = @JoinColumn(name = "rental_id"), inverseJoinColumns = @JoinColumn(name = "driver_id"))
    private List driver = new List();


text:
Q: Python Plot yyplot scientific notation not working I have the code running properly, producing a plot but I don't see the scientific notation. Don't know why?
code:
fig,ax1 =  plt.subplots()
ax1.plot(x,y,'-',color=yclr)
ax1.ticklabel_format(style='sci', axis='y')
ax2 = ax1.twinx()
ax2.plot(x,yy,'-',color=yyclr)
ax2.ticklabel_format(style='sci', axis='y')
plt.show()

Plot:

Update:
Based on the accepted answer, I just included scilimits=(0,0) and it worked. But scientific limit font size is higher than rest, which were set to 12.

A: Passing scilimits=(0, 0) to ticklabel_format should trigger it.
fig,ax1 =  plt.subplots()
ax1.plot(x,y,'-',color=yclr)
ax1.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
ax2 = ax1.twinx()
ax2.plot(x,yy,'-',color=yyclr)
ax2.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
plt.show()


text:
Q: Incomplete Astable 555 Circuit Triggering I am using a DSO138 oscilloscope for learning electronics. It is not much, but it is very helpful for me at present.
I was setting up a 555 astable circuit. I noticed that it was triggering even though the circuit was not complete. I have included a picture of the circuit as well as the oscilloscope trace. The oscilloscope ground is connected to ground, and the oscilloscope positive is connected to pin 3 of the 555 (output).

The funny thing is that it does not trigger if my fingers are far from the white wire (which is connected to pin 2 of the 555, but nowhere else), but if they are close, I get the trace I included. If my fingers get really close to the white wire, the duty cycle goes to near 50%.
I am not sure what is going on. Can anyone help explain this?
I have also included a trace for when the oscilloscope ground is connected but the oscilloscope positive lead is not:

I assume this is noise in the power supply. I also assume it is related to the issue described above.
Any help would be much appreciated. Thanks in advance.
Here is a schematic:

A: From your oscilloscope, the frequency of the output seems to be around 50Hz (or could be 60Hz if you're in the US or other countries - it's not that easy to see the exact period). When you put your hand near to the white wire, you could be coupling mains electromagnetic radiation into the circuit. The 555 timer can be used as a schmitt trigger in certain conditions - generally with the trigger (pin 2) and threshold (pin 6) pins together.
If the threshold pin isn't actually connected to anything, it might be capacitively coupling to the trigger pin.
In a sentence, your body acts as an antenna for mains, bringing your body near to a circuit with floating inputs will couple some noise into the circuit, potentially producing an effect like this.


text:
Q: C++ in Qt array not allowing values to be passed in or operated on This class will compile fine and run in visual studios, and it will compile in Qt, but when the array is actually used in the == operator in createItem() it is errored out. It says segmentation fault when running. I have tried setting values into the array manually and it doesnt work either. Does Qt not accept C++ arrays, because this class works fine in visual studios compiling and running.
Also I'm a beginner who is just going with what works, this code is probably neither efficient nor memory saving or clean it just does what I want it to for now. But any improvements you may have are welcome.
#include "inventory.h"
#include <string>
#include <iostream>

inventory::inventory()
{
}

int inv[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
std::string itemName[1000] = {};

void inventory::setItem(int x) {
if (checkItem(x) == true) {
    for (int f = 0; f < 10 && f >= 0; ++f) {
        if (inv[f] == 0) {
            inv[f] = x;
            std::cout << "You have placed " << getItemName(x) << " in  your inventory." << std::endl;
            break;
        }
        else if (f == 9 && inv[f] != 0) {
            std::cout << "You have no more inventory space." << std::endl;
            break;
        }
    }
}
else {
    std::cout << "Item doesn't exist." << std::endl;
}
}

std::string inventory::getItemName(int x) {
std::string g = itemName[x];
return g;
}

void inventory::createItem(std::string y) {
bool exist = false;
for (int i = 0; i <= 1000; i++) {
    if (itemName[i] == y) {
        exist = true;
        break;
    }
}
for (int x = 1; x <= 1000; x++) {
    if (itemName[x] == "") {
        if (exist == false) {
            itemName[x] = y;
            break;
        }
        else if (exist == true) {
            std::cout << "ERROR: Item already exists" << std::endl;
            break;
        }
    }
}
}

int inventory::getItemID(std::string y) {
for (int i = 0; i <= 1000; ++i) {
    if (itemName[i] == y) {
        return i;
    }
    else if (i == 1000 && itemName[i] != y) {
        std::cout << "ERROR: Item not found" << std::endl;
        return 1001;
    }
}
}

bool inventory::checkItem(int x) {
if (itemName[x] != "") {
    return true;
}
else {
    return false;
}
}

int inventory::checkInv(int x) {
for (int i = 0; i < 10; ++i) {
    if (inv[i] == x) {
        std::cout << "Item is in your inventory." << std::endl;
        return true;
        break;
    }
    else if (inv[i] == 9 && inv[9] != x) {
        std::cout << "You don't have the required item in your inventory." << std::endl;
        return false;
        break;
    }
}
}

A: Your problem has absolutely nothing to do with Qt being wrong and Visual Studio being correct.
for (int i = 0; i <= 1000; i++) {

Arrays are indexed from 0 to n-1, where n is the number of elements.  Therefore the valid indices of the itemName array is 0 to 999.
Look at your loops -- you are accessing itemName[i].  What happens when i is 1000?  You are now accessing itemName[1000], which is out of bounds.
The solution to this loop (and others) is this:
for (int i = 0; i < 1000; i++) {

You also make the same error in non-looping code, like this:
else if (i == 1000 && itemName[i] != y)

Again, you're accessing itemName[1000], which is out of bounds.
Also, when you make mistakes like this, the program will exhibit undefined behavior.  This means the program may run, may crash, may run today and crash tomorrow, may run for years and all of a sudden crash one day.
So saying that it runs ok with one compiler and not another means that you need to fix your program, and not be fooled into thinking there is something wrong with the compiler that built the "crashing" version of the program.


text:
Q: Getting Radio buttons Selection I have made a program where the user can select a destination by using the radio buttons. My problem is even if the user selects "1" as the destination the program identifies it as "2".
Here is what i have done :
public partial class Airplane_Simulation : Form
{
    private String status="";

    public Airplane_Simulation()
    {
        InitializeComponent();
        CheckedChanged();

        rbOne.CheckedChanged += (s,e) => { CheckedChanged(); };
        rbTwo.CheckedChanged += (s, e) => { CheckedChanged(); };

        //more codes here
    }

    public void CheckedChanged()
    {
        status = rbOne.Checked ? rbOne.Text : rbTwo.Text;
    }
}

What seems to be the problem here ? i have used the if condition to check which one is checked but still i only get the option as "2".
Thank you for your time.

A: This may help you If you want to change the status everytime when a checkbox is clicked.
 private void Form1_Load(object sender, EventArgs e)
    {
        rbOne.Click += (s, o) => { status = rbOne.Text; };
        rbTwo.Click += (s, o) => { status = rbTwo.Text; };
    }

A: First the single equal sign is an assignment not a check for equality.
You should use two(2) equal signs.
Then I would use the rbOne.IsChecked property to see if the control is checked or not.
The rbOne.Checked is an event not a property.
Edit:
the above could be used in WPF. Here is what I would od in Windows Forms:
    public Form1()
    {
        InitializeComponent();

        rbOne.Click += new EventHandler(radioButton_Click);
        rbTwo.Click += new EventHandler(radioButton_Click);
    }

    public void radioButton_Click(object sender, EventArgs e)
    {
        status = rbOne.Checked ? rbOne.Text : rbTwo.Text;

}

I would not use the CheckedChanged event because it will be called twice when you select the other radio button.


text:
Q: How is padding calculated when using percentage (%)? Why does the padding in this example not equal 300px?

#Test{
  width:600px;
  padding-right:50%;
  box-sizing:border-box;
  background:#ddd;
}

TEXT ETISI DHOASIHD I SAIDUHSILAUDH LISH ADBHSJADB JHSA DKH ASKDH KSAH DKLJS ADLK ASJKLD KLASH DLSJAH KLS ADKL S JS KSH KD KSJ HDKJSH DKH SDKH SKDH KSJH DKJSH DKJ HTEXT ETISI DHOASIHD I SAIDUHSILAUDH LISH ADBHSJADB JHSA DKH ASKDH KSAH DKLJS ADLK ASJKLD KLASH DLSJAH KLS ADKL S JS KSH KD KSJ HDKJSH DKH SDKH SKDH KSJH DKJSH DKJ HTEXT ETISI DHOASIHD I SAIDUHSILAUDH LISH ADBHSJADB JHSA DKH ASKDH KSAH DKLJS ADLK ASJKLD KLASH DLSJAH KLS ADKL S JS KSH KD KSJ HDKJSH DKH SDKH SKDH KSJH DKJSH DKJ HTEXT ETISI DHOASIHD I SAIDUHSILAUDH LISH ADBHSJADB JHSA DKH ASKDH KSAH DKLJS ADLK ASJKLD KLASH DLSJAH KLS ADKL S JS KSH KD KSJ HDKJSH DKH SDKH SKDH KSJH DKJSH DKJ H

*

*Where is the browser deriving it's calculation, 50% of what?

*In the example below the padding actually becomes smaller as the container of #Test becomes larger.

*I actually want the width of #Test to be dynamic however I've fixed it for the purpose of this example.

*And  how do I get 50% padding of #Test?
Notes: I am not just looking for a solution but an understanding of the way padding is working here.

A:
TL;DR
The padding is calculated according to the parent's width

First, you should note that:

Percentage:
  The percentage is calculated with respect to the width of the generated box's containing block [...] (source: w3c, emphasis mine)

This means the padding is calculated according to the parent element width (it's worth to note that in non flexbox layouts, padding top and bottom are also relative to the width of the containing block).
With box-sizing: border-box
When you change the default box-model to border-box, the padding (and border) is included in the width of the element like in your example. So with
width:600px;
padding-right:50%;
box-sizing:border-box;

The right padding must be 50% of parent's width but the overall width of element is 600px wide. The only moment the padding right is 50% of element's width is when parent width = element width (Note that this can't happen in your example because the parent is body and body has a default margin).
Workaround:
If you want the padding to be 50% of the element's width, in this box model you can:

*

*set a fixed padding: width:600px; padding-right: 300px;

*give the element a fluid width : width:50%; padding-right:25%;

Without box-sizing: border-box
In the default box-model, the padding isn't included in the width of the element so element width = 600px + 50% of parent's width as you can see in the following example:

#Test{
  width:600px;
  padding-right:50%;
  background:#ddd;
}

TEXT ETISI DHOASIHD I SAIDUHSILAUDH LISH ADBHSJADB JHSA DKH ASKDH KSAH DKLJS ADLK ASJKLD KLASH DLSJAH KLS ADKL S JS KSH KD KSJ HDKJSH DKH SDKH SKDH KSJH DKJSH DKJ HTEXT ETISI DHOASIHD I SAIDUHSILAUDH LISH ADBHSJADB JHSA DKH ASKDH KSAH DKLJS ADLK ASJKLD KLASH DLSJAH KLS ADKL S JS KSH KD KSJ HDKJSH DKH SDKH SKDH KSJH DKJSH DKJ HTEXT ETISI DHOASIHD I SAIDUHSILAUDH LISH ADBHSJADB JHSA DKH ASKDH KSAH DKLJS ADLK ASJKLD KLASH DLSJAH KLS ADKL S JS KSH KD KSJ HDKJSH DKH SDKH SKDH KSJH DKJSH DKJ HTEXT ETISI DHOASIHD I SAIDUHSILAUDH LISH ADBHSJADB JHSA DKH ASKDH KSAH DKLJS ADLK ASJKLD KLASH DLSJAH KLS ADKL S JS KSH KD KSJ HDKJSH DKH SDKH SKDH KSJH DKJSH DKJ H

Workaround:
If you want the padding to be 50% of the element's width, in this box model you can:

*

*set a fixed padding: width:300px; padding-right: 300px;

*give the element a fluid width : width:25%; padding-right:25%;

References:

*

*The box model MDN, W3C

*The padding property : MDN, W3C

*The box-sizing property : MDN W3C

A: It's in relation to the parent element's width, unless the parent's width depends on this one.
From W3C's CSS 2.1 Specification:

The percentage is calculated with respect to the width of the generated box's containing block, even for 'padding-top' and 'padding-bottom'. If the containing block's width depends on this element, then the resulting layout is undefined in CSS 2.1.


text:
Q: ASP.NET MVC 3 user authorization issue in session_start() function My application uses Identity claim authentication (Active directory user account) to let user access the application pages.
I am trying to change the routing information in the session_start() function, so that if a logged in user is in a non-admin role then i can redirect him to an "Access Denied" page.
I have tried to change the routing info in this function. But i cannot able to do that.
Any suggestions? or what i am doing wrong in this?
Thanks,
Balan

A: Rather than doing authentication this way, I would suggest you to follow the simple way of doing the authentication per controller basis. Like following
[Authorize(Roles = "Administrator")]
public class StoreManagerController : Controller


text:
Q: Convexity, mean gradients and minimizing constants If $\,f: \mathbb{R}^2 \to \mathbb{R}, (x_1, x_2) \mapsto f(x_1, x_2)$ is convex in the $x_2$ axis for all $x_1$, and $A, B \subseteq \mathbb{R}^2$ are both non-empty, is the following true?
$$\frac{1}{|A|}\sum_{\mathbf{x} \in A}\frac{\partial f}{\partial x_2}(x_1, x_2) < \frac{1}{|B|}\sum_{\mathbf{x} \in B}\frac{\partial f}{\partial x_2}(x_1, x_2)\iff$$
$$\underset{\alpha \in \mathbb{R}}{\text{argmin}}\sum_{\mathbf{x} \in A}f(x_1, x_2 + \alpha) > \underset{\beta \in \mathbb{R}}{\text{argmin}}\sum_{\mathbf{x} \in B}f(x_1, x_2 + \beta)$$


text:
Q: how to validate multiple steps FORM I have query how to validate multiple step form, i create a form and it has a three sections in a same page,
1.Personal Info,
2.Contact info,
3.Conformation details.
My question is:
If these specific inputs of step1 are all valid and return "true" in #Form, the step-two button will (be activated/take you to the next step) and similarly wth step 2 if all specific input are all valid and return true the step3 will activate
how to validate form in steps when i am using jquery validation
my code is here:
$(document).ready(function() {
var navHTML = '' + ''; $(function(){

        // init
        $('#Form > div')
            .hide()
            .append(navHTML);
        $('#first-step .prev-als').remove();
        $('#last-step .form-next').remove();

        // show first step
        $('#first-step').show();
$("a.form-next").click(function() {

    var whichStep = $(this).parent().parent().attr('id');

            if( whichStep == 'first-step' )
            {

      $("#first-step").validate();
                if($("#form").valid()==false)  return false;
//Dont navigate to second page

            }
            else if( whichStep == 'second-step' )

            {

            }

            else if( whichStep == 'last-step' )
            {
                // validate last-step
            }
$(this).parent().parent().hide().next().show(); });

$('a.prev-als ').click(function(){
            $(this).parent().parent().hide().prev().show();
        });

    });

});

A: If you want to do this in the browser, consider using the jQuery Wizard Plugin located here: http://worcesterwideweb.com/2007/06/04/jquery-wizard-plugin/
A demo of the plugin in action can be found here: http://worcesterwideweb.com/jquery/wizard/


text:
Q: Parsing Images Into Multiple Images I'm making a game with custom text icons, I want to load each of the images from one Image. How can I split one Image into a bunch of other images that are just part of the original images?

A: I think you are looking for CropImageFilter

An ImageFilter class for cropping images. This class extends the basic ImageFilter Class to extract a given rectangular region of an existing Image and provide a source for a new image containing just the extracted region

You have to use it with FilteredImageSource

This class is an implementation of the ImageProducer interface which takes an existing image and a filter object and uses them to produce image data for a new filtered version of the original image.

e.g.
public class Part extends JPanel {
    private Image src;

    public Part(Image src) {
        this.src = src;
    }

    public Image create(int xPos, int yPos, int width, int height) {
        ImageFilter cropImagefilter = new CropImageFilter(xPos, yPos, width, height); //see constructor detail
        FilteredImageSource filteredImageSource = new FilteredImageSource(this.src.getSource(), cropImagefilter)
        Image part = createImage(filteredImageSource);
        return part;
    }
}


text:
Q: I want to make use of expandlelistView to display products and the sub products I want to make use of expandlelistView to display products and the sub products, which is the childHolder, in the childHolder, it contains a textView and an Edittext which holds the value for the product count for each sub product, the problem here is this.

*

*When I input the values in the edittext, upon collapsing the group, the data is lost in the edittext.

*The values get duplicated in the other group edittext.
3.How to save the data for later use in the Application.
The code below.
The activity layout.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.activities.ShelfCheckActivity">

<ExpandableListView
    android:id="@+id/listview"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:dividerHeight="0dp"
    android:groupIndicator="@null"
    android:descendantFocusability="beforeDescendants"/>

</RelativeLayout>

The adapter class
public class ShelfCheckAdapter extends BaseExpandableListAdapter {

ArrayList<ListItemModel> groupItem;
GroupViewHolder groupViewHolder;
ChildViewHolder childViewHolder;
Context context;
public LayoutInflater layoutInflater;

public ShelfCheckAdapter(ArrayList<ListItemModel> groupItem, Context
context) {
    this.groupItem = groupItem;
    this.context = context;
}

public  void setInflater(LayoutInflater inflater)
{
    this.layoutInflater = inflater;
}

@Override
public int getGroupCount() {
    return groupItem.size();
}

@Override
public int getChildrenCount(int groupPosition) {
    return groupItem.get(groupPosition).getArrayList().size();
}

@Override
public Object getGroup(int groupPosition) {
    return groupItem.get(groupPosition);
}

@Override
public Object getChild(int groupPosition, int childPosition) {
    return groupItem.get(groupPosition).getArrayList().get(childPosition);
}

@Override
public long getGroupId(int groupPosition) {
    return groupPosition;
}

@Override
public long getChildId(int groupPosition, int childPosition) {
    return childPosition;
}

@Override
public boolean hasStableIds() {
    return false;
}

@Override
public View getGroupView(int groupPosition, boolean isExpanded, View
convertView, ViewGroup parent) {
    if(convertView == null)
    {
        groupViewHolder = new GroupViewHolder();
        convertView = layoutInflater.inflate(R.layout.list_row_group,null);
        groupViewHolder.groupTitle = (TextView)
   convertView.findViewById(R.id.textViewGroup);
        convertView.setTag(groupViewHolder);
    }
    else{
        groupViewHolder = (GroupViewHolder) convertView.getTag();
    }

groupViewHolder.groupTitle.setText(groupItem.get(groupPosition).getTitle());

    return convertView;
}

@Override
public View getChildView(int groupPosition, int childPosition, boolean
    isLastChild, View convertView, ViewGroup parent) {
    if(convertView == null)
    {
        childViewHolder = new ChildViewHolder();
        convertView =
   LayoutInflater.from(context).inflate(R.layout.list_row_child,null);
        childViewHolder.childTitle =
    convertView.findViewById(R.id.textViewChild);
        childViewHolder.et = convertView.findViewById(R.id.productCount);

        convertView.setTag(childViewHolder);

    }
    else{
        childViewHolder = (ChildViewHolder) convertView.getTag();
    }
  childViewHolder.childTitle.setText(groupItem.get(groupPosition)
 .getChildTitles().get(childPosition));

    if (!groupItem.get(groupPosition).getArrayList()
    .get(childPosition).getValue().equals(""))
        childViewHolder.et.setText(groupItem.get(groupPosition)
 .getArrayList().get(childPosition).getValue());
    else
        childViewHolder.et.setText("");

    childViewHolder.et.setOnFocusChangeListener((v, hasFocus) -> {
        if (!hasFocus){
            final EditText Caption = (EditText) v;

  groupItem.get(groupPosition)
  .getArrayList().get(childPosition).setValue(Caption.
   getText().toString());
        }
    });

      return convertView;

}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
    return false;
}

private class GroupViewHolder {
    public TextView groupTitle;
}

private class ChildViewHolder {
    public TextView childTitle;
    public EditText et;
}
}

The model class
public class ListItemModel {

String title;
ArrayList<EdittextValues> arrayList = new ArrayList<>();

public ListItemModel(String title) {
    this.title = title;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public ArrayList<EdittextValues> getArrayList() {
    return arrayList;
}

public void setArrayList(ArrayList<EdittextValues> arrayList) {
    this.arrayList = arrayList;
}
}

The pojo class
public class EdittextValues {
String value;

public EdittextValues(String value) {
    this.value = value;
}

public String getValue() {
    return value;
}

public void setValue(String value) {
    this.value = value;
}
}

The activity class
public class ShelfCheckActivity extends AppCompatActivity implements
SearchView.OnQueryTextListener {

private ExpandableListView expandableListView;

ShelfCheckAdapter shelfCheckAdapter;
ArrayList<ListItemModel> listItemModels;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_shelf_check);

    // initializing the views
    initViews();

    // preparing list data
    //initListData();

}

/**
 * method to initialize the views
 */
private void initViews() {

    expandableListView = findViewById(R.id.listview);
    initListData();
    shelfCheckAdapter = new
    ShelfCheckAdapter(listItemModels,ShelfCheckActivity.this);

 shelfCheckAdapter
 .setInflater((LayoutInflater)
   getSystemService(Context.LAYOUT_INFLATER_SERVICE));
    expandableListView
  .setAdapter(shelfCheckAdapter);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_store_check, menu);

    MenuItem menuItem = menu.findItem(R.id.action_search);
    SearchView searchView = (SearchView) menuItem.getActionView();

    searchView.setOnQueryTextListener(this);
    return true;
}

private void initListData() {

    ArrayList<EdittextValues> edittextValues = new ArrayList<>();

    ArrayList<String> childTitle = new ArrayList<>();
    childTitle.add("Product a");
    childTitle.add("Product b");
    childTitle.add("Product c");
    childTitle.add("Product d");
    childTitle.add("Product e");
    childTitle.add("Product f");
    childTitle.add("Product g");
    childTitle.add("Product h");
    childTitle.add("Product i");
    childTitle.add("Product j");
    childTitle.add("Product k");
    childTitle.add("Product l");

    for(int i = 0; i < childTitle.size(); i++)
    {
        edittextValues.add(new EdittextValues(""));
    }

    listItemModels = new ArrayList<>();
    listItemModels.add(new ListItemModel("Product
    1",edittextValues,childTitle));
    listItemModels.add(new ListItemModel("Product
    2",edittextValues,childTitle));
    listItemModels.add(new ListItemModel("Product
    3",edittextValues,childTitle));
    listItemModels.add(new ListItemModel("Product
    4",edittextValues,childTitle));
    listItemModels.add(new ListItemModel("Product
    5",edittextValues,childTitle));
    listItemModels.add(new ListItemModel("Product
    6",edittextValues,childTitle));

  }

  @Override
   public boolean onQueryTextSubmit(String s) {
    return false;
  }

   @Override
  public boolean onQueryTextChange(String s) {
    return false;
  }
  }

enter image description here

A: Just change below methods and check its working or not!
@Override
public View getChildView(int groupPosition, int childPosition, boolean
    isLastChild, View convertView, ViewGroup parent) {
    if(convertView == null)
    {
        convertView = LayoutInflater.from(context).inflate(R.layout.list_row_child,null);
        childViewHolder = new ChildViewHolder(convertView, groupPosition, childPosition);
        convertView.setTag(childViewHolder);
    }
    else{
        childViewHolder = (ChildViewHolder) convertView.getTag();
    }
  childViewHolder.childTitle.setText(groupItem.get(groupPosition)
 .getChildTitles().get(childPosition));

      return convertView;

}

Another change is
private class ChildViewHolder {
    public TextView childTitle;
    public EditText et;

    public ChildViewHolder(View itemView, int groupPosition, int childPosition) {
        super(itemView);
        childTitle = itemView.findViewById(R.id.textViewChild);
        et = itemView.findViewById(R.id.productCount);

        et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if(charSequence != null){
                      groupItem.get(groupPosition).getArrayList().get(childPosition).setValue(charSequence.toString());
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

}


text:
Q: Python Tkinter Entry() Calculations I am currently trying to build a GUI calculator using python with the help of tkinter. I have managed to set up all of my buttons and they interact with my entry() bar when I press the button (e,g: Press button 5 and 5 appears into the entry()).
The only thing left to do is actually perform the mathematical equations that appear in the entry(). For example, if I enter 5 + 5 * 2 into the entry bar, how would I make the answer appear into the entry() after it's updated? So basically all I'm asking is someone to help me make this happen!
I have provided the code below and a screenshot of the calculator. Also please don't report this as a duplicate or flag this question as a post, (I'm reasking this question because I got no help on my last one so please help a young python programmer out!). Also I'm asking you not to provide me with links because I've read every possible link on tkinter there is to read and still have no clue what I'm doing.
Here is my code:
import sys
from tkinter import *
from PIL import Image, ImageTk

#ACTIONS:
def clear():
    #Action: Clears the entry().
    txtDisplay.delete(0,END);
    return;

def update_Entry(inputValue):
    #Updates the entry when a button is pressed.
    currentText = num1.get();
    update = num1.set(currentText + inputValue);

#Parent Window.
root = Tk();
root.title('Calculator ++ [1.7.2]');
root.geometry('350x450');

#Main entry.
num1 = StringVar();
txtDisplay = Entry(root, textvariable = num1, relief=RIDGE, bd = 10, width=33, insertwidth = 1, font = 40, justify=RIGHT);
txtDisplay.place(x=15, y=10);
txtDisplay.focus();

print(txtDisplay.get())

#Buttons:
zeroButton = Button(root, text='0', width=20, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('0'));
zeroButton.place(x=17,y=382);
oneButton = Button(root, text='1', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('1'));
oneButton.place(x=17, y=302);
twoButton = Button(root, text='2', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('2'));
twoButton.place(x=100, y=302);
threeButton = Button(root, text='3', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('3'));
threeButton.place(x=182, y=302);
fourButton = Button(root, text='4', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('4'));
fourButton.place(x=17, y=222);
fiveButton = Button(root, text='5', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('5'));
fiveButton.place(x=100, y=222);
sixButton = Button(root, text='6', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('6'));
sixButton.place(x=182, y=222);
sevenButton = Button(root, text='7', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('7'));
sevenButton.place(x=17, y=142);
eightButton = Button(root, text='8', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('8'));
eightButton.place(x=100, y=142);
ninthButton = Button(root, text='9', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('9'));
ninthButton.place(x=182, y=142);

decimalButton = Button(root, text='.', width=8, height=3, bg='powder blue', command=lambda:update_Entry('.'));
decimalButton.place(x=182, y=382);
equalButton = Button(root, text='=', width=8, height=8, bg='Lightgreen', command=lambda:update_Entry('='));
equalButton.place(x=264, y=307);
plusButton = Button(root, text='+', width=8, height=3, bg='gray', command=lambda:update_Entry('+'));
plusButton.place(x=264, y=222);
minusButton = Button(root, text='-', width=8, height=3, bg='gray', command=lambda:update_Entry('-'));
minusButton.place(x=264, y=142);
multiplyButton = Button(root, text='x', width=8, height=3, bg='gray', command=lambda:update_Entry('*'));
multiplyButton.place(x=264, y=66);
divideButton = Button(root, text='÷', width=8, height=3, bg='gray', command=lambda:update_Entry('/'));
divideButton.place(x=182, y=66);
clearButton = Button(root, text='Clear (CE)', width=20, height=3, command = clear, bg='Orange');
clearButton.place(x=17, y=66);

#Locks the parent windows size.
root.maxsize(350,450);
root.minsize(350,450);

#Parent window's background color:
root.configure(background = 'black');
root.mainloop();

Screenshot:

A: For something this simple, try having this as the command for your equalButton:
def evaluate():
    currentText = num1.get()
    try:
        num1.set(str(eval(currentText)))
    except SyntaxError:
        num1.set('<ERROR>')


text:
Q: Facing a problem with Return URL asp dotnet core version 3.1 Im using Identity framework When Use [Authorize] in get method the url shows https://localhost:44329/Account/Login?ReturnUrl=%2FAdmin%2FProductTypes%2FCreate
but it should be https://localhost:44329/Identity/Account/Login?ReturnUrl=%2FAdmin%2FProductTypes%2FCreate
Why Identity Missing in Url?
Startup.cs file code
namespace OnlineShop
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            services.AddIdentity<IdentityUser,IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>();
            services.AddControllersWithViews();
            services.AddRazorPages();
            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(30);
                //options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;
            });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseSession();
            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "areas",
                    pattern: "{area=Customer}/{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }
    }
}

A: .AddIdentity() does not contains build-in pages, you need add .AddDefaultUI() to use default UI:
services.AddIdentity<IdentityUser,IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddDefaultUI()          //add this line....
        .AddEntityFrameworkStores<ApplicationDbContext>();


text:
Q: How to Resolve Undefined Array Key Warning? I am trying to submit a form with two conditions regulated by a checkbox. If the second condition is true, I get a warning message--Undefined array key "outside" in C:\xampp\htdocs\Taxi. I tried the following code:
if (isset($_POST['assign'])){
    $tid=addslashes($_POST['tid']);
    require 'dbconnect.php';
    if(addslashes($_POST['outside']))
    {
        $outside=addslashes($_POST['outside']);
        $outinv=addslashes($_POST['inv']);
        $sql = "UPDATE trips SET inventory='$outside',cardetails='$inv' WHERE id='$tid'";
        $stmt = $con->prepare($sql);
        $stmt->execute();
    }
    else if(!addslashes($_POST['outside'])){
        $asn=addslashes($_POST['asn']);
        echo $asn;
    }
}

A: Maybe you want this.
if (isset($_POST['assign'])){

$tid=addslashes($_POST['tid']);

 require 'dbconnect.php';

if(isset($_POST['outside']))
{
$outside=addslashes($_POST['outside']);
 $outinv=addslashes($_POST['inv']);

 $sql = "UPDATE trips SET inventory='$outside',cardetails='$inv' WHERE id='$tid'";
$stmt = $con->prepare($sql); $stmt->execute();

 }
else {
$asn=addslashes($_POST['asn']);
echo $asn;

}
}


text:
Q: BizTalk Mapping supress empty attribute in the destination I have a case in BizTalk where I want to map an "Attribute Node" which type is Date that can't be null or empty and to avoid problems I need to suppress in the destination transformation map when the source is null.
I followed this link to try the same thing that we do with Nodes but doesn't answer my problem.
https://social.technet.microsoft.com/Forums/security/en-US/4ab184e0-c978-429c-a80d-e869732de8a2/how-to-suppress-empty-nodes-in-biztalk-map?forum=biztalkgeneral
Anyone have an idea?
Thank you,
Roberto

Edited
The link didn't mentioned that the Logical String returns True or Nill depending on your source.
I've obliged to check if is empty and as well null

A: From the source, connect to a Length Functoid, then Greater Than 1 Functoid.
Connect the Greater Than Functoid to the target.
However you end up composing it, connecting a Functoid that returns a boolean is treated as a create yes/no regardless of any value also mapped.


text:
Q: ios - How to declare URLDecode? I'm trying to get access token,when I decode URL it's getting an error,I think am declaring wrong here.How to declare URLDecode to get access token?
in .h file
@interface NSString (URLDecode)

-(NSString *)URLDecode;

@end

in .m file
-(NSString *)URLDecode

    {

        NSString *result = [(NSString*)self stringByReplacingOccurrencesOfString:@"+" withString:@" "];
        result = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        return result;
    }

- (NSDictionary*)parsePairs:(NSString*)urlStr

{

    NSRange r = [urlStr rangeOfString:@"="];
    if(r.length == 0)
    {
        return nil;
    }

    //Here I'm getting an error

    NSString* token = [[urlStr substringFromIndex:r.location + 1 ] URLDecode];

    NSCharacterSet* objectMarkers;
    objectMarkers = [NSCharacterSet characterSetWithCharactersInString:@"{}"];
    token = [token stringByTrimmingCharactersInSet:objectMarkers];

    NSError* regexError;
    NSMutableDictionary* pairs = [NSMutableDictionary dictionaryWithCapacity:10];

    NSRegularExpression* regex;
    regex = [NSRegularExpression regularExpressionWithPattern:@"\"([^\"]*)\":\"([^\"]*)\""
                                                      options:0
                                                        error:&regexError];
    NSArray* matches = [regex matchesInString:token
                                      options:0
                                        range:NSMakeRange(0, token.length)];

    for(NSTextCheckingResult* result in matches)
    {
        for(int n = 1; n < [result numberOfRanges]; n += 2)
        {
            NSRange r = [result rangeAtIndex:n];
            if(r.length > 0)
            {
                NSString* name = [token substringWithRange:r];

                r = [result rangeAtIndex:n + 1];
                if(r.length > 0)
                {
                    NSString* value = [token substringWithRange:r];

                    [pairs setObject:value forKey:name];
                }
            }
        }
    }

    regex = [NSRegularExpression regularExpressionWithPattern:@"\"([^\"]*)\":([0-9]*)"
                                                      options:0
                                                        error:&regexError];
    matches = [regex matchesInString:token
                             options:0
                               range:NSMakeRange(0, token.length)];

    for(NSTextCheckingResult* result in matches)
    {
        for(int n = 1; n < [result numberOfRanges]; n += 2)
        {
            NSRange r = [result rangeAtIndex:n];
            if(r.length > 0)
            {
                NSString* name = [token substringWithRange:r];

                r = [result rangeAtIndex:n + 1];
                if(r.length > 0)
                {
                    NSString* value = [token substringWithRange:r];
                    NSNumber* number = [NSNumber numberWithInt:[value intValue]];

                    [pairs setObject:number forKey:name];
                }
            }
        }
    }

    return pairs;
}

Any ideas?

A: You need to make a cetgory of NSString in your Xcode project as :
1.

*Then do as :

Then when you click Next button a cetgory will be created of NSString . Then use add code in that. And then Import this category in your class as :
#import "NSString+URLDecode.h"

and then call method declared in category over NSString as
NSString *decodedUrlStr = [urlStr URLDecode];

Hope it helps you.


text:
Q: When can you call functions with labeled arguments without the labels? It seems that in certain situations you can call functions with labeled arguments without the labels if they're in the right order; e.g.
let f ~x ~y = Format.sprintf "%d %s" x y;;
f 3 "test";;

runs successfully, but
f "test" 3;;

fails with the error message
Line 1, characters 2-8:
Error: This expression has type string but an expression was expected of type
         int

For functions with optional arguments, it seems to work if you don't pass in the optional arguments:
let f ?(x = 1) ~y () = Format.sprintf "%d %s" x y;;
f "help" ();;

succeeds, but
f 2 "help" ();;

fails with the error message
Line 1, characters 4-10:
Error: The function applied to this argument has type
         ?x:int -> y:string -> string
This argument cannot be applied without label

Is there a general rule for when this is possible?

A: You can omit labels if the application is total (i.e., all required arguments are provided) and if the return type of the function is not a type variable. Arguments to the optional parameters must always be passed by a label.
Let's do some examples,
let example1 ?(opt=0) ~a ~b ~c unlabeled =
  opt + a + b + c + unlabeled;;

example1 1 2 3 4;;
- : int = 10

Here we were able to apply all arguments without labels, because we have provided all required arguments (the optional parameter is not required, hence the name), and the resulting type is not polymorphic. However, if we will take the List.fold function from Core or ListLabels, which has type
'a list -> init:'accum -> f:('accum -> 'a -> 'accum) -> 'accum

Then we will get,
List.fold [1;2;3;4] 0 (+);;
- : init:(int -> (int -> int -> int) -> '_weak1) ->
    f:((int -> (int -> int -> int) -> '_weak1) ->
       int -> int -> (int -> int -> int) -> '_weak1) ->
    '_weak1

instead of 10, which one would expect. The reason for that is since the resulting type 'accum is a type variable, so it could also be a function, e.g., int -> int or string -> int -> unit, etc -- all those types match with the 'accum type. That basically means that this function accepts a potentially infinite number of positional arguments. Therefore, all arguments that we provided were interpreted as positional, and as a result, we never were able to fill in the labeled arguments, therefore, our application wasn't made total. This actually makes our original definition of the rule at the beginning of the posting redundant - since an application, which type is denoted with a type variable, could never be total.
Note, that this problem only occurs when the return type is a type variable, not just includes some type variables, for example, we can easily omit labels with the List.map function, e.g, given List.map from Core, which has type
'a list -> f:('a -> 'b) -> 'b list

we can easily apply it
# List.map [1;2;3] ident;;
- : int Core_kernel.List.t = [1; 2; 3]

With all that being said, it is usually assumed a bad practice to omit the labels. Mainly because of the caveats with polymorphic return types and because it makes the order of the labeled arguments important, which is sort of counter-intuitive.

A: Yes, there is a general rule for this. From the manual:

Formal parameters and arguments are matched according to their respective labels, the absence of label being interpreted as the empty label. This allows commuting arguments in applications. One can also partially apply a function on any argument, creating a new function of the remaining parameters.
If several arguments of a function bear the same label (or no label), they will not commute among themselves, and order matters. But they can still commute with other arguments.
As an exception to the above parameter matching rules, if an application is total (omitting all optional arguments), labels may be omitted. In practice, many applications are total, so that labels can often be omitted.


text:
Q: How to cancel pending retries on Polly's async WaitAndRetryPolicy I'm using polly for a simple retry n-times szenario on a HTTP POST-request. It should handle any exception and retry to post my payload to the api-endpoint for n-times. Therefore I used a WaitAndRetryPolicy wraping a TimoutPolicy with a pessimistic strategy for a timeout per try. Both as async policies.
When the retry-case is taking place every retry-attempt, which was made, is posted to the endpoint after connection is re-esteblished.
The method which wraps the two policies up:

    public static PolicyWrap WaitAndRetryNTimesWithTimeoutPerTry(int n, TimeSpan sleepDuration, TimeSpan retryTimeout)
    {
        var waitAndRetryPolicy = Policy.Handle<Exception>().WaitAndRetryAsync(
        retryCount: n,
            sleepDurationProvider: attempt => sleepDuration,
            onRetry: (exception, waitDuration, ctx) =>
            {
                Debug.WriteLine($"[Polly.OnRetry due '{exception.Message}'; waiting for {waitDuration.TotalMilliseconds} ms before retrying.");
            }
        );

        var timeoutPerTryPolicy = Policy.TimeoutAsync(
            retryTimeout, TimeoutStrategy.Pessimistic);

        return waitAndRetryPolicy.WrapAsync(timeoutPerTryPolicy);
    }

The code which calls the web api:

    var waitAndRetry5TimesWithShortTimeout = ResiliencePolicyFactory.WaitAndRetryNTimesWithTimeoutPerTry(
        n: 5,
        sleepDuration: TimeSpan.FromMilliseconds(700),
        retryTimeout: TimeSpan.FromMilliseconds(2300));
        }

    try
    {
        await waitAndRetry5TimesWithShortTimeout.ExecuteAndCaptureAsync(async token =>
        {
            if (!cancellationToken.IsCancellationRequested)
            {
                response = await client.PostAsync(uri, content, cancellationToken);
                if (response.IsSuccessStatusCode)
                {
                    Debug.WriteLine($"[{nameof(CheckinService)}] ===>> Now Checked in!");
                }
            }
        }, cancellationToken);
    }
    catch(Exception ex)
    {
        throw new ApplicationException("NoCheckInPossible", ex);
    }

When the code hits the retry case and succeed after several retries, every retry-attempt made, is posted to endpoint, eventough I'm passing the cancellation token to ExecuteAsync-Task and the HttpClient.
In my understanding the first successfull request should cancel all pending retries. Can anybody point out, what I'm doing wrong?

A: The issue looks to be that this line:
response = await client.PostAsync(uri, content, cancellationToken);

is using a variable called cancellationToken, not the variable token which Polly passes in to the executed delegate at async token =>.
Using the below should fix it:
response = await client.PostAsync(uri, content, token);

Explanation
Polly timeout policies combine a timing-out CancellationToken into any cancellationToken the caller passes into the execution, but for that timing-out token to have any effect, within the executed delegate you must use the token Polly supplies to the execution (the variable token in this case).
(From the code posted in the question, we can't see that anything signals cancellation of cancellationToken; if something does, please comment or edit the question to clarify.)
With the code client.PostAsync(uri, content, cancellationToken), if nothing is cancelling cancellationToken, then each POST never gets cancelled, which likely explains why you are seeing multiple POSTs run to completion.
Demonstration
I made a runnable reproducible example close to your posted code, to demonstrate.
public static Random rand = new Random();

public static async Task Main()
{

    var waitAndRetry5TimesWithShortTimeout = WaitAndRetryNTimesWithTimeoutPerTry(
        n: 5,
        sleepDuration: TimeSpan.FromMilliseconds(70),
        retryTimeout: TimeSpan.FromMilliseconds(230));

    CancellationToken cancellationToken = new CancellationTokenSource().Token;

    string response;
    try
    {
        await waitAndRetry5TimesWithShortTimeout.ExecuteAndCaptureAsync(async token =>
        {
            Console.WriteLine("Placing call");
            if (!cancellationToken.IsCancellationRequested)
            {
                response = await PretendPostAsync(cancellationToken); // Change 'cancellationToken' to 'token' here, and it will start to work as expected.
                if (response == "success")
                {
                    Console.WriteLine($"Now Checked in!");
                }
            }
        }, cancellationToken);
    }
    catch(Exception ex)
    {
        throw new ApplicationException("NoCheckInPossible", ex);
    }

}

public static async Task<string> PretendPostAsync(CancellationToken token)
{
    if (rand.Next(4) != 0)
    {
        await Task.Delay(TimeSpan.FromSeconds(0.5), token);
    }

    return "success";
}

public static AsyncPolicyWrap WaitAndRetryNTimesWithTimeoutPerTry(int n, TimeSpan sleepDuration, TimeSpan retryTimeout)
{
    var waitAndRetryPolicy = Policy.Handle<Exception>().WaitAndRetryAsync(
    retryCount: n,
        sleepDurationProvider: attempt => sleepDuration,
        onRetry: (exception, waitDuration, ctx) =>
        {
            Console.WriteLine($"[Polly.OnRetry due '{exception.Message}'; waiting for {waitDuration.TotalMilliseconds} ms before retrying.");
        }
    );

    var timeoutPerTryPolicy = Policy.TimeoutAsync(
        retryTimeout, TimeoutStrategy.Pessimistic);

    return waitAndRetryPolicy.WrapAsync(timeoutPerTryPolicy);
}

You can run this in DotNetFiddle here and see that it typically gives output like:
Placing call
[Polly.OnRetry due 'The delegate executed asynchronously through TimeoutPolicy did not complete within the timeout.'; waiting for 70 ms before retrying.
Placing call
Now Checked in!
[Polly.OnRetry due 'The delegate executed asynchronously through TimeoutPolicy did not complete within the timeout.'; waiting for 70 ms before retrying.
Placing call
Now Checked in!

(The code example randomises to simulate different degrees of failure; you might have to run it a few times to see similar results.)
Multiple calls clearly get placed (Placing call), and multiple run to completion (Now Checked in!), because nothing cancels them.
Change the line indicated to use token, and it can be seen that even if multiple calls are placed, earlier tries are cancelled, and only one succeeds.
Placing call
[Polly.OnRetry due 'The delegate executed asynchronously through TimeoutPolicy did not complete within the timeout.'; waiting for 70 ms before retrying.
Placing call
[Polly.OnRetry due 'The delegate executed asynchronously through TimeoutPolicy did not complete within the timeout.'; waiting for 70 ms before retrying.
Placing call
Now Checked in!

Tidying up
Because HttpClient.PostAsync(...) does honor CancellationTokens, you can use the slightly more efficient TimeoutStrategy.Optimistic.


text:
Q: How do I implement a custom handleChange function on Formik? In an input element, handleChange function would receive the event object from the onChange event. How do I create a custom handleChange function for non-input fields like the following?
import React from 'react';
import { useFormik } from "formik";

const SomeForm = () =>
{
  const { handleChange, handleSubmit, values } = useFormik({
    initialValues: {
      type: `company`, name: ``,
    },
    onSubmit: values => {
      console.log(JSON.stringify(values, null, 2));
    },
  });

  return (

      <form onSubmit={ handleSubmit }>
        Type

          <li className={ values.type === `company` && `active` }
               onClick={() => handleChange(/* some custom handle change */)} >
              Company

          <li className={ values.type === `individual` && `active` }
               onClick={() => handleChange(/* some custom handle change */)} >
              Individual

        Full Name

        <input type="text"
               name="name"
               value={ value.name }
               onChange={ handleChange } />
      </form>

  )
};

export default SomeForm;

A: use setField('fieldName',value) method of form object provided in render props pattern of Field component.

A: I think this is what you're after. You can add your custom code after field.onChange(e).
// Custom field
const MyTextField = ({ label, ...props }) => {
    const [field, meta] = useField(props);
    return (
        <>
            <input {...field} {...props}
                   onChange={e => {

                       // The original handler
                       field.onChange(e)

                       // Your custom code
                       console.log('I can do something else here.')

                   }}
                   className={ meta.error && 'is-invalid'}` }  />
            {meta.touched && meta.error && (

{meta.error}

            )}

        </>
    );
};

And use it like so
<MyTextField name="entry" type="text" />


text:
Q: How to get incremental recoverage with Jacoco I want to get a incremental code coverage report with Jacoco.
I modified some codes and it can get an incremental code coverage. But I got a problem.
1.I deploy a app(v1) and test "A" file 0-100 line codes, then I got a report(r1).
2.I modified some bugs(v2) and test "A" file 0-10 lines(verify a bug),then test 101-200 line codes, then I got a report(r2).

I want to merge r1 and r2 reports to show that I'm already test "A" file 0-200 lines.Does anybody has some idea?


text:
Q: AXIS2/C and ONVIF I'm trying to create the stub of the wsdl http://www.onvif.org/onvif/ver10/device/wsdl/devicemgmt.wsdl using AXIS2/C (c++), using the following command:

./WSDL2CPP.sh -uri http://www.onvif.org/onvif/ver10/device/wsdl/devicemgmt.wsdl

and I get the following answer:
Exception in thread "main" org.apache.axis2.wsdl.codegen.CodeGenerationException: Error parsing WSDL
    at org.apache.axis2.wsdl.codegen.CodeGenerationEngine.<init>(CodeGenerationEngine.java:153)
    at org.apache.axis2.wsdl.WSDL2Code.main(WSDL2Code.java:35)
    at org.apache.axis2.wsdl.WSDL2CPP.main(WSDL2CPP.java:19)
Caused by: org.apache.axis2.AxisFault: **`No service was not found in the WSDL at http://www.onvif.org/onvif/ver10/device/wsdl/devicemgmt.wsdl with targetnamespace http://www.onvif.org/ver10/device/wsdl`**
    at org.apache.axis2.description.WSDL11ToAllAxisServicesBuilder.populateAllServices(WSDL11ToAllAxisServicesBuilder.java:115)
    at org.apache.axis2.wsdl.codegen.CodeGenerationEngine.<init>(CodeGenerationEngine.java:147)
    ... 2 more

A: I used the hack used on python-zeep, but it helps with axis2/c as well:
Add this to devicemgmt.wsdl, just before the close tag "</wsdl:definitions>":
<wsdl:service name="DeviceService">
             <wsdl:port name="DevicePort" binding="tds:DeviceBinding">
               <soap:address location="http://192.168.1.100/onvif/device_service"/>
             </wsdl:port>
</wsdl:service>

However, I'm still having problems generating the code with any of the variable bindings ("XSD complexType with mix content not supported in ADB"). I had to disable it as follows:
./WSDL2C.sh -o ../axis2c-test/gen -d none -uri devicemgmt.wsdl

A: This error normally coming because of the tool cannot find a service element in the WSDL. Because in WSDL definition it has to have a endpoint defined. Please check your WSDL whether it has a service element included or any other imported WSDL has the service element.
So basically to get rid of this you have to define a endpoint in this WSDL.


text:
Q: how to fix ffmpeg-python outputting abnormal size after combining audio and video file I am trying to combine audio and video using ffmpeg-python. my video file is 40mb and my audio file is 5mb but when i combine them i am getting 90mb which is abnormal. i was expecting the output file to be the size of the video file + the size of the audio file. My question is, how can I maintain the size of the output file to be equal to the size of the input video and audio file?
import ffmpeg
input_video = ffmpeg.input('video.mp4)
input_audio = ffmpeg.input('audio.mp4')
ffmpeg.concat(input_video, input_audio, v=1, a=1).output('finished_video.mp4').run()


text:
Q: How to fetch data while ignoring some specific fields? With a model Book that uses MarkDown for a field called content, when I do the following query
Book.objects.filter(published=True).order_by('read')

The site becomes slow because of the content field, I think the hard work occurs when Django tries to convert these fields to python object. When I clean all the content field for each record and leave them blank, the query is pretty much faster.
In my case content field contains large text. To gain in performance, How can I fetch data by ignoring a specific field?
I want to ignore content field like:
Book.objects.filter(published=True)#.ignore_fields('content',).order_by('read')

A: Try to use defer:
Book.objects.defer('content').filter(published=True).order_by('read')


text:
Q: Set JavaScript object property with a function I'm trying to set the property of an object with a function but instead, I get a value of 100 and the slide bar stuck in the middle. What am I doing wrong? Here is my code:
term: {
        min: 1,
        max: function(){
          var period = document.getElementById("duration").value;
          if (this.period == "days"){
            var value = 31;
          } else if(this.period == "months"){
            value = 12;
          } else {
            value = 365;
          };
          return value;
        },

        step: 1,
        _value: 10,
        get value() {
          return parseFloat(this._value);
        },
        set value(val) {
          this._value = val;
        },
        reset: function() {
          this._value = 12;
        }
      },

And this is the result on th UI:

EDIT:
This is how I use min and max:
document.querySelectorAll('.controller-row')
    .forEach(function(group) {
      var min = inputValues[group.id].min;
      var max = inputValues[group.id].max;
      var value = inputValues[group.id].value;
      var step = inputValues[group.id].step;

      var boundary = max ? 100 * (value - min) / (max - min) : 0;

      var range = group.querySelector('input[type=range]');

      range.setAttribute('style',
        'background-image: linear-gradient(90deg, #4098FF 0%, #4098FF ' + boundary + '%, white ' + boundary + '%);'
      );
      range.min = min;
      range.max = max;
      range.value = value;
      range.step = step;

      var textInput = group.querySelector('input[type=number]');
      textInput.min = min;
      textInput.max = max;
      textInput.value = value;
      textInput.step = step;
    });


text:
Q: URL as a string and values in Xcode I am working on a web service app and i have a question. I am calling a specific Url site with the following code:
NSURL *Url = [NSURL URLWithString:[requestStream stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

NSString *htmlString = [NSString stringWithContentsOfURL:Url encoding:NSUTF8StringEncoding error:&error];

Then i create an nsstring and print it with the NSLog and i got the following results:
2014-05-14 15:50:58.118 jsonTest[1541:907] Data : Array
(
    [url] => http://sheetmusicdb.net:8000/hnInKleinenGruppen
    [encoding] => MP3
    [callsign] => SheetMusicDB.net - J
    [websiteurl] =>
)

My question in how can i parse the URL link and then use it as a value? I tried to put them to an array or a dictionary but i get error back. So if anyone can help me i would appreciate it.
Ok i managed to grab the link with the following code:
if(htmlString) {
    //NSLog(@"HTML %@", htmlString);

    NSRange r = [htmlString rangeOfString:@"=>"];
    if (r.location != NSNotFound) {
        NSRange r1 = [htmlString rangeOfString:@"[encoding]"];
        if (r1.location != NSNotFound) {
            if (r1.location > r.location) {
                _streamTitle = [htmlString substringWithRange:NSMakeRange(NSMaxRange(r), r1.location - NSMaxRange(r))];
                NSLog(@"Title %@", _streamTitle);
            }
        }
    }
} else {
    NSLog(@"Error %@", error);
}

Thank you for your suggestions. My problem now is that i pass the string into an avplayer and i can't hear music.

A: I think this will be help for you..
// @property (nonatomic,retain) NSMutableData *responseData;
// @synthesize responseData;

NSString *urlString=@"http:your urls";
self.responseData=[NSMutableData data];
NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] delegate:self];
NSLog(@"connection====%@",connection);

JSON Delegates :
 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
 {
   [self.responseData setLength:0];
 }
 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
 {
    [self.responseData appendData:data];
 }
 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
 {
    self.responseData=nil;
 }
 -(void)connectionDidFinishLoading:(NSURLConnection *)connection
 {
      NSArray *response_Array = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:nil];

  //  Write code for retrieve data according to your Key.
 }

A: Try This:
NSString *urlStr=[NSString stringWithFormat:@"uRL"];
 NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

        NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

        if (theConnection)
        {
            receivedData=[[NSMutableData data] retain] ;
        }

#pragma mark - Connection Delegate
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    // append the new data to the receivedData
    // receivedData is declared as a method instance elsewhere

    //NSLog(@"data %@",data);
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // release the connection, and the data object
    //    [connection release];
    //    [receivedData release];

    UIAlertView *prompt = [[UIAlertView alloc] initWithTitle:@"Connection Failed" message:[error localizedDescription]delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [prompt show];

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    NSString *content = [[NSString alloc]  initWithBytes:[receivedData bytes]
                                                  length:[receivedData length] encoding: NSUTF8StringEncoding];
    NSData *jsonData = [content dataUsingEncoding:NSUTF32BigEndianStringEncoding];

    NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];

    }

}