Using HTTPOnly Cookie Returned from API in React app

Question: I am working on my first React application which consumes a REST API. Certain information within the API isn't accessible unless authorized by logging in, and the API returns an HTTPOnly cookie as a response upon a successful POST request to the login endpoint; I'm using axios, to accomplish this. It's possible to view the cookie within the network tab of the browser and it also successfully logged to the console, but I'm unsure of how I can actually store the information returned from the API within my react app. The cookie vanishes from the browser when I leave the page after logging in. Is there a way I can implement this cookie into the React App's memory/state so it can be sent and used upon future requests in the application? I've scoured for a few days and seen various methods to access a returned JWT, but most of them include using LocalStorage which isn't secure or are from deprecated tutorials many years ago. After logging in, the JWT returned from the API will need to be sent back upon future requests, which will also be made using axios.
All help is much appreciated.
Answer: You can configure the expiry of the HttpOnly cookie. It sounds like your server is currently storing the JWTs in HttpOnly session cookies. If you are using Chrome, you can confirm this by looking at the "Expires / Max-Age" column in the Application tab. If it is a session cookie, the field will be unspecified, and the cookie disappears once you end your browsing session. If you set the expiry of the HttpOnly cookie to say a year, then the cookie persists across browsing sessions.
Comment: Thank you for your comment. I checked and noticed that it's stored in the Network tab as a response cookie. It expires in one day so the expiration seems to not be the issue either. I think the issue comes in with storing/accessing the API's response cookie in the actual React app.
Comment: How did you store it? If the app is refreshed, is the session being restored?


Call a contact number for wp7

Question: In my contact app(for wp7), i am not able to correct this error at all. I have also added an image below. When i Tap on the contact number, am not able to Call that number. I am getting the following error- NullReferenceException. I have also used the PhoneCallTask.

In xaml-
<StackPanel x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

        <TextBlock Text="{Binding Path=DisplayName, Mode=OneWay}" Foreground="{StaticResource PhoneAccentBrush}" FontSize="{StaticResource PhoneFontSizeExtraLarge}" />

        <Border BorderThickness="2" HorizontalAlignment="Left" BorderBrush="{StaticResource PhoneAccentBrush}" >
            <Image Name="Picture" Height="175" Width="175" HorizontalAlignment="Left" />
        </Border>
        <TextBlock Height="50" Name="textBlock1" Text="call mobile" FontSize="40" Margin="0,30,0,0"/>
        <ListBox x:Name="ListBox" ItemsSource="{Binding Path=PhoneNumbers}" FontSize="64" Height="100"  Margin="0,0,0,0" SelectionChanged="ListBox_SelectionChanged">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>

                        <TextBlock Grid.Column="2" Text="{Binding Path=PhoneNumber, Mode=OneWay}" />
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </StackPanel>

In xaml.cs-
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);

        //Set the data context for this page to the selected contact
        this.DataContext = App.con;

        try
        {
            //Try to get a picture of the contact
            BitmapImage img = new BitmapImage();
            img.SetSource(App.con.GetPicture());
            Picture.Source = img;
        }
        catch (Exception)
        {
            //can't get a picture of the contact
        }
    }

    private void ListBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
    {
        SampleData data = (sender as ListBox).SelectedItem as SampleData;
        ListBoxItem selectedItem = this.ListBox.ItemContainerGenerator.ContainerFromItem(data) as ListBoxItem;
        PhoneCallTask PhoneTask = new PhoneCallTask();
        PhoneTask.PhoneNumber = data.PhoneNumbers;
        PhoneTask.Show();
    }

    public class SampleData
    {
        public string PhoneNumbers { get; set; }
    }

Can anybody help me with this? Thanks in advance for your hard work!
Answer: I am pretty sure the SelectedItem property is not of type SampleData, so the cast will fail and return null:
SampleData data = (sender as ListBox).SelectedItem as SampleData;

Therefore, this line throws a null reference exception, because data is null:
PhoneTask.PhoneNumber = data.PhoneNumbers;

Using the debugger, it should be easy to confirm this conclusion - if you are not in the habit of using the debugger to solve problems, i sincerely urge you to start using it ;-)
Comment: Yes you are right! I don't know how to use the debugger...Do you have any examples to show me how to use it.
Comment: @Mac, try following this tutorial: http://www.codeproject.com/Articles/79508/Mastering-Debugging-in-Visual-Studio-2010-A-Beginn

Call a contact number for wp7


Why is my server using a well known port as source port

Question: Is it normal that my server is requesting 184.108.40.206 dns with 22/udp as source port? How can i get it to use unregistered ports only
Comment: Could you add to the question the output of:
`lsb_release -a` ,
`cat /etc/resolv.conf`
and `resolvectl status` ?
Comment: I ll post it as soon as i can thanks
Comment: None of these commands work for me. I'm on rhel 7.
Comment: I expect `cat /etc/resolv.conf` to work for RHEL7. Could you share the error message?
Comment: search xxxx.pp
nameserver 18.104.22.168        no problem. Only that command is not recognised
Answer:
Is it normal that my server is requesting dns with 22/udp as source port?

No.
You would expect DNS queries from a client to use either:

a random ephemeral port (which you can adjust in <code>/proc/sys/net/ipv4/ip_local_port_range</code> but is typically 32769-60999)

when no port randomization is used: UDP port 53
Comment: Thank you HermanB ill check the referenced file
Comment: Port range is specified to ephemeral ports


Report in ANCOVA: descriptive means or estimated marginal means?

Question: I have conducted an analysis of covariance, ANCOVA, followed by Bonferroni post-hoc tests, on SPSS. I want to report the differences between my groups in text (APA style) and in a corresponding bar graph. My covariate (a different variable from the DV and IV, not a pretest) was found significant, so the descriptive means and the estimated marginal means (EMM) are different.
I want to know which of the means ("descriptive" or EMM) is better to report and put in the graph. One way to think about it is that the adjusted means are not real data but simply estimations from the software --nothing my article should be about. However my analysis will be drawn on the conclusions of the ANCOVA, comparing the EMM, so I should focus on the EMM.
I have explored various manuals and articles without finding a clear answer --I found everything and the opposite.
Should I graph the actual means as presented in the "descriptives" table, or should I graph the estimated marginal means?
Comment: Estimated marginal means are not only adjusted for the covariates; they are the predicted means with the collapsed subgroups _equally_ weighted. For example, consider you have two factors with groups A1 A2 B1 B2 and you want to know EMMs for B1 and B2 groups. Then EMM for B1 is the simple mean of 2 means of predicted values: mean(mean_predicted_value_in_A1B1, mean_predicted_value_in_A2B1).
Answer: Report estimated marginal mean and standard error in writing results and making graph.


Why We Need EventArgs class in C#?

Question: I know that the purpose of event keyword just to used in pair with += operator to make list of delegate. And when constructing delegate we can make any signature (of parameter) for method that compatible with that delegate.
For example I create  delegate
public delegate void StartEventHandler(object sender, StartEventArgs e);

with two parameter: the first with the type object and the second with the type StartEventArgs. But in many article that I found on the internet, the second parameter for that delegate must inherited EventArgs type. Why we do this instead to make the second parameter come/inherited from arbitrary type?
Answer: You don't need to and I'm sure the code will still compile if you used an arbitrary base class but it is a convention.
Conventions are good because it makes it easier to understand for people who are not familiar with your code already. If I subscribe to an event in C# I expect a certain method signature.
It is also good because it makes different types of events interchangeable.
For example, say you have three delegates
public delegate void AEventHandler(object sender, AEventArgs e);
public delegate void BEventHandler(object sender, BEventArgs e);
public delegate void CEventHandler(object sender, CEventArgs e);

You could write a generic method that conforms to all three delegates because all the args objects inherit from the same base class.
public void eventMethod(object sender, EventArgs e) {
    // Any one of the events fired
}

public void subscribeToEvents() {
    eventA += new AEventHandler(this.eventMethod);
    eventB += new BEventHandler(this.eventMethod);
    eventC += new CEventHandler(this.eventMethod);
}

And even cast if you know what types to expect
public void eventMethod(object sender, EventArgs e) {
    // Any one of the events fired
    if (e is BEventArgs) {
        // Event type B fired
        var eventB = e as BEventArgs;
        eventB.doSomething()
    }
}

Comment: If you're able to use C# 7 the pattern matching switch will enable "casting if you know what types to expect".

Why We Need EventArgs class in C#?


Laravel resource route parameters not overriding

Question: I am building a Laravel 8 api. I'm trying to set up a show route for /api/access-type/{access_type}. I want to change the {access_type} to be {id}
This is the route definition:
Route::middleware(['auth:api'])->group(function () {

    /////////// not allowed to use these. Creating/deleting these resources would require code changes
    Route::apiResource(
        \App\Http\Controllers\AccessTypeController::$uri,
        'AccessTypeController'
    )->only(['index', 'show'])->parameters(['access_type' => 'id']);
});

When I look at the listed routes I can see that the route hasn't changed:
GET|HEAD | api/access-types/{access_type} | access-types.show | App\Http\Controllers\AccessTypeController@show | Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful | Illuminate\Routing\Middleware\ThrottleRequests:api | Illuminate\Routing\Middleware\SubstituteBindings | App\Http\Middleware\Authenticate:api

If I use postman to visit /api/access-types/3 I can see that there is no $request->id variable, but there is a $request->access_type variable, so the overwrite isn't working. What am I doing wrong? This should work according to: docs
Comment: Could you try `['access_types' => 'id']`
Comment: Hi @Remul, no luck with that
Answer: I fixed it with the following:
Route::apiResource(
    \App\Http\Controllers\AccessTypeController::$uri,
    'AccessTypeController'
)->parameters(['access-types' => 'id']);

The parameter had to match the uri that I was setting it up for. I suppose this is so you can group multiple different resource routes into one.
Answer: I fixed it on laravel version 10 with the following:
use App\Http\Controllers\OrderController;

Route::apiResource("orders", OrderController::class)
   ->parameters(['orders' => 'order_number'])
    ->only(['show','store','update']);


Getting a memory leak when signing aChar in C++?

Question: I am learning C++. I am having a problem where I am allocating memory without the new keyword. The memory leak starts from UserInputCharArray[size - 1] = aChar. I am assigning a character to a memory location which is not allocated using the new keyword.
Can anyone help me solve this issue to allocate memory using the new keyword?
Here is an image when I run:

Here is my code:
    #include <iostream>

using namespace std;

// Creating a function for high frequency letters by passing in our vowels and
// a boolean for moving from lower-case vowels to upper-case vowels.
void highestFreq(int a, int e, int i, int o, int u, bool isLow) {

    // Declaring variables.
    int maximumCount = 0;
    char mainChar;

    // Creating an array of five for the vowels.
    int arr[5];

    arr[0] = a;
    arr[1] = e;
    arr[2] = i;
    arr[3] = o;
    arr[4] = u;

    // Set counter to zero.
    int counter = 0;

    // Looping through the vowels starting with value 1 -> 5.
    for (int x = 1; x < 5; x++) {

        // Count when array is less than
        if (arr[counter] < arr[x])

            counter = x;
    }

    // Looping through the vowels starting with value 0 -> 5
    for (int x = 0; x < 5; x++) {

        // count plus one.
        if (arr[counter] == arr[x])

            maximumCount += 1;

    }

    // Checking with the vowels.
    if (counter == 0)

        mainChar = 'a';

    else if (counter == 1)

        mainChar = 'e';

    else if (counter == 2)

        mainChar = 'i';

    else if (counter == 3)

        mainChar = 'o';

    else if (counter == 4)

        mainChar = 'u';

    // Moving from lower case letter to upper case letter.
    if (!isLow)

     // Conversion happening here from lower-case to upper-case letters.
       mainChar = mainChar - 'a' + 'A';

    // If there are multiple high frequency letters then a message needs to be passed in there.
    if (maximumCount > 1) {

        // checking to see if there are no lower case vowels .
        if (isLow)

            // Display - if there is no lower case vowels or there is no
            // upper case vowels.
            cout << "There are no lower ";

        else

            // Otherwise - display there are no upper case vowels
            cout << "There are no upper ";
            cout << "case vowels" << "\n";

    }

    else {

        // Otherwise - display the highest frequency letters.
        cout << "The highest frequency ";

        // Checking to see if there is any high frequency letters.
        if (isLow)

            // Displaying lower case vowels
            cout << "lower ";

        else

            // Displaying upper case vowels
            cout << "upper ";

            // Display how many high frequency vowels are their.
             cout << "case vowel is " << mainChar << " with a frequency of " << arr[counter] << "\n";

    }

}

int main() {

    // A char is being used -  for the user to still continue with the program.
    char userInputProceed = 'y';

   // Looping begin for user to continue.
    while (userInputProceed == 'Y' || userInputProceed == 'y') {

        // Declaration for the lower-case and upper-case vowels.
        int low_a, low_e, low_i, low_o, low_u;
        int high_A, high_E, high_I, high_O, high_U;

        // Initializing the count of lower-case and upper-case vowels.
        low_a = low_e = low_i = low_o = low_u = 0;
        high_A = high_E = high_I = high_O = high_U = 0;

        // Setting a size starting from one.
        int size = 1;

        // Declaring a variable of type char.
        char aChar;

        // Declaring a size to be using the new operator.
        char *UserInputCharArray = new char[size];

        // Prompt the user to enter a string.
        cout << "Enter a string: ";

        // Capturing userInput, one char at a time.
        aChar = cin.get();

        // A loop that will be taking values from the input stream and it will
        // count the size of input.  \n
        while (aChar != 10) {

            // Count size of input.
            UserInputCharArray[size - 1] = aChar;

            // Getting each size and add one.
            size += 1;

            // Then get the char one at a time - once more.
            aChar = cin.get();

        }

        // The loop process of the vowels.
        for (int x = 0; x < size; x++) {

            aChar = *(UserInputCharArray + x);

            if (aChar - 'a' == 0)

                low_a += 1;

            else if (aChar - 'e' == 0)

                low_e += 1;

            else if (aChar - 'i' == 0)

                low_i += 1;

            else if (aChar - 'o' == 0)

                low_o += 1;

            else if (aChar - 'u' == 0)

                low_u += 1;

            else if (aChar - 'A' == 0)

                high_A += 1;

            else if (aChar - 'E' == 0)

                high_E += 1;

            else if (aChar - 'I' == 0)

               high_I += 1;

            else if (aChar - 'O' == 0)

                high_O += 1;

            else if (aChar - 'U' == 0)

                high_U += 1;

        }

        // Displaying lower-case vowels with their frequency and display - following with
        // if the count of any vowel is zero then it will not be displayed.
        if (low_a > 0 || low_e > 0 || low_i > 0 || low_o > 0 || low_u > 0) {

            cout << "The lower-case vowels which are present are: ";

            if (low_a > 0)

                cout << "a (" << low_a << ")";

            if (low_e > 0)

                cout << "e (" << low_e << ")";

            if (low_i > 0)

                cout << "i (" << low_i << ")";

            if (low_o > 0)

                cout << "o (" << low_o << ")";

            if (low_u > 0)

                cout << "u (" << low_u << ")";

            cout << endl;

        }

        // Displaying upper case vowels with their frequency and display - following with
        // if the count of any vowel is zero then it will not be displayed.
        if (high_A > 0 || high_E > 0 || high_I > 0 || high_O > 0 || high_U > 0) {

            cout << "The upper-case vowels which are present are: ";

            if (high_A > 0)

                cout << "A (" << high_A << ")";

            if (high_E > 0)

                cout << "E (" << high_E << ")";

            if (high_I > 0)

                cout << "I (" << high_I << ")";

            if (high_O > 0)

                cout << "O (" << high_O << ")";

            if (high_U > 0)

                cout << "U (" << high_U << ")";

            cout << endl;

        }

        // Calling out the high frequency letter function.
        highestFreq(low_a, low_e, low_i, low_o, low_u, true);
        highestFreq(high_A, high_E, high_I, high_O, high_U, false);

        // Using the delete operator.
        delete[] UserInputCharArray;

        // Waiting for the user input if they want to continue with the program.
        cout << "To continue enter y or Y, anything else will quit the program" << endl;

        // Getting the user input to continue with the program.
        cin >> userInputProceed;

        // Wait for userInput until he/she quits.
        cin.get();

    }

    return 0;

}

Updated Code
    #include <iostream>
#include <string>

using namespace std;

// ----- REFACTORED MY CODE.  ------

// Returning a lower case vowels.
char LowVowel(int x) {

    switch(x) {
        case 0:
            return 'a';
            break;
        case 1:
            return 'e';
            break;
        case 2:
            return 'i';
            break;
        case 3:
            return 'o';
            break;
        case 4:
            return 'u';
            break;

    }
}

// Returning a upper case vowels.
char UpperVowel(int x) {

    switch (x) {
        case 0:
            return 'A';
            break;

        case 1:
            return 'E';
            break;
        case 2:
            return 'I';
            break;
        case 3:
            return 'O';
            break;
        case 4:
            return 'U';
            break;
   }

}
// Initializing the array to be used for upper and lower cases frequency.

void init(int arr[]) {
    for (int x = 0; x < 5; x++) {
        arr[x] = 0;
    }
}

int main() {

    // Declaring a variable of type char
    char aChar;

    // Allocation of memory to a character pointer as per the size of
    // the entered input.
    char *cPointer = new char;

    // Store an array for the frequency of lower and upper vowels.
    int arr[5];

    // counter and maximum to be stored for our maximum frequency.
    int counter = 0, maximum;

    // Prompting the user to enter a string.
    cout << "Enter a string: ";

    // Capturing userInput.
    aChar = cin.get();

    while (aChar != '\n') {

        // increment counter.
        counter++;

        // then if enter key is pressed - stop entering data.
        if (aChar == '\n')
            break;

        // Storing the accepted char inside the pointer.
        *(cPointer + counter) = aChar;

        // Increase the counter.
        aChar = cin.get();

    }

    // Initializing the arr array
    init(arr);

    // Looping until the end of inputted information.
    for (int x = 0; x < counter; x++) {

        // Checking the lower case vowels
        // and even increase the counter

        if (*(cPointer + x) == 'a')
            arr[0]++;
        else if (*(cPointer + x) == 'e')
            arr[1]++;
        else if (*(cPointer + x) == 'i')
            arr[2]++;
        else if (*(cPointer + x) == 'o')
            arr[3]++;
        else if (*(cPointer + x) == 'u')
            arr[4]++;
    }

    // Display lower case vowels results.
    cout << "The lower-case vowels which are present are: \n ";

    // Looping..
    for (int x = 0;  x < 5; x++) {

        // find the maximum frequency.
        maximum = arr[x];
        if (arr[x] > maximum)
            maximum = x;

        // then if the frequency value not zero then
        // display.
        if (arr[x] != 0) {
           cout << LowVowel(x)
            << " ( " << arr[x] << " )";
        }
    }
    // Display lower case vowels.
    cout << "Lower case vowel " << LowVowel(maximum)
    << " which appears most frequently = " << arr[maximum];

    // init the arr array .
    init(arr);

    // looping once again for the entered info.
    for (int x = 0; x < counter; x++) {

        // checking the upper case vowels
        // and increasing the counter once again.
        if (*(cPointer + x) == 'A')

            arr[0]++;

        else if (*(cPointer + x) == 'E')
            arr[1]++;

        else if (*(cPointer + x) == 'I')

            arr[2]++;

        else if (*(cPointer + x) == 'O')
            arr[3]++;

        else if (*(cPointer + x) == 'U')
            arr[4]++;
    }

    // Display upper case vowels.
    cout << "Upper case vowels and its frequency" << endl;

    // looping
    for (int x = 0; x < 5; x++) {

        // finding the maximum freq.
        maximum = arr[x];
        if (arr[x] > maximum)
            maximum = x;

        // if the frequency value is not zero then display.
        if (arr[x] != 0) {

            cout << "\n Vowel " << UpperVowel(x) << " occurred " << arr[x] << " times";

        }
     }

      cout << "Upper case vowel " << UpperVowel(maximum) << " which appears most frequently = " << arr[maximum];

}

Comment: Welcome to Stack Overflow! Please [edit] your code to reduce it to a [mcve] of your problem.  Your current code includes much that is peripheral to your problem - a minimal sample normally looks similar to a good unit test: only performing one task, with input values specified for reproducibility.
Answer:
I am assigning a character to a memory location which I am not even
  allocated memory using the 'new' keyword.

Actually, you have allocated memory for that location... Specifically, you declare and allocate 1-char of data with:
int size = 1;
char *UserInputCharArray = new char[size];

So the pointer UserInputCharArray points to a valid block of memory of size 1. The value at that memory address can be accessed by dereferencing the pointer with either:
*UserInputCharArray;

or
UserInputCharArray[0];  (or UserInputCharArray[size-1] as you used)

(the [] operator acts as a dereference.)
Both are equivalent. However, when using [], you are limited to the single index 0. Anything more (e.g. 1) would invoke Undefined Behavior as an attempt to access memory outside the bounds of the block you allocated. (as you do in your loop beginning when size = 2)
Why Not Use string?
While you are free to manage the storage needs for UserInputCharArray your self with new and delete, you are far better served using the features of C++ (namely the string handling provides by #include <string>) that will provide automatic memory management for UserInputCharArray, e.g. you can #include <string> and change:
char *UserInputCharArray = new char[size];

to
string UserInputCharArray;

and then:
UserInputCharArray[size - 1] = aChar;

to
UserInputCharArray.push_back(aChar);

The memory will then also be freed when UserInputCharArray goes out of scope.
Note, you have additional logic errors with your code.
Comment: Thank you for your answer @David .. I will try your snippet soon. I am working on a refactor version of my code,  I will post it tonight and let me know if that will work. Thank you!
Comment: Also note, you may not immediately crash when you access `UserInputCharArray[1];`, etc., because `new` will allocate a block of memory that is properly aligned and may contain more memory than just `1` char (though you cannot 'legally' use any of it) Why not use `string` instead of `char *` and let the container manage memory for you?
Comment: So, should I change my size to `size = 2`?  Please show me snippet prior  to my code above. thank you!
Comment: You should change your size to the maximum you anticipate `size += 1;` may reach and add a limit to your loop to protect your memory bounds, e.g. `while (size < MAXSIZE && aChar != 10) { ... }`
Comment: Better `#include ` and change `char *UserInputCharArray = new char[size];` to `string UserInputCharArray;` and then change `UserInputCharArray[size - 1] = aChar;` to `UserInputCharArray.push_back(aChar);`. `string` will automatically increase the size of `UserInputCharArray` as needed. (and will `free` it automatically when it goes out of scope). Otherwise you might as well write the code in C `:)`
Comment: In the comments section it's kind of hard to read.. Please update your answer above. Thank you :) .
Comment: OK, also go back through your logic, the `"Looping through the vowels starting with value"` loops make no sense.
Comment: You want to chat using stackoverflow ?  - So i can show you my refactored code
Comment: Sure, I'll have to figure out how to get there and open a channel for us. Damn, they keep updating these pages and now I don't have a simple "chat" button anymore. You can 'edit' your question and **add** your new code at the **end** of your current answer (don't delete your original code or the answers and comments will no longer make sense)
Comment: When clicking on "Add comment" in here you will see: "Please avoid extended discussions in comments. Would you like to automatically move this discussion to chat?" Just click on "automatically move this discussion to chat"
Comment: Not for me, for whatever reason, all I get is another empty comment box -- I don't know why. I've used this site for 4 years and there has always been exactly what you describe. I think the problem is you don't have enough rep yet. Let me add to your rep and then we will see of chat is available again. (No joy -- I just get another comment box `:(`) Why don't you initiate the chat and I'll see if I get the invite. (I don't even see the widget that shows people currently chatting any more -- really strange)
Comment: To create a new room to chat: Please follow this instructions: There is a link to chat in the footer of every page. The link also appears in the Stack Exchange site switcher on the upper right corner of every page. Click one of those links, and then click the "create a new room" button at the bottom of the Rooms page.
Comment: There is a definite problem. Here is what I see [Screen Shot of My Browser Window Showing Footer](http://paste.opensuse.org/25226461). Looks like I'll have to post to Meta to find out what the problem is. Do you get a link? If I'm not seeing anything, then it must be a reputation < 20 issue. You should qualify now, but I can't explain the lack of an option to chat (I've done it many many times -- there is just no widget there now)
Comment: check my updated code please. Also, keep in mind I am using infinite loop but I want to make a good habit to NOT use global variables
,labels or go-to statements
infinite loops, examples include:
for(;;)
while(1)
while(true)
do{//code}while(1);
and even no break statements to exit loops.
Comment: ByTheWay: Your code above gave me some errors with: `candidate template ignored: could not match 'const _CharT *' against 'int'
operator+(const basic_string<_CharT, _Traits, _Allocator>& __lhs, const _CharT* __rhs)
error: cannot delete expression of type 'std::__1::string' (aka 'basic_string, allocator >')
       delete[] UserInputCharArray;`
Comment: Everything O-K, @David?
Comment: Yes, sorry, had a phone call. Your problem is coming from the logic being somewhat convoluted. What you should do is think about making classification easy -- using a frequency array for each lower and upper case vowels. Then simply determine which vowel of each case occurred the most frequently and the index (which you can relate to the character) to be able to identify what occurred the most frequent and how many times it occurred. Here is a link to get you going (note: it will choose the 1st vowel if there is a tie for most frequent) [example](http://paste.opensuse.org/86876722)
Comment: Sure. Last advise I would have for you would be "don't try and code it all at once". For example, instead of trying to code both upper/lower case handling at once, instead, take one case and implement that first. Once you have it all working, then you can extend it to the other case -- but make sure you have the simple case working first -- then build outwards. That applies no matter what you are trying to model. The smaller the bites, the less chance there is of choking. Good luck with your coding. After sufficient time, don't forget to select an answer to your question.


Why do some consider it against the spirit of cricket to mankad a batsmen?

Question: So recently, there has been this incident where a batsmen was out due to a mankad (http://www.news.com.au/sport/cricket/cricket-greats-slam-mankad-dismissal-at-u19-cricket-world-cup/news-story/e4134bb470e2482f0a17dc4dedba6c1f)
Having read what it actually is, I don't really understand why it's against the spirit of the game. I mean, it's a legitimate dismissal within the rules of cricket and it's fairly easy to avoid being dismissed this way by just not trying to leaving the crease to get a headstart before the ball is bowled.
It seems to be the cricket version of getting out while trying to steal a base (in baseball). Why is there so much outrage about it?
Comment: This is a very fair question, but also one that I think will be very difficult to answer without allowing personal opinion to intrude. I've therefore edited the question to make it more neutral and open-ended. I'd also like to make a plea for answers to **explain why the controversy exists, rather than whether it should exist**.
Answer: It is considered to be ungentelmaly conduct and sharp practice which is against the spirit of cricket.
There are different types of mankad in my opinion as an umpire.   The one in the u19 world Cup the bowler was never going to deliver the ball and no warning was given.   Also the batsmen was not stealing a run.
There have been other cases including Jos Butler over the summer where the batsmen was 3 or 4 ft down and could be argued to be stealing  run.   He was also warned.
As an umpire what I have discussed with my colleagues is that if the batsmen is approaching the 4ft marker he is stealing a run and I will warn him and should be be run out I will have no issue with the dismissal.   However in the situation in the u19 world Cup I would be with my colleague having a chat with the fielding captain as to the appeal and whether he wants it to stand.
I believe there may be changes coming in the next law rewrite to deal with this.
Ben
Comment: For what it's worth, the umpire in the U19 WC did ask the fielding captain about whether the appeal should stand.


Problemas com a Midaslib

Question: Estou tentando executar uma aplicação em Delphi, porém toda vez que tento compilar aparece um erro "Unit 'Midaslib' not found", existe alguma forma de colocar essa biblioteca manualmente?
Verifiquei que antigamente utilizava-se o midas.dll.
Answer: Na classe principal, declare na unit o MidasLib não vai mais alertar sobre a dll.
Comment: Eu estou declarando na unit e mesmo assim aparece o erro.
Comment: @FlávioNavesJr tente colocar o midas.dll na pasta do projeto e na pasta System32 ou SysWOW64
Comment: @FlávioNavesJr Se está dando erro na hora que você declara o MidasLib na unit, deve ser pelo motivo que nosso amigo Andrey mencionou, está faltando declarar o MidasLib na biblioteca
Answer: Provavelmente o diretório onde se encontra o arquivo MidasLib.pas não está na Library do Delphi.
Geralmente é: C:\Program Files (x86)\Embarcadero\Studio\15.0\source\data\dsnap
Deve funcionar a partir do Delphi 6.
Comment: Na verdade o nome do projeto não é midaslib, aparentemente Midaslib é uma biblioteca e por isso não estou conseguindo, pois ela não consta nessa versão do Delphi, algo assim.Estou utilizando a versão Tókio 10.2.
Comment: Sei que o nome do seu projeto não é *MidasLib*. *MidasLib* realmente é apenas uma biblioteca, e como mencionei na resposta, o caminho onde está essa biblioteca é que não deve estar adicionado na **Library** do Delphi. Podes conferir?
Answer: Mas é  no seu computador ou num computador cliente?
O que normalmente se faz é ter que colocar o
  uses
     midas,
     midaslib,

no codigo do projecto (ficheiro .dpr do seu projecto). Pode lá chegar ao clicar no nome do projecto e fazer View Source.

Problemas com a Midaslib


Two Sample Independent Test for Proportions (z test or t test)

Question: Context:
I have two independent samples that I want to compare for equality through an AB test.
The metric being evaluated is binary: user clicks or not (proportions).
Question:

I keep reading that z test are not to be used based on the assumptions that it makes and that t tests are recommended instead. I haven't seen any formula for two independent samples t test for proportions, but only for means. Does it exist?

Is it even true that two sample z test for proportion is not recommended?
Comment: You're fine to use a z test.   The two sample z test for a difference in proportions is based off the asymptotic sampling distribution for the binary proportions. In the limit, the sampling distributions are normal, with variance which need not be independently estimated from the mean. You're absolutely fine to use the z test in this scenario.
Answer: There are several nearly equivalent tests to compare
two binomial proportions. The parameter of interest is
the difference between the two population proportions
$p_1 - p_2,$ which is usually estimated by the difference
between the corresponding two sample proportions
$\hat p_1 - \hat p_2,$ where $\hat p_i = x_i/n_i, i=1,2.$ with numbers $x_i$ of successes in $n_i$ trials.
Differences among the tests center on how or whether
to use a normal approximation and on how to estimate
the standard deviation of $\hat p_1 - \hat p_2,$ often
called the (estimated) standard error. Roughly speaking,

One method is to assume equality of $p_1$ and $p_2,$ estimating $p = p_1 = p_2$ as $\hat p = \frac{x_1+x_2}{n_1+n_2}$ and $\widehat{\mathrm{Var}}(\hat p) = (n_1+n_2)\hat p(1-\hat p).$

An alternative method is to estimate the variances of the $\hat p_i$ separately and add.

Moreover, especially for small $n_i,$ various tests use
different continuity corrections when invoking normal approximations, and other tests use no continuity correction.
Fortunately, these variations in method often make very
little difference in final results. So it is more important
to remember that the variations exist (so as not to be puzzles when various analyses do not match exactly) than to worry
about which to use.
In R, the procedure prop.test uses a test statistic with an approximate chi-squared distribution. Suppose that there are $n_1 = 100$ subjects in the A group with $x_1 = 83$ successes
and, independently $n_2 = 88$ subjects in the B group with
$x_2 = 92$ successes, so that $\hat p_1  = 0.83, \hat p_2 \approx 0.9565.$ These two sample proportions differ
significantly at the $1\%$ level because the P-value
of the test is smaller than $0.01.$
prop.test(c(83,88), c(100,92), cor=F)

        2-sample test for equality of proportions
        without continuity correction

data:  c(83, 88) out of c(100, 92)
X-squared = 7.8742, df = 1, p-value = 0.005015
alternative hypothesis: two.sided
95 percent confidence interval:
 -0.21111962 -0.04192386
sample estimates:
   prop 1    prop 2
0.8300000 0.9565217

Notice that this test is the same as a chi-squared test
of homogeneity on the $2 \times 2$ table there columns
are for A and B, rows are for Success and Failure.
(Particularly with sample sizes around 100 or larger,
I choose to use the argument cor=F to suppress the
continuity correction.)
TAB = rbind(c(83,88), c(17,4));  TAB

     chisq.test(TAB, cor=F)
         [,1] [,2]
    [1,]   83   88
    [2,]   17    4

        Pearson's Chi-squared test

data:  TAB
X-squared = 7.8742, df = 1, p-value = 0.005015

The P-value is exactly the same as for a two-tailed test prop.test(as above), but no confidence interval or
estimates $\hat p_i$ are given.
Notes: (1) If some of the counts in TAB are very small (thus, triggering a warning message), it is
best to use chisq.test with parameter sim=T to get
a simulated P-value that may be more useful than the one from the
traditional chi-squared test statistic.
(2) Several other Answers on this site discuss
tests of binomial proportions. You may find additional example and discussions alternative tests there. Also, uses of alternative tests can be
found online.
Comment: Nice answer (+1) It shouldn't really alter the results much, but shouldn't the second element in the 'success count' vector be 91?
Comment: After a browser crash I changed the numbers slightly, but some of the old ones reappeared from history file (I guess). Hope I've fixed it now. Thanks.
Comment: You mentioned two alternatives. Can you please specify the formulas of the two alternatives?


Question based on $\triangle$ and Arithmetic progression.

Question:
If $a,b,c$ are the sides of a $\triangle ABC$ which are in Arithmetic progression. Then Range of $\displaystyle \frac{b}{c}$

$\bf{My\; Try::}$ In a Triangle Given that sides $a,b,c$ are in Arithmetic Progression.
So $2b=a+c\Rightarrow a=2b-c$
and In Triangle, $\displaystyle a+b>c\Rightarrow 2b-c+b>c\Rightarrow 3b>2c\Rightarrow \frac{b}{c}>\frac{2}{3}$
Now how can i calculate upper limit, Help required, Thanks
Comment: The upper limit is surely $1$, if $a \leq b \leq c$.
Answer: Let $s:=\frac bc,t:=\frac ac$.
From $2b=a+c$, we have
$$2s=t+1\iff t=2s-1\tag1$$
From $$a+b\gt c,\quad b+c\gt a,\quad c+a\gt b$$
we have
$$t+s\gt 1,\quad s+1\gt t,\quad 1+t\gt s\tag2$$
From $(1)(2)$,
$$2s-1+s\gt 1,\quad s+1\gt 2s-1,\quad 1+2s-1\gt s,$$
to have
$$\color{red}{\frac 23\lt \frac bc\lt 2}$$


MSBuild zip directories task without any external dependencies (no MSBuildCommunityTasks)

Question: I have attempted to find a way to zip a build up using MSBuild without using MSBuildCommunityTasks. I did manage to find some code online but it seems to take all the files, even ones in directories and put it in one file (no directories).
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

<UsingTask TaskName="Zip" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
<ParameterGroup>
  <InputFileNames ParameterType="Microsoft.Build.Framework.ITaskItem[]" Required="true" />
  <OutputFileName ParameterType="System.String" Required="true" />
  <OverwriteExistingFile ParameterType="System.Boolean" Required="false" />
</ParameterGroup>
<Task>
  <Reference Include="System.IO.Compression" />
  <Using Namespace="System.IO.Compression" />

  <![CDATA[
    const int BufferSize = 64 * 1024;

    var buffer = new byte[BufferSize];
    var fileMode = OverwriteExistingFile ? FileMode.Create : FileMode.CreateNew;

    using (var outputFileStream = new FileStream(OutputFileName, fileMode))
    {
      using (var archive = new ZipArchive(outputFileStream, ZipArchiveMode.Create))
      {
        foreach (var inputFileName in InputFileNames.Select(f => f.ItemSpec))
        {
          var archiveEntry = archive.CreateEntry(Path.GetFileName(inputFileName));

          using (var fs = new FileStream(inputFileName, FileMode.Open))
          {
            using (var zipStream = archiveEntry.Open())
            {
              int bytesRead = -1;
              while ((bytesRead = fs.Read(buffer, 0, BufferSize)) > 0)
              {
                zipStream.Write(buffer, 0, bytesRead);
              }
            }
          }
        }
      }
    }
  ]]>

</Task>
</UsingTask>
</Project>

How can i get this code to zip up my folder and keep the directories intact?
Answer: <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <UsingTask TaskName="Zip" TaskFactory="CodeTaskFactory" AssemblyName="Microsoft.Build.Tasks.v12.0">
    <ParameterGroup>
      <Directory ParameterType="System.String" Required="true" />
    </ParameterGroup>
    <Task>
      <Reference Include="System.IO.Compression.FileSystem" />
      System.IO.Compression.ZipFile.CreateFromDirectory(Directory, Directory + ".zip");
    </Task>
  </UsingTask>

  <Target Name="Foo">
    <Zip Directory="C:\Users\Ilya.Kozhevnikov\Dropbox\Foo" />
  </Target>
</Project>

Answer: There are many things you could do with directories of files and directories in the archive. As a simplifying assumption, let's pick a base directory and require that all files are below it. In the archive, the entries will be the parts of the file paths up to but not including the base directory name.
So, add a parameter:
<BaseDirectory ParameterType="System.String" Required="true" />

Change the archive path for the entry:
var archiveEntry = archive.CreateEntry(
    new Uri(Path.GetFullPath(BaseDirectory) + path.DirectorySeparatorChar)
        .MakeRelativeUri(new Uri(Path.GetFullPath(inputFileName))).ToString());

And, as a bonus, fix the too-strict file access sharing:
using (var fs = new FileStream(inputFileName, FileMode.Open, FileAccess.Read, FileShare.Read))

Comment: This didn't seem to work. Basically all i want it to do is zip up a file and leave its hierarchy intact. All the folders and files should be in the same structure as the original file.


log4j: Could not find root logger information. Is this OK?

Question: While loading log4j from within Eclipse plugin (in forced programmatic mode) it says it can't find root logger information, while it presents.
The SSCCE code is below. It is based on simplest available headless RCP application sample:
package try_eclipsepluginlog4j_01;

import java.io.IOException;
import java.net.URL;

import org.apache.log4j.PropertyConfigurator;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Platform;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.osgi.framework.Bundle;

/**
 * This class controls all aspects of the application's execution
 */
public class Application implements IApplication {

    static
    {
        try {
            Bundle bundle = Platform.getBundle("Try_EclipsePluginLog4j_01");
            URL config1 = bundle.getEntry("/conf/log4j.sample.xml");
            URL config2 = FileLocator.resolve(config1);
            PropertyConfigurator.configure(config2);

            org.apache.log4j.Logger log4j = org.apache.log4j.Logger.getLogger(Application.class);

            log4j.info("log4j is here");
        }
        catch(IOException e) {
        }
    }

    // private static final Logger log = Logger.getLogger(Application.class);

    /* (non-Javadoc)
     * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext)
     */
    public Object start(IApplicationContext context) throws Exception {
        System.out.println("Hello RCP World!");
        return IApplication.EXIT_OK;
    }

    /* (non-Javadoc)
     * @see org.eclipse.equinox.app.IApplication#stop()
     */
    public void stop() {
        // nothing to do
    }
}

Configuration file is follows:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
  <appender name="console" class="org.apache.log4j.ConsoleAppender">
    <param name="Target" value="System.out"/>
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
    </layout>
  </appender>

  <root>
    <priority value ="debug" />
    <appender-ref ref="console" />
  </root>

</log4j:configuration>

Output follows:
log4j: Trying to find [log4j.xml] using context classloader org.eclipse.core.runtime.internal.adaptor.ContextFinder@58242ff4.
log4j: Trying to find [log4j.xml] using org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader@547248ad[Try_EclipsePluginLog4j_01:1.0.0.qualifier(id=13)] class loader.
log4j: Trying to find [log4j.xml] using ClassLoader.getSystemResource().
log4j: Trying to find [log4j.properties] using context classloader org.eclipse.core.runtime.internal.adaptor.ContextFinder@58242ff4.
log4j: Trying to find [log4j.properties] using org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader@547248ad[Try_EclipsePluginLog4j_01:1.0.0.qualifier(id=13)] class loader.
log4j: Trying to find [log4j.properties] using ClassLoader.getSystemResource().
log4j: Could not find resource: [null].
log4j: Reading configuration from URL file:/D:/Users/Dims/Design/eclipse-rcp-kepler/Try_EclipsePluginLog4j_01/conf/log4j.sample.xml
log4j: Could not find root logger information. Is this OK?
log4j: Finished configuring.
log4j:WARN No appenders could be found for logger (try_eclipsepluginlog4j_01.Application).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Hello RCP World!

Project structure is follows:
Comment: There's a catch block swallowing an `IOException` in the static initializer. Are you able to add `e.printStackTrace()` here - or check with the debugger that the code is not falling into this catch block?
Comment: No, it is not falling there.
Answer: Since you're using an XML file and not a properties file, try using the DOMConfigurator rather than the PropertyConfigurator.
DOMConfigurator.configure(config2);


Method of Undetermined Coefficients: Solving for a particular solution

Question: Solve for $2y''+3y'+y=t$ using method of undetermined coefficients. So I let $Y=At+b$ to solve for the particular solution. After substituting the first and second derivative into $2y''+3y'+y=t$, I get $3A+At+B= t,$ -> $ A(3+t)+B=t$. But I don't know how to proceed from here because computing $3+t=1$ gives $t=-2$ whereas the solution is $Y=t-3$. Can someone help correct my mistake?
Comment: Why are you taking $3+t=1$?
Answer: I believe the mistake you're suspecting was when you said you got $3A + At+B=t$. When we let $y=At+B$ (which also means $y'=A$ and $y''=0$), we should have
\begin{align}
2y''+3y'+y=t &\implies 2(0)+3A+(At+B)=t\\
&\implies At+(3A+B)=t
\end{align}
When we equate coefficients, I got $A=1$ (from $At=t$) and $B=-3$ (from $3A+B=0$).
Comment: For $y=At+B$, wouldn't we have $y'=t$ and $y''=0$ or am I missing something?
Comment: You're right; I made a mistake. But I edited and hope I fixed my answer.


Check whether a field value exists in a custom table when a webform is submitted

Question: I created a custom table named "test_customerid" for the use of select queries from the drupal database. The fields are naid (for national id), name and surname.
My aim is to display an error message if the user attempts to insert an National ID which is already present in the table. Otherwise, all information are added to the table "test_customerid". This must occur when a webform is submitted.
Here are my codes that I included in the webform.module of my drupal project (inside function webform_webform_submission_insert($node, $submission)):
$accessnode=$node->nid;
if($accessnode==6)
{
    $dataSub=$submission->data[1]['value'];//submitted value of National ID

    $result=db_query("SELECT * FROM {test_customerid} WHERE naid = :naid",array(':naid'=>$dataSub));
    if(!(empty($result)))//I also tried "if($result)"
    {
        drupal_set_message(t('The NID already exists.'), 'error');
    }
    else
    {

        db_insert('test_customerid')
        ->fields(array(

        'naid' => $submission->data[1]['value'],
        'name' => $submission->data[2]['value'],
        'surname' => $submission->data[3]['value'],
        ))
        ->execute();
    }

The problem is:
It displays the error message even if the user inputs a new National ID. I can't add new information in the table.
I even tried to convert the data into strings by using these before placing the variable into the insert query but it gives me the same error message:

$dataconvert=implode(",",$dataSub);
$dataconvert=serialize($dataSub);

I want that the query to take the National ID value from the webform and check out if it exists in the table. Can you someone help me with this please?
Answer: Just replace
$result=db_query("SELECT * FROM {test_customerid} WHERE naid = :naid",array(':naid'=>$dataSub));

with
$result=db_query("SELECT * FROM {test_customerid} WHERE naid = :naid",array(':naid'=>$dataSub))->fetchAll();

and try, hope it will work
Answer: It should be like
$accessnode=$node->nid;
if($accessnode==6) {
  $dataSub=$submission->data[1][0];//submitted value of National ID

  $result=db_query("SELECT * FROM {test_customerid} WHERE naid = :naid",array(':naid'=>$dataSub));
  if(!(empty($result))) {
    drupal_set_message(t('The NID already exists.'), 'error');
  }
  else {
    db_insert('test_customerid')
    ->fields(array(

    'naid' => $submission->data[1][0],
    'name' => $submission->data[2][0],
    'surname' => $submission->data[3][0],
    ))
    ->execute();
  }
}

$submission->data[1]['value'] does not exist in the $submission object. Change this to $submission->data[1][0] and it will start working.
Also you have to change
db_insert('test_customerid')
  ->fields(array(
    'naid' => $submission->data[1]['value'],
    'name' => $submission->data[2]['value'],
    'surname' => $submission->data[3]['value'],
))
->execute();

query as well.It should be
db_insert('test_customerid')
  ->fields(array(
    'naid' => $submission->data[1][0],
    'name' => $submission->data[2][0],
    'surname' => $submission->data[3][0],
))
->execute();

Hoping that this would solve the problem of yours.


Field template for display mode of referenced paragraph

Question: I have a custom field field_platform (referencing a the custom paragraph type platform) and a template for my field: field--field-platform.html.twig. Is there a way to override this for a specific display mode of the referenced paragraph type? I have a mode named cover_view for the custom paragraph type platform I want to override the field template for.
I found Field template for display mode but the template suggestion is for the display mode of the content, not the referenced paragraph.
Drupal 8.5.6, Paragraphs 8.x-1.3
Thanks in advance!
Answer: Implement hook_theme_suggestions_alter like in the other answer and you can find everything you need in the $variables.

The following snippet will add the template suggestion for the view mode of the referenced paragraphs. Note that this will probably only make sense as long as you use only one paragraph type OR all multiple paragraph types have the same view mode configured.
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYMODULE_theme_suggestions_field_alter(array &$suggestions, array $variables) {

  $element = $variables['element'];

  if ($element['#field_type'] == 'entity_reference_revisions') {

    foreach ($element as $key => $value) {
      if (is_numeric($key) && isset($value['#paragraph'])) {

        $paragraph = $value;
        $suggestions[] = 'field__' . $element['#field_name'] . '__paragraph__' . $paragraph['#view_mode'];
      }
    };
  }
}

Seems you can implement that from you theme's *.theme file as well.

I guess the same logic works for any entity (node etc.) reference as well.


adding custom styles/scripts to elementor widget

Question: I am currently struggling to inject a custom style to an existing elementor widget (no custom one).
Sure I could simply put the changes in a global .css but then I wouldn't profit from elementors dynamic component based includes.
I found some methods in the offical code reference but they doesn't seem to do what I want to achieve. For example elementor/editor/before_enqueue_styles which only affects the whole editor, same for frontend.
Answer: use the following for dynamic styles and scripts on a widget:
class ReplaceMeClassName extends \Elementor\Widget_Base {
    public function __construct( $data = [], $args = null ) {
        parent::__construct( $data, $args );

        /** Main Style **/
        $src= 'the_source_with_complete_url.min.css';
        $version=filemtime( 'the_source_with_complete_path.min.css');
        if(WP_DEBUG===true){
            /** style **/
            $src= 'the_source_with_complete_url.css';
            $version=filemtime('the_source_with_complete_path.css');
        }
        /** style **/
        wp_register_style( 'name_of_the_style', $src, /* depends */ array(), $version );

        /** Main Script **/
        $src= 'the_source_with_complete_url.min.js';
        $version=filemtime( 'the_source_with_complete_path.min.js');
        if(WP_DEBUG===true){
            /** Script **/
            $src= 'the_source_with_complete_url.js';
            $version=filemtime('the_source_with_complete_path.js');
        }
        /** Script **/
        wp_register_script( 'name_of_the_script', $src, /* depends */ array(), $version );
    }
    /**
     * Enqueue when widget is on page.
     */
    public function get_style_depends() {
        return array( 'name_of_the_style' );
    }
    /**
     * Enqueue scripts when widget is on page.
     */
    public function get_script_depends() {
        return array( 'name_of_the_script' );
    }
    /* ..... */


Fastest way to set all values of an array?

Question: I have a char [], and I want to set the value of every index to the same char value.
There is the obvious way to do it (iteration):
  char f = '+';
  char [] c = new char [50];
  for(int i = 0; i < c.length; i++){
      c[i] = f;
  }

But I was wondering if there's a way that I can utilize System.arraycopy or something equivalent that would bypass the need to iterate. Is there a way to do that?
EDIT :
From Arrays.java
public static void fill(char[] a, int fromIndex, int toIndex, char val) {
        rangeCheck(a.length, fromIndex, toIndex);
        for (int i = fromIndex; i < toIndex; i++)
            a[i] = val;
    }

This is exactly the same process, which shows that there might not be a better way to do this.
+1 to everyone who suggested fill anyway - you're all correct and thank you.
Comment: Yeah, I'm coding for Superman.
Comment: The version of the JDK code in your addendum shows a "swizzle" that is done in some versions of the JDK:  An external flag somewhere indicates that array bounds checking should be bypassed in the method, and then an explicit bounds check is added, outside the loop.  This provides a significant performance boost, since bounds checking is not only expensive in its own right, but it complicates other optimizations.
Comment: @Bombe it's for a custom password field, so I have to replace every `char` in the document with `'•'` on the fly - which means it has to be as responsive as possible. Might say why not set value for each index as you go? It's for using with `drawString`, so I can anti-alias the •'s text. `fill` seems to work well. :)
Comment: @paranoid-android, so you do have users that are able to type more than 1000 characters per second? I am impressed.
Comment: I think it is better to use 'fill' just because it is a standard method of built-in class and could be changed to more effective implementation by JVM at runtime. Even more i think it is bound to happen. Java doesn't support direct memory access by design, but that doesn't mean that generated code shouldn't support it too.
Answer: Try Arrays.fill(c, f) : Arrays javadoc
Comment: The source for Arrays.fill suggests that it just does a loop (plus a range check beforehand). Should benchmark to see if the JVM does something clever instead...
Comment: What if it is a two dimensional array?
Comment: While this is terse and works .. take a look at the next answer by @RossDrew : this is extremely slow vs an optimized approach.
Answer: As another option and for posterity I was looking into this recently and found a solution that allows a much shorter loop by handing some of the work off to the System class, which (if the JVM you're using is smart enough) can be turned into a memset operation:-
/*
 * initialize a smaller piece of the array and use the System.arraycopy
 * call to fill in the rest of the array in an expanding binary fashion
 */
public static void bytefill(byte[] array, byte value) {
  int len = array.length;

  if (len > 0){
    array[0] = value;
  }

  //Value of i will be [1, 2, 4, 8, 16, 32, ..., len]
  for (int i = 1; i < len; i += i) {
    System.arraycopy(array, 0, array, i, ((len - i) < i) ? (len - i) : i);
  }
}

This solution was taken from the IBM research paper "Java server performance: A case study of building efficient, scalable Jvms" by R. Dimpsey, R. Arora, K. Kuiper.
Simplified explanation
As the comment suggests, this sets index 0 of the destination array to your value then uses the System class to copy one object i.e. the object at index 0 to index 1 then those two objects (index 0 and 1) into 2 and 3, then those four objects (0,1,2 and 3) into 4,5,6 and 7 and so on...
Efficiency (at the point of writing)
In a quick run through, grabbing the System.nanoTime() before and after and calculating a duration I came up with:-

This method : 332,617 - 390,262 ('highest - lowest' from 10 tests)
Float[] n = new Float[array.length]; //Fill with null : 666,650
Setting via loop : 3,743,488 - 9,767,744  ('highest - lowest' from 10 tests)
Arrays.fill : 12,539,336

The JVM and JIT compilation
It should be noted that as the JVM and JIT evolves, this approach may well become obsolete as library and runtime optimisations could reach or even exceed these numbers simply using fill().
At the time of writing, this was the fastest option I had found.  It has been mentioned this might not be the case now but I have not checked.  This is the beauty and the curse of Java.
Comment: @RossDrew we removed the code from Apache POI - it turns out that in modern JVMs, Arrays.fill is optimised (http://psy-lob-saw.blogspot.com/2015/04/on-arraysfill-intrinsics-superword-and.html) - I used jmh to benchmark and found this to be case (Zulu 1.8.0_302 and 17.0.0 JVMs).
Comment: This shall be the accepted answer, Arrays.fill is too slow for large arrays when you are looking for speed. OP states "fastest way". This answer really helps
Comment: @timbo in that it's the same approach yes.  I posted my answer as the answer is minimal and links are dead.  I've posted a deeper explanation, link to source study including full reference name in case the link dies, explanation of it's performance at the time and why it is or will be obsolete to optimise Java in this way.  I felt that a more complete answer was necessary and judging by my upvotes, a welcome one.
Comment: @PJFanning I knew that would at least eventually be the case when I wrote this.  That's why I put that last part in, to reflect that massive benefit of Java; your code will just get faster.
Comment: Isn't this basically what Bill Tutt already posted?
Comment: @RossDrew - at some point in the past, someone has taken your code and committed it the Apache POI codebase - see https://bz.apache.org/bugzilla/show_bug.cgi?id=65796 - would it be possible to get your permission to reuse your code? Apologies for the inconvenience.
Answer: Use Arrays.fill
  char f = '+';
  char [] c = new char [50];
  Arrays.fill(c, f)

Answer: Java Programmer's FAQ Part B Sect 6 suggests:
public static void bytefill(byte[] array, byte value) {
    int len = array.length;
    if (len > 0)
    array[0] = value;
    for (int i = 1; i < len; i += i)
        System.arraycopy( array, 0, array, i,
            ((len - i) < i) ? (len - i) : i);
}

This essentially makes log2(array.length) calls to System.arraycopy which hopefully utilizes an optimized memcpy implementation.
However, is this technique still required on modern Java JITs such as the Oracle/Android JIT?
Comment: I found the tutorial but not the specific link - do you know where it could be?
Comment: There are links in my answer to more in depth discussion of this method @Karussell
Answer: System.arraycopy is my answer. Please let me know is there any better ways. Thx
private static long[] r1 = new long[64];
private static long[][] r2 = new long[64][64];

/**Proved:
 * {@link Arrays#fill(long[], long[])} makes r2 has 64 references to r1 - not the answer;
 * {@link Arrays#fill(long[], long)} sometimes slower than deep 2 looping.

 */
private static void testFillPerformance() {
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    System.out.println(sdf.format(new Date()));
    Arrays.fill(r1, 0l);

    long stamp0 = System.nanoTime();
    //      Arrays.fill(r2, 0l); -- exception
    long stamp1 = System.nanoTime();
    //      System.out.println(String.format("Arrays.fill takes %s nano-seconds.", stamp1 - stamp0));

    stamp0 = System.nanoTime();
    for (int i = 0; i < 64; i++) {
        for (int j = 0; j < 64; j++)
            r2[i][j] = 0l;
    }
    stamp1 = System.nanoTime();
    System.out.println(String.format("Arrays' 2-looping takes %s nano-seconds.", stamp1 - stamp0));

    stamp0 = System.nanoTime();
    for (int i = 0; i < 64; i++) {
        System.arraycopy(r1, 0, r2[i], 0, 64);
    }
    stamp1 = System.nanoTime();
    System.out.println(String.format("System.arraycopy looping takes %s nano-seconds.", stamp1 - stamp0));

    stamp0 = System.nanoTime();
    Arrays.fill(r2, r1);
    stamp1 = System.nanoTime();
    System.out.println(String.format("One round Arrays.fill takes %s nano-seconds.", stamp1 - stamp0));

    stamp0 = System.nanoTime();
    for (int i = 0; i < 64; i++)
        Arrays.fill(r2[i], 0l);
    stamp1 = System.nanoTime();
    System.out.println(String.format("Two rounds Arrays.fill takes %s nano-seconds.", stamp1 - stamp0));
}

12:33:18
Arrays' 2-looping takes 133536 nano-seconds.
System.arraycopy looping takes 22070 nano-seconds.
One round Arrays.fill takes 9777 nano-seconds.
Two rounds Arrays.fill takes 93028 nano-seconds.
12:33:38
Arrays' 2-looping takes 133816 nano-seconds.
System.arraycopy looping takes 22070 nano-seconds.
One round Arrays.fill takes 17042 nano-seconds.
Two rounds Arrays.fill takes 95263 nano-seconds.
12:33:51
Arrays' 2-looping takes 199187 nano-seconds.
System.arraycopy looping takes 44140 nano-seconds.
One round Arrays.fill takes 19555 nano-seconds.
Two rounds Arrays.fill takes 449219 nano-seconds.
12:34:16
Arrays' 2-looping takes 199467 nano-seconds.
System.arraycopy looping takes 42464 nano-seconds.
One round Arrays.fill takes 17600 nano-seconds.
Two rounds Arrays.fill takes 170971 nano-seconds.
12:34:26
Arrays' 2-looping takes 198907 nano-seconds.
System.arraycopy looping takes 24584 nano-seconds.
One round Arrays.fill takes 10616 nano-seconds.
Two rounds Arrays.fill takes 94426 nano-seconds.
Comment: Why did you pick System.arraycopy(...) when your logs state that Arrays.fill(...) was faster every run? Generally, it was massively faster!
Comment: For people reading this answer in case you miss odys's comment at the start of the method. One round Arrays.fill  actually is using Arrays.fill(Object[],Object) which wil fill the outer array with references to r1 (i.e. setting afterwards r2[i][j] = 42 will set r2[x][j] = 42 for all x), clearly not the intended behavior.
Answer: As of Java-8, there are four variants of the setAll method which sets all elements of the specified array, using a provided generator function to compute each element.
Of those four overloads only three of them accept an array of primitives declared as such:

setAll(double[] array, IntToDoubleFunction generator)

setAll(int[] array, IntUnaryOperator generator)

 setAll(long[] array, IntToLongFunction generator)

Examples of how to use the aforementioned methods:
// given an index, set the element at the specified index with the provided value
double [] doubles = new double[50];
Arrays.setAll(doubles, index -> 30D);

// given an index, set the element at the specified index with the provided value
int [] ints = new int[50];
Arrays.setAll(ints, index -> 60);

 // given an index, set the element at the specified index with the provided value
long [] longs = new long[50];
Arrays.setAll(longs, index -> 90L);

The function provided to the setAll method receives the element index and returns a value for that index.
you may be wondering how about characters array?
This is where the fourth overload of the setAll method comes into play. As there is no overload that consumes an array of character primitives, the only option we have is to change the declaration of our character array to a type Character[].
If changing the type of the array to Character is not appropriate then you can fall back to the Arrays.fill method.
Example of using the setAll method with Character[]:
// given an index, set the element at the specified index with the provided value
Character[] character = new Character[50];
Arrays.setAll(characters, index -> '+');

Although, it's simpler to use the Arrays.fill method rather than the setAll method to set a specific value.
The setAll method has the advantage that you can either set all the elements of the array to have the same value or generate an array of even numbers, odd numbers or any other formula:
e.g.
int[] evenNumbers = new int[10];
Arrays.setAll(evenNumbers, i -> i * 2);

There's also several overloads of the parallelSetAll method which is executed in parallel, although it's important to note that the function passed to the parallelSetAll method must be side-effect free.
Conclusion
If your goal is simply to set a specific value for each element of the array then using the Arrays.fill overloads would be the most appropriate option. However, if you want to be more flexible or generate elements on demand then using the Arrays.setAll or Arrays.parallelSetAll (when appropriate) would be the option to go for.
Comment: I found setall more performant when setting an array (size 500) to a default value than using fill by about 3x
Answer: I have a minor improvement on Ross Drew's answer.
For a small array, a simple loop is faster than the System.arraycopy approach, because of the overhead associated with setting up System.arraycopy.  Therefore, it's better to fill the first few bytes of the array using a simple loop, and only move to System.arraycopy when the filled array has a certain size.
The optimal size of the initial loop will be JVM specific and system specific of course.
private static final int SMALL = 16;

public static void arrayFill(byte[] array, byte value) {
  int len = array.length;
  int lenB = len < SMALL ? len : SMALL;

  for (int i = 0; i < lenB; i++) {
    array[i] = value;
  }

  for (int i = SMALL; i < len; i += i) {
    System.arraycopy(array, 0, array, i, len < i + i ? len - i : i);
  }
}

Comment: Another minor improvment could be removing the conditional:
`for (int i = SMALL, mask; i < len; i += i) {mask = (len - i + i) >> 31; System.arraycopy(array, 0, array, i,  ~mask & len - i | mask & i);}`

I have not benchmarked this in practice so it might not be.
Comment: interesting! In principle, when compiled to native code I agree that a few arithmetic and bit operations could be faster, on a modern CPU, than a conditional branch.  But there will be conditional branching inside `System.arraycopy` which we can do nothing about...
Answer: If you have another array of char, char[] b and you want to replace c with b, you can use c=b.clone();.
Comment: Or, if your arrays are variable length, create a "super long" prototype and use System.arraycopy.  Either will effectively do a `memcpy` below the covers.
Answer: See Arrays.fill method:
char f = '+';
char [] c = new char [50];
Arrays.fill(c, f);

Answer: Arrays.fill might suit your needs
Answer: Arrays.fill(myArray, 'c');
Arrays.fill
Although it is quite possible that this is doing the loop in the background and is therefore not any more efficient than what you have (other than the lines of code savings). If you really care about efficiency, try the following in comparison to the above:
int size = 50;
char[] array = new char[size];
for (int i=0; i<size; i++){
  array[i] = 'c';
}

Notice that the above doesn't call array.size() for each iteration.
Comment: The reference to array.length is cheap (not a call) and is easily optimized out of the loop.
Comment: @HotLicks Are you sure that the compiler does this? Isn't it possible for the array reference to change (and therefore the size) within the loop? Therefore would it be safe for the compiler to optimize this out? I suppose if it were smart enough to ensure that the array reference is not modified inside the loop it could do so. Again, do you have some knowledge that this optimization is being done?
Comment: @HotLicks Can I assume your statement holds try of arrays but not collections?
Comment: `array` is not changed in the loop -- very easy for the compiler to determine.  And the `arraylength` bytecode directly references the array size field in the array object, so it's virtually as cheap if left in the loop as if moved out.  Even Sun's own code (in my post) doesn't worry about moving the reference out of the loop.  The biggest performance boost is obtained in the more optimized version of Sun's code shown in the addendum to Paranoid's original -- there a special/secret flag on the method turns off bounds checking, and explicit bounds checking is done outside the loop.
Answer:    /**
     * Assigns the specified char value to each element of the specified array
     * of chars.
     *
     * @param a the array to be filled
     * @param val the value to be stored in all elements of the array
     */
    public static void fill(char[] a, char val) {
        for (int i = 0, len = a.length; i < len; i++)
            a[i] = val;
    }

That's the way Arrays.fill does it.
(I suppose you could drop into JNI and use memset.)
Answer: You could use arraycopy but it depends on whether you can predefine the source array, - do you need a different character fill each time, or are you filling arrays repeatedly with the same char?
Clearly the length of the fill matters - either you need a source that is bigger than all possible destinations, or you need a loop to repeatedly arraycopy a chunk of data until the destination is full.
    char f = '+';
    char[] c = new char[50];
    for (int i = 0; i < c.length; i++)
    {
        c[i] = f;
    }

    char[] d = new char[50];
    System.arraycopy(c, 0, d, 0, d.length);

Answer: Arrays.fill is the best option for general purpose use.
If you need to fill large arrays though as of latest idk 1.8 u102, there is a faster way that leverages System.arraycopy.
You can take a look at this alternate Arrays.fill implementation:
According to the JMH benchmarks you can get almost 2x performance boost for large arrays (1000 +)
In any case, these implementations should be used only where needed. JDKs Arrays.fill should be the preferred choice.


Nancy support for .NETCoreApp

Question: Trying to add the Nancy package to a new project. In project.json (dependencies segment) red squigly under "Nancy": "1.4.3". Mouseover displays an error relating to support for .NETCoreApp
Comment: Nancy 1.4.3 only  supports framework 4.x Simple solution but suggest for experimental use only is to install what is, as of today, an alpha version:

Install-Package Nancy -Pre
Comment: UPDATE: Spoke too soon. Nancy 2.0.0-alpha doesn't work either so I guess we'll have to wait for Nancy to catch up.
Answer: The master branch of Nancy on github already runs on .net core.We are moving from Rake to Cake for the build script , hoping to wrap that up this week so .netcore support can be pushed to Nuget.So yes wait just a bit.
Comment: That's great. Not a blocker for me but I was feeling really bad for Christian Horsdal. In his new book "Microservices in .NET: with C#" he raves about Nancy and has it as a foundation in all his source.
Comment: Sifico, are there any news about Nancy builds? I tried similar configuration on my machine and receive the same error.
(Installing Nancy with "Install-Package Nancy")
Comment: https://www.nuget.org/packages/Nancy/2.0.0-clinteastwood , please note .net core is only on 2.0-* packages.
Answer: This example was original written on Stack Overflow Documentation:
Setup Nancyfx with Dotnet core v1.1, Kestrel, and Visual Studio Code on *nix systems
Prerequiste steps:

Get dotnet core for your platform:
Dotnet Core
Follow instructions and make sure dotnet core is working
Get Visual Studio Code for your platform:
VS Code
Launch Visual Studio Code (VS code) and install the C# extension then reload

Create self hosted NancyFx project:

Setup a project with a correct project directory structure.
Open Bash Terminal and type:

mkdir nancydotnetcore
cd nancydotnetcore
mkdir src
mkdir test
touch global.json

Open global.json and enter the following code:

{
    "projects":["src", "test"]
}

In Bash terminal:

cd src
mkdir NancyProject1
dotnet new

Open folder NancyProject1 in VS code
You will get a warning: "Required assets to build and debug are missing from 'nancyproject1'."
Click "Yes"
Also you will see: There are unresolved dependencies from 'project.json'. Please execute the restore command to continue.
Click "Close" we will get to this soon.

Add the dependencies, open "project.json" and overwrite it with the following:

{
    "version": "1.0.0-*",
    "buildOptions": {
        "debugType": "portable",
        "emitEntryPoint": true
    },

    "frameworks": {
        "netcoreapp1.1": {
            "dependencies": {
                "Microsoft.AspNetCore.Hosting": "1.1.0",
                "Microsoft.AspNetCore.Server.Kestrel": "1.1.0",
                "Microsoft.AspNetCore.Owin": "1.1.0",
                "Nancy": "2.0.0-barneyrubble",
                "Microsoft.NETCore.App": {
                    "type": "platform",
                    "version": "1.1.0"
                }
            }
        }
    }
}

VS code will ask to restore click "Restore"

Create folder "Modules" in VSCode project
In the Modules folder add a file named "IndexModule.cs" then copy and save the following:

namespace NancyProject1
{
    using Nancy;
    public class IndexModule : NancyModule
    {
        public IndexModule()
        {
            Get("/", _ => "Hello dotnet core world!");
        }
    }
}

In the root directory of the project create a file called "Startup.cs" and copy and paste the following:

namespace NancyProject1
{
    using Microsoft.AspNetCore.Builder;
    using Nancy.Owin;

    public class Startup
    {
        public void Configure(IApplicationBuilder app)
        {
            app.UseOwin(x => x.UseNancy());
        }
    }
}

Open file "Program.cs" and overwrite the content with the following and save:

namespace NancyProject1
{
    using System.IO;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;

    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseKestrel()
                .UseStartup()
                .Build();

            host.Run();
        }
    }
}

Done! Now lets run this and see the output.
Click the debug symbol in VS Code, and Click the run button. It should compile and start the project.
Open the browser @ http://localhost:5000

Pat yourself on the back and enjoy!

still pre release version but works with .net core as the time of this writing, view engines are very limited on core.
Comment: similarly can I host windows service using Nancy and .net core?
Answer: Install-Package Nancy -Version 2.0.0-barneyrubble -Pre

Nancy support for .NETCoreApp


How can a method be called for testing and not be executed?

Question: Here's my Component :
<code>@Component({
    selector: 'app-signup',
    templateUrl: './signup.component.html',
    styleUrls: ['./signup.component.scss']
})
export class SignUpComponent implements OnInit {
    specialLink: string;

    constructor(
        private activatedRoute: ActivatedRoute,
        private techService: TechService
 ) {}

ngOnInit() {
        this.specialLink = this.activatedRoute.snapshot.params.id;

        if (this.specialLink !== undefined) {
            console.log('GOOD1');
            this.setSpecialSignup();
            console.log('GOOD3');
        }

setSpecialSignup() {
        console.log('GOOD2');
        this.techService.getStuff();
    }
</code>
And here's my tests :
<code>describe('SignUpComponent', () => {
  let component: SignUpComponent;
  let fixture: ComponentFixture<SignUpComponent>;
  let ActivatedRouteMock: any;

  beforeEach(async(() => {
    ActivatedRouteStub = {
      snapshot: {
        params: { id: 123 }
      },
    };

    TechServiceMock = jasmine.createSpyObj('TechService', ['getStuff']);
    TechServiceMock.getStuff.and.returnValue(new Promise((resolve, reject) => { resolve() }));

    TestBed.configureTestingModule({
      declarations: [ SignUpComponent ],
      imports: [ RouterTestingModule ],
      providers: [
        {provide: ActivatedRoute, useValue: ActivatedRouteStub},
        {provide: TechService, useValue: TechServiceMock},
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(SignUpComponent);
    component = fixture.componentInstance;
  });

  describe('to get special signup', () => {
      it('should call setSpecialSignup() one time when user is coming from special link', () => {
        spyOn(component, 'setSpecialSignup');
        ActivatedRouteStub.snapshot.params.id = "some_special_link";
        fixture.detectChanges();
        expect(component.setSpecialSignup).toHaveBeenCalled(); // it's working
      });

      it('should call TechService', () => {
        ActivatedRouteStub.snapshot.params.id = "123";
        fixture.detectChanges();
        expect(TechServiceMock.getStuff).toHaveBeenCalled(); // it's NOT working
      });
    });
</code>
I want to test if techService.getStuff() has been called. The service is in
setSpecialSignup() method in Signup component.
The method has been called when I test it, but the logs in console tells me otherwise. (It goes GOOD1 and GOOD3 without GOOD2, which is weird).
Maybe this is simple question, but is there any explenation for this ?
How can I test if TechServiceMock.getStuff() has been called ?
I tried different approaches to mock TechService but any of these helped.
What did I miss ?
Answer: If I understand you correctly, you are looking for the callThrough() method, you can read more about it here: https://hatoum.com/blog/2016/11/12/jasmine-unit-testing-dont-forget-to-callthrough
Comment: Perfect ! The article is very informative and very clear, thanks a lot :)


I have been trying to upload marketplace Vm solution form GCP ,and am unable to find the reason why this is happening to me

Question: openlitespeed-django-1-vm: {"ResourceType":"compute.v1.instance","ResourceErrorCode":"403","ResourceErrorMessage":{"code":403,"message":"The caller does not have permission","status":"PERMISSION_DENIED","statusMessage":"Forbidden","requestPath":"https://compute.googleapis.com/compute/v1/projects/sriastrovastu-map/zones/us-east4-b/instances","httpMethod":"POST"}}
Answer: You seem to have a permission issue as indicated by this section.
<code>"message":"The caller does not have permission","status":"PERMISSION_DENIED"
</code>
You would probably want to make sure the account you are using has the right IAM permissions.
If you are trying to submit a solution to Cloud Marketplace, I would suggest you take a look at this documentation.


All visited urls ending with _900 in cache_page tables

Question: I came across strange problem with drupal 7 and caching for anonymous users. After clearing cache, newly visited pages by anonymous users are stored in cache_page with _900 at the end of url like this www.example.com/examplepage_900. Anybody know what can cause this behavior?
Comment: Is it a port number?
Comment: @DavidThomas I have no idea why are such links created in cache tables. All visited pages ends with _900
Answer: This issue was caused by module http://drupal.org/project/resp_img after installing the latest version, everything is ok.


Coercity definitions in $\mathbb{R}$

Question: Let $f:\mathbb{R}\to\mathbb{R}\cup\{-\infty, +\infty\}$ be a function. My definition of coervit is that $f$ is coercive if
$$ (D)\qquad \lim_{|x|\to +\infty} f(x) = +\infty.$$
I am trying to justify some equivalent definitions I found surfing on the web. For example:
a) $f(x)\ge |x|$;
It is clear that, for $|x|\to +\infty$, it follows that $f(x)\to +\infty$, too, and then $a)\implies (D)$. However I am not able to understand how to prove (if it holds!) that $(D)\implies a)$.
b) $\displaystyle\lim_{|x|\to +\infty} \frac{f(x)}{|x|} =\alpha>0$. This one is of my particular interest, but I am not able to prove the equivalence with $(D)$. Intuitively I justify it saying that "infinities with same order", something like $\displaystyle\lim_{|x|\to +\infty} \frac{\alpha x}{x}$, but I am not so sure.
Could someone please help me?
Thank you in advance!
Answer: The definitions are not equivalent for example $f(x) $ = $\log(|x|)$ and $-1$ at $0$ satisfies $D$ but does not satisfy $a)$ since $|x|>f(x)$ for all $x$ .$f(x)$ also does not satisfy $b)$ since $\log(|x|)/
|x| $  goes to $0$ as $|x|$ goes to infinity
Comment: So it only holds $a)\implies (D)$ and $b)\implies (D)$, isn't it?
Comment: Yes but the reverse fails . @User1010
Comment: @User1010 Does this answer your question?

Coercity definitions in $\mathbb{R}$


Animating Polyline fails with Lat/Long Array

Question: I am trying to use google.maps.geometry.spherical.interpolate to animate a set of Lat/Long. I can successfully animate two Lat/Long points, but when I try to loop through them I do not see all points animate. What is wrong with my approach?
Here is how to animate just two points: http://jsfiddle.net/4kgg7536/9/

function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
 'zoom': 10,
   'center': new google.maps.LatLng(25.969937410307143, -80.0804620727539),
   'mapTypeId': google.maps.MapTypeId.TERRAIN,
   'scrollwheel': true,
   'draggable':true
  });

  var flightPath = {
    one: [
   new google.maps.LatLng(26.248630099430756,-80.05024967041015),
    new google.maps.LatLng(26.136493049813648, -80.16423282470703),
    new google.maps.LatLng(26.034120197851937,-80.04475650634765),
    new google.maps.LatLng(25.957590547577706,-80.1573663696289),
    new google.maps.LatLng(25.827870363354016,-80.03239688720703),
   new google.maps.LatLng(25.698007870576784,-80.14500675048828)
    ]};

  var flightSymbol = {
    path: google.maps.SymbolPath.FORWARD_OPEN_ARROW,
    strokeOpacity: 1,
    scale: 3
  };

  var pathSymbol = {
    path: 'M 0,-0.5 0,0.5',
    strokeOpacity: 1,
    strokeWeight:3,
    scale: 4
  }

   flightRoute = new google.maps.Polyline({
    path: flightPath.one,
    geodesic: true,
    strokeOpacity: 0,
    icons: [
   {
     icon: flightSymbol,
     offset: '100%'
   }, {
     icon: pathSymbol,
     offset: '0',
     repeat: '15px'
   },
    ],
    strokeOpacity: 0,
    strokeColor: '#f00',
    map: map
  });

   var departure = flightPath['one'][0];
  var arrival = flightPath['one'][4];

  var step = 0;
  var numSteps = 500; //Change this to set animation resolution
  var timePerStep = 5; //Change this to alter animation speed
  var interval = setInterval(function() {
  step += 1;
  if (step > numSteps) {
      clearInterval(interval);
  } else {
     var are_we_there_yet = google.maps.geometry.spherical.interpolate(departure,arrival,step/numSteps);
     flightRoute.setPath([departure, are_we_there_yet]);
    }
   }, timePerStep);
 }

Now here I try to animate the set of lat/longs without success:

function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
 'zoom': 10,
   'center': new google.maps.LatLng(25.969937410307143, -80.0804620727539),
   'mapTypeId': google.maps.MapTypeId.TERRAIN,
   'scrollwheel': true,
   'draggable':true
  });

  var flightPath = {
    one: [
   new google.maps.LatLng(26.248630099430756,-80.05024967041015),
    new google.maps.LatLng(26.136493049813648, -80.16423282470703),
    new google.maps.LatLng(26.034120197851937,-80.04475650634765),
    new google.maps.LatLng(25.957590547577706,-80.1573663696289),
    new google.maps.LatLng(25.827870363354016,-80.03239688720703),
   new google.maps.LatLng(25.698007870576784,-80.14500675048828)
    ]};

  var flightSymbol = {
    path: google.maps.SymbolPath.FORWARD_OPEN_ARROW,
    strokeOpacity: 1,
    scale: 3
  };

  var pathSymbol = {
    path: 'M 0,-0.5 0,0.5',
    strokeOpacity: 1,
    strokeWeight:3,
    scale: 4
  }

   flightRoute = new google.maps.Polyline({
    path: flightPath.one,
    geodesic: true,
    strokeOpacity: 0,
    icons: [
   {
     icon: flightSymbol,
     offset: '100%'
   }, {
     icon: pathSymbol,
     offset: '0',
     repeat: '15px'
   },
    ],
    strokeOpacity: 0,
    strokeColor: '#f00',
    map: map
  });

for(i=0;i<=flightPath['one'].length-2;i++)
  {
   var departure = flightPath['one'][i];
  var arrival = flightPath['one'][i+1];

  var step = 0;
  var numSteps = 500; //Change this to set animation resolution
  var timePerStep = 5; //Change this to alter animation speed
  var interval = setInterval(function() {
  step += 1;
  if (step > numSteps) {
      clearInterval(interval);
  } else {
     var are_we_there_yet = google.maps.geometry.spherical.interpolate(departure,arrival,step/numSteps);
     flightRoute.setPath([departure, are_we_there_yet]);
    }
   }, timePerStep);
       }
 }

The snippet above has the following change where I put everything inside of a for-loop, however only the last two points animate. I am not clearing the map, so why is it that only the last two points show?
for(i=0;i<=flightPath['one'].length-2;i++)
{
    var departure = flightPath['one'][i];
    var arrival = flightPath['one'][i+1];

    var step = 0;
    var numSteps = 500; //Change this to set animation resolution
    var timePerStep = 5; //Change this to alter animation speed
    var interval = setInterval(function() {
    step += 1;

    if (step > numSteps) {
        clearInterval(interval);
    } else {
             var are_we_there_yet = google.maps.geometry.spherical.interpolate(departure,arrival,step/numSteps);
             flightRoute.setPath([departure, are_we_there_yet]);
         }
    }, timePerStep);
}

Comment: Why the down-vote? What more do I need to post to show effort? I am confused.. why down-vote without providing a constructive comment?
Answer: google.maps.geometry.spherical.interpolate only works between two points on the polyline.  You need to update your setInterval function to handle multiple sets of points.  Putting it in inside the for loop will only run between the last two points in the polyline (the loop iterates to the last set of points, then the set interval function runs).
If you want the polyline to stay between the earlier points you have to create a new one to fill in the previous history.
proof of concept fiddle
code snippet:

var flightRoute, flightRouteCompleted;

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    'zoom': 10,
    'center': new google.maps.LatLng(25.969937410307143, -80.0804620727539),
    'mapTypeId': google.maps.MapTypeId.TERRAIN,
    'scrollwheel': true,
    'draggable': true
  });

  var flightPath = {
    one: [
      new google.maps.LatLng(26.248630099430756, -80.05024967041015),
      new google.maps.LatLng(26.136493049813648, -80.16423282470703),
      new google.maps.LatLng(26.034120197851937, -80.04475650634765),
      new google.maps.LatLng(25.957590547577706, -80.1573663696289),
      new google.maps.LatLng(25.827870363354016, -80.03239688720703),
      new google.maps.LatLng(25.698007870576784, -80.14500675048828)
    ]
  };
  for (var i = 0; i < flightPath["one"].length; i++) {
    var marker = new google.maps.Marker({
      position: flightPath["one"][i],
      map: map,
      title: "" + i
    })
  }

  var flightSymbol = {
    path: google.maps.SymbolPath.FORWARD_OPEN_ARROW,
    strokeOpacity: 1,
    scale: 3
  };

  var pathSymbol = {
    path: 'M 0,-0.5 0,0.5',
    strokeOpacity: 1,
    strokeWeight: 3,
    scale: 4
  }

  flightRoute = new google.maps.Polyline({
    path: flightPath.one,
    geodesic: true,
    strokeOpacity: 0,
    icons: [{
      icon: flightSymbol,
      offset: '100%'
    }, {
      icon: pathSymbol,
      offset: '0',
      repeat: '15px'
    }, ],
    strokeOpacity: 0,
    strokeColor: '#f00',
    map: map
  });
  flightRouteCompleted = new google.maps.Polyline({
    geodesic: true,
    strokeOpacity: 0,
    icons: [{
      icon: pathSymbol,
      offset: '0',
      repeat: '15px'
    }, ],
    strokeOpacity: 0,
    strokeColor: '#f00',
    map: map
  });
  var departure = flightPath["one"][0];
  var arrival = flightPath['one'][1];
  var i = 0;
  var step = 0;
  var numSteps = 500; //Change this to set animation resolution
  var timePerStep = 5; //Change this to alter animation speed
  var interval = setInterval(function() {
    step += 1;
    if (i >= (flightPath["one"].length - 1)) {
      clearInterval(interval);
    } else if (step > numSteps) {
      i++;
      step = 0;
      departure = flightPath["one"][i];
      arrival = flightPath['one'][i + 1];
      if (i == 1) {
        flightRouteCompleted.setPath([flightPath["one"][0]]);
      }
      flightRouteCompleted.getPath().push(flightPath["one"][i]);
    } else {
      var are_we_there_yet = google.maps.geometry.spherical.interpolate(departure, arrival, step / numSteps);
      flightRoute.setPath([departure, are_we_there_yet]);
    }
  }, timePerStep);
}
google.maps.event.addDomListener(window, "load", initMap);

Comment: That should be fixed (the termination condition wasn't working)
Comment: This is perfect, except it is generating the following error if you look in the console when the animation reaches the last marker:

*js?v=3.exp&callback=initMap&libraries=geometry:46 Uncaught TypeError: Cannot read property 'lat' of undefined*
Comment: Fantastic work, I will learn from this, thank you sir! I have up-voted and accepted your answer.


Issue in iPhone Dictionary?

Question: I am revolving around with a small issue in iPhone while playing around Array and Dictionary. I have and product dictionary with the following data
  name = Product;
    options =     (
                {
            code = code1;
            name = "product AAA";
        },
                {
            code = code1;
            name = "product BBB";
        },
                {
            code = "code2";
            name = "product BBB";
        },
                {
            code = "code3";
            name = "product CCC";
        },
                {
            code = "code3";
            name = "product DDD";
        },
                {
            code = code4;
            name = "product EEE";
        },
                {
            code = code4;
            name = "product FFF";
        }
    );

Also i have an array of matching products
matchingProducts
{
    "product BBB",
    "product CCC",
    "product DDD"
)

Now, all i want to do is i want to remove from products dictionary comparing to matchingProducts array.  how can i do it.
Note: I cannot use key to remove objects as per my business rules. I have issue as i have names are repeated but i have to get the final result dictionary as shown below. Is it possible.
   name = Product;
    options =     (
                {
            code = code1;
            name = "product AAA";
        },
                {
            code = code1;
            name = "product BBB";
        },
                {
            code = code4;
            name = "product EEE";
        },
                {
            code = code4;
            name = "product FFF";
        }
    );

Please, reply me back if my question is not clear.
I have fixed the similar issue in java using the below code
for (int j = 0; j < matchingProducts.size(); j++) {
 String product = ((Product) matchingProducts.elementAt(i)).name;

 for (int i = 0; i <Product.size(); i++) {
     String productName = ((Product) Product.elementAt(i)).name;
     if (product.equals(productName)) {
  Product.removeElementAt(i);
  break;
     }
 }
 }

Comment: i have used an array to extract the dictionary value and trying to achieve it .. but failed
Comment: If you are unable to use the key (which i assume is the product code in this scenario), what would be the rule you use to match and remove similar objects? e.g. how would you decide between removing 'code 1, product BBB' and 'code 2, product BBB'
Comment: @Neel, I see 2 arrays. Which one is dictionary and what are its keys?
Comment: @Madhumal I have placed the java code. I am well versed in java. I am looping the matchingProducts array and getting the element using loop counter as index. Now checking that with the each element of the products dictionary. if matching then removing the dictionary object according to the index. then i am using break. please suggest any such logic will work here.
Answer: NSMutableDictionary *Product = initialize like you did with Products;
NSMutableDictionary *resultant = [NSMutableDictionary alloc]init]; //this will have your result
NSArray *keys = [Product allKeys];
for(int i = 0 ; i < [keys count]; i++)
  {
    id temp = [Product objectForKey:keys[i]];

 bool matchFound = NO;
for (int j = 0; j < [matchingProduct count]; j++)
   {
     id temptemp = [matchingProduct objectAtIndex:j] //Assuming matchingProduct is an NSArray or NSMutableArray
     if(temp == temptemp)
       {
           matchFound = YES;
       }
   }

  if(!matchFound)
     [resultant addObject:temp];

}
// resultant now has what you wanted. Use it.
Comment: from my above product dictionary,how can i access the all codes names along with values from dictionary.It internally holds the options array.
Comment: Can you post your declaration for both Product dictionary and matchingProduts array ?
Comment: NSDictionary *productDict = nil;
    for (NSDictionary *dict in items)
    {
     if ([[dict objectForKey:@"name"] isEqualToString:@"Product"])
     {
      productDict = dict;
      break;
     } }

 NSArray *matchingProducts;
     for(int i=0;i<[selectedStateDictvalues  count];i++)
     {
     NSString *optionString = (NSString*)[selectedStateDictKeys objectAtIndex:i];
      if([optionString isEqualToString:@"ExcludeProduct"])
       {
        matchingProducts =[[[[selectedStateDictvalues objectAtIndex:i]  objectForKey:@"options"] valueForKeyPath:@"@unionOfObjects.name"] retain];
}}
Comment: hey neel it would be better if you move this to gmail or something. I am sure I can help you with this. If you are interested mail me the relevant code for the all the declarations : productDict, Items, MatchingProducts etc and I will send you the solution. If you do it now, expect an answer by tonight. firstname.lastname@example.com

Issue in iPhone Dictionary?