text:
Q: How can I force chrome to save email passwords? I am running Ubuntu Quantal (12.10) with Chrome (not Chromium) installed via terminal. Unfortunately, when it comes to mail automatic log in, for some reason Chrome doesn't offer to save passwords, which is really frustrating if one uses mail a lot, I do not want to write my username and passwords every time I check my mail. Looked everywhere and I can't find a solution.

A: See the image. Do you have similar settings in the Advanced Settings section?


text:
Q: refresh javascript after jquery request I'm trying to refresh a
 using jQuery to call a PHP script that includes javascript.
After refresh the page is loaded but javascript isn't executed.
My problem is that I do not use javascript function but simply code.
I know I have to use .on() or .live() but don't know how.
The page I'm trying to call:
require 'connexion.php';

$statement = $connexion->prepare("SELECT * FROM table");
$statement->execute();

echo "
";
//  generating content
if (isset($statement))
{
        while($data = $statement->fetch())
        {
?>

<?php

                if ($data['user'] == 'user1')
                {
                    echo "
".'Le '.$data['date'].'  '.$data['user'].' à dit:'.'
'."\n" ;
                    ?><?php
                    echo "
"."\n" ;
                }
                else
                {
                    echo "
".'Le '.$data['date'].'  '.$data['user'].' à dit:'.'
'."\n" ;
                    ?><?php
                    echo "
"."\n" ;
                }

        }
}

        echo '
';
?>

the main page:

A: From what I see, there is absolutely no need to use JS on the page you're calling with AJAX. All of that stuff can be rendered by PHP only, and that's the way you should do it.
Even if it wasn't, running JS code from an AJAX response can be quite unsafe and challenging. You would have to separate the JS code (maybe in a JSON variable) and then run eval() on it... Again, very very unsafe, and not recommended.
If you still want to use JS after the AJAX call, define the function on the main page, and pass it just the arguments you get from the AJAX call. Something like this:
function autoRefresh_div() {
    $.get("refreshpage.php", function(res){
        var content = res.htmlContent; // say this is the content for the div
        var jsParam = res.jsParam;     // and this is the JS parameter(s)
        $("#refreshdiv").html(content);
        handleAjax(jsParam);
    });
}

function handleAjax(params) {
    /// do stuff here
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Show that $(X_1 + \cdots + X_n )/n \to 0$ in distribution by characteristic function There's a random variable $X$ whose characteristic function is $\phi(t) = E(e^ {itX})$ is given by  $$\phi(t) = e^{-|t|^{3/2}}$$ Let $X_1, X_2, \ldots$ the independent random variable with the same distribution as $X$.

*

*Show that $(X_1 + \cdots + X_n )/n \to 0$ in distribution.

*Find a choice of constants $C_n$, depending on $n$ , such that $(X_1 + \cdots + X_n )/C_n \to X$ in distribution.
What I tried with continuity theorem:
but I don't know how to continue the next steps. Thank you!

A: Pay attention to exponent rules. The characteristic for the sum divided by $n$ is.
$$({e^{-(|\frac{t}{n}|^{3/2})}})^n={e^{-n(|\frac{t}{n}|^{3/2})}}={e^{-\frac{1}{\sqrt n}(|t|^{3/2})}}$$
This converges to $1$, which is the characteristic of $0$.
Step 2, we need
$${e^{(C(n))^{-3/2}n(|t|^{3/2})}}=e^{-(|t|^{3/2})}$$
Hence $C(n)=n^{2/3}$ from some $n>k$.


text:
Q: How to do tuple augmentation The following code is from chapter 5 of "F# 4.0 Design Patterns".
let a = 1,"car"
type System.Tuple<'T1,'T2> with
  member t.AsString() =
    sprintf "[[%A]:[%A]]" t.Item1 t.Item2
(a |> box :?> System.Tuple<int,string>).AsString()

The desired output is [[1]:["car"]]
However, a red squiggly appears under AsString(). "The field, constructor or member 'AsString' is not defined. Maybe you want one of the following: ToString"

A: This is a bit odd code sample - I suspect the point that this is making is that F# tuples are actually .NET tuples represented using System.Tuple - by showing that an extension to System.Tuple can be invoked on ordinary F# tuples.
I suspect the behaviour of F# has changed and it no longer allows this - it may have been that adding extensions was allowed on System.Tuple, but not on ordinary F# tuples, but the two have became more unified in the compiler.
However, you can do a very similar thing using the .NET-style extension methods:
let a = 1,"car"

[<System.Runtime.CompilerServices.ExtensionAttribute>]
type TupleExtensions =
  [<System.Runtime.CompilerServices.ExtensionAttribute>]
  static member AsString(t:System.Tuple<'T1,'T2>) =
    sprintf "[[%A]:[%A]]" t.Item1 t.Item2

let st = (a |> box :?> System.Tuple<int,string>)
st.AsString()

This can actually be also invoked directly on an F# tuple value:
("car", 32).AsString()


text:
Q: Use properties of the base control that is inside the UserControl How can I use the properties of the controls that are inside a user control without having to use DependencyProperty?
Since, if for example I want to use all the properties of a button, I would have to declare all these?
And if there is another way without user control and it is the correct one, I would appreciate it if you answered it. (Google translator, sorry)
UserControl:
<UserControl x:Class="UserControls.UserControl01"
                 ...
                 >
        <Grid>
            <Button x:Name="uc_btn" />
            <TextBox x:Name="uc_txt"  />
            <DataGrid x:Name="uc_dtg"  />
        </Grid>
    </UserControl>

Code using the UserControl:
<Window x:Class="UserControls.wnd02"
        ...
        >
    <Grid>
        <local:UserControl01 uc_btn.Background="Red" uc_txt.Margin="10" uc_dtg.BorderThickness="5" Margin="90" />

        <local:UserControl01 uc_btn.Background="Green" uc_txt.Margin="25" uc_dtg.BorderThickness="20" Margin="5" />
    </Grid>
</Window>

A: It is not usual to do what you are asking.
Let's consider a usercontrol which is intended to work as if it is one single control. For example a time picker. This contains two sliders which increase/decrease hour and minute. You can also overtype in the hour and minute textboxes and there's a : between the two textboxes.
This usercontrol is all about the one property though. Time.  You don't care what the minutes background is externally. If this changes it's internal to the usercontrol.
In this scenario you'd usually add a TimeSpan dependency property to the usercontrol and this is the only thing anything external to it uses.
Pretty much all commercial WPF development uses the MVVM pattern and that TimeSpan would be bound to a property in the parent view's viewmodel.
That's one scenario.
Another is where a usercontrol encapsulates a bunch of UI which is then re-usable.
Styling has scope so when you apply a style to say a Button in a window then that would apply to any Buttons in a usercontrol within it. Setting their properties.
There are also certain dependency properties marked as "inherits" whose values propogate down the visual tree.
One such is DataContext and it is this which most teams would use to deal with properties within a usercontrol.
Using MVVM there would be a MainWindowViewModel.
That would have (say ) a ChildUserControlViewModel property. That would be associated with usercontrol using a datatemplate specified datatype.
You'd then bind properties of whatever is in a usercontrol to properties of ChildUserControlViewModel or properties of MainWindowViewModel using RelativeSource binding.
ViewModel first is a common navigation and composition pattern for WPF. You should be able to find numerous blogs explain it better than I can in a SO post.
Here's one:
https://social.technet.microsoft.com/wiki/contents/articles/30898.simple-navigation-technique-in-wpf-using-mvvm.aspx


text:
Q: Button trigger when they press Enter in the Page in MVC view without using Jquery I have a Modal in MVC view that has a button which call java script to post to controller. How I can make the Button trigger when they press Enter in the Page.
I am not sure where in View I can call the JavaScript Function.
Please no Jquery. I have to use only use Javascript for this purpose.
This is My View:
 @using (Html.BeginForm("forgotPassword", "Home", FormMethod.Post))
        {
            @Html.AntiForgeryToken()

Email Address

<input type="email" name="email" placeholder="example@email.com" id="email" class="forgot-password-textbox">

<input type="button" value="Submit" id="btn-reset-password" onclick="resetPasswordHandler()" class="orange-button forgot-password-button">

        }

and this is Js method:
function resetPasswordHandler() {
    //Post Data to Controller
};

A: You can call resetPasswordHandler function when enter key is pressed.
document.onkeydown = function () {
    if (window.event.keyCode == '13') {
        resetPasswordHandler();
    }
}

A: *

*Use the onsubmit function on the form (instead of onclick on the button)

*Return false from the function to prevent the form submission

*Change your button to type='submit'

    @using (Html.BeginForm("forgotPassword", "Home", FormMethod.Post, new { onsubmit = "return resetPasswordHandler()" }))
        {
            @Html.AntiForgeryToken()

Email Address

<input type="email" name="email" placeholder="example@email.com" id="email" class="forgot-password-textbox">

<input type="submit" value="Submit" id="btn-reset-password" class="orange-button forgot-password-button">

        }

function resetPasswordHandler() {
    var postResult = null;
    var data = {
        Email: document.getElementById('email').value
    };
    var path = "/forgotPassword";

    var errorMessage = document.getElementById('Message');

    $.ajax({
        dataType: "text",
        url: path,
        data: data,

        type: "POST",
        cache: false,
        success: function (result) {
            postResult = $.parseJSON(result);
            if (postResult.status == "success") {
                $('#forgot').hide();
                $('#forgot-thank-you').show();
            }
            else {
                errorMessage.innerHTML = postResult.message;
            }
        },
        error: function () {
            errorMessage.innerHTML = "An error occured";
        }
    });
    return false;
};


text:
Q: Add media edit gallery thumbnail resize dashboard I know it sounds like stupid but my client is asking for it and I have no idea how to get through it.
When I create a gallery in post by clicking "Add Media" and select images, then I hit the button that says "Create a new gallery". Now the next page is of ordering images where I can drag and drop the image to re-order. The problem is right now they are very big thumbnail(3 thumbnail per row). I need them to be more small(atleast 6 thumbnail per row).
Is it possible. Please help.

A: You can do it like this:
add_action( 'admin_print_scripts-post.php', function(){
    ?>
    <style>
    .attachment-preview {
        width: 90px !important;
        height: 90px !important;
    }
    </style>
    <?php
});

But you'll have to find your way to get the CSS right. This one is just a test, it works but have issues.


text:
Q: What does the filter parameter mean in Conv2d layer? I am getting confused with the filter paramater, which is the first parameter in the Conv2D() layer function in keras. As I understand the filters are supposed to do things like edge detection or sharpening the image or blurring the image, but when I am defining the model as
input_shape = (32, 32, 3)
model = Sequential()
model.add( Conv2D(64, kernel_size=(5, 5), activation='relu', input_shape=input_shape, strides=(1,1), padding='same') )
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2,2)))
model.add(Conv2D(64, kernel_size=(5, 5), activation='relu', input_shape=input_shape, strides=(1,1), padding='same'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2,2)))
model.add(Conv2D(128, kernel_size=(5, 5), activation='relu', input_shape=input_shape, strides=(1,1), padding='same'))
model.add(Flatten())
model.add(Dense(3072, activation='relu'))
model.add(Dense(2048, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))

I am not mentioning the the edge detection or blurring or sharpening anywhere in the Conv2D function. The input images are 32 by 32 RGB images.
So my question is, when I define the Convolution layer as Conv2D(64, ...), does this 64 means 64 different types of filters, such as vertical edge, horizontal edge, etc, which are chosen by keras at random? if so then is the output of the convolution layer (with 64 filters and 5x5 kernel and 1x1 stride) on a 32x32 1-channel image is 64 images of 28x28 size each. How are these 64 images combined to form a single image for further layers?

A: The filters argument sets the number of convolutional filters in that layer. These filters are initialized to small, random values, using the method specified by the kernel_initializer argument. During network training, the filters are updated in a way that minimizes the loss. So over the course of training, the filters will learn to detect certain features, like edges and textures, and they might become something like the image below (from here).

It is very important to realize that one does not hand-craft filters. These are learned automatically during training -- that's the beauty of deep learning.
I would highly recommend going through some deep learning resources, particularly https://cs231n.github.io/convolutional-networks/ and https://www.youtube.com/watch?v=r5nXYc2wYvI&list=PLypiXJdtIca5sxV7aE3-PS9fYX3vUdIOX&index=3&t=3122s.

A: Just wanted to clarify what the output shape was.
Although jakub's answer was good, I don't think it addressed the "single image for further layers" part of the question.
I did a model.summary() to find out more.
I found that the shape returned from a Conv2D is (None, img_width, img_height, num_filters)
So when you pass the output of the Conv2D to MaxPooling you are passing that shape which means it is basically passing each entire convoluted image.
The other layers handle this gracefully. MaxPooling2D(2,2) returns the same shape but half the image size (None, img_width / 2, img_height / 2, num_filters).
Side note: I wish the filters was named num_filters because filters seems to imply you're passing in a list of filters in which to convolute the image.


text:
Q: jQuery widget _on delegating Element I am using the Widget factory from jQuery UI into a existing production environment.
This environment uses a binded event called sm2.validateNext which triggers before the page changes. However when trying to bind to this event using _on, it would try to split this event name and delegate it. (Which i believe is correct, bot not the expected functionality for me).
Code (inside the $.widget):
this._on(true, document, {
    "sm2.validateNext": function () { ... },
});

And debugging this code, it gets delegated (not my expected behaviour) (from jquery-ui.widget.js)
var match = event.match( /^(\w+)\s*(.*)$/ ),
eventName = match[1] + instance.eventNamespace,
selector = match[2];
if ( selector ) {
    delegateElement.delegate( selector, eventName, handlerProxy );
} else {
    element.bind( eventName, handlerProxy );
}

Because of the . (dot) it gets a match and selector becomes valid delegating the event. However I need to get binded with its handlerProxy.
Is there a way to avoid get "trapped" into that match? I tried to escape sm2\.validateNext without result.
Note: $(document).on("sm2.validateNext"...) Doesnt work for me as I need the instance to be at the widget object.

Thanks for your help!

A: Found my solution by using $.proxy
Instead of:
this._on(true, document, {
    "sm2.validateNext": function () { ... },
});

I used:
$(document).on("sm2.validateNext", $.proxy(function () { ... }, this));

And now it works just as I expected.


text:
Q: Formula to get unique possible combinations Is there any to get all possible outcome as below.
I have 2 word O & E
I want to get 6 character word with O & E like this
O O O O O O
E O O O O O

there are mane such possible results. If there any formula which will give possible combinations.

A: Just copy down this starting from row 1
=SUBSTITUTE(SUBSTITUTE(DEC2BIN(ROW()-1,6),"0","O"),"1","E")


text:
Q: Using Google Cloud API python sample asynchronous recording code is giving me attribute error Link to code:
https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/speech/cloud-client/transcribe_async.py
I'm using the sample python code from Google Speech API to convert long (greater than 1 minute) audio files from speech to text. How do I run the code in PyCharm so it converts my audio file (in wave format) to text using the API key I created (to charge my account) without getting the 'NoneType' error?
I added the path of the audio file directly into the code (line 73). I also added "--" in front of 'path' to make it process the LOC (line 73). The error I get is as follows:
**C:\Users\Dave\AppData\Local\Programs\Python\Python37\python.exe C:/Users/Dave/Desktop/mizu/gcapi.py
Traceback (most recent call last):
  File "C:/Users/Dave/Desktop/mizu/gcapi.py", line 75, in <module>
    if args.path.startswith('gs://'):
AttributeError: 'NoneType' object has no attribute 'startswith'
Process finished with exit code1**

import argparse
import io

# [START speech_transcribe_async]
def transcribe_file(speech_file):
    """Transcribe the given audio file asynchronously."""
    from google.cloud import speech
    from google.cloud.speech import enums
    from google.cloud.speech import types
    client = speech.SpeechClient()

    # [START speech_python_migration_async_request]
    with io.open(speech_file, 'rb') as audio_file:
        content = audio_file.read()

    audio = types.RecognitionAudio(content=content)
    config = types.RecognitionConfig(
        encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,
        sample_rate_hertz=16000,
        language_code='en-US')

    # [START speech_python_migration_async_response]
    operation = client.long_running_recognize(config, audio)
    # [END speech_python_migration_async_request]

    print('Waiting for operation to complete...')
    response = operation.result(timeout=90)

    # Each result is for a consecutive portion of the audio. Iterate through
    # them to get the transcripts for the entire audio file.
    for result in response.results:
        # The first alternative is the most likely one for this portion.
        print(u'Transcript: {}'.format(result.alternatives[0].transcript))
        print('Confidence: {}'.format(result.alternatives[0].confidence))
    # [END speech_python_migration_async_response]
# [END speech_transcribe_async]

# [START speech_transcribe_async_gcs]
def transcribe_gcs(gcs_uri):
    """Asynchronously transcribes the audio file specified by the gcs_uri."""
    from google.cloud import speech
    from google.cloud.speech import enums
    from google.cloud.speech import types
    client = speech.SpeechClient()

    audio = types.RecognitionAudio(uri=gcs_uri)
    config = types.RecognitionConfig(
        encoding=enums.RecognitionConfig.AudioEncoding.FLAC,
        sample_rate_hertz=16000,
        language_code='en-US')

    operation = client.long_running_recognize(config, audio)

    print('Waiting for operation to complete...')
    response = operation.result(timeout=90)

    # Each result is for a consecutive portion of the audio. Iterate through
    # them to get the transcripts for the entire audio file.
    for result in response.results:
        # The first alternative is the most likely one for this portion.
        print(u'Transcript: {}'.format(result.alternatives[0].transcript))
        print('Confidence: {}'.format(result.alternatives[0].confidence))
# [END speech_transcribe_async_gcs]

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument(
        '--path', help='C:/Users/Dave/Desktop/mizu/output.wav')
    args = parser.parse_args()
    if args.path.startswith('gs://'):
        transcribe_gcs(args.path)
    else:
        transcribe_file(args.path)

I expect it to output a file with text from the audio file being transcribed, billing my account in the process.

A: https://docs.python.org/3/library/argparse.html
With parser.add_argument('--path', help='C:/Users/Dave/Desktop/mizu/output.wav') you just defined that your script may accept argument --path after it's invoked from command line, and that text is just a help text shown if someone starts your script with --help argument.
So, if that script where if __name__ == '__main__' is located has the name myscript.py, you actually have to start your script like:
python myscript.py --path C:/Users/Dave/Desktop/mizu/output.wav

But, that routine makes no sense in this case, a solution for you is to get rid of that extra code. Do just:
if __name__ == '__main__':
    transcribe_file('C:/Users/Dave/Desktop/mizu/output.wav')


text:
Q: Does a goroutine terminates after its Kubernetes container gets terminated? For example, a container runs the main thread and a goroutine. The main thread encounters an issue and terminates. Note that for Golang, termination of the main thread does not result in auto-termination of the goroutine.

*

*As the main thread has been terminated, will the container be killed and re-created? Or will the container continue running due to the goroutine is still running?

*If the container will be killed and re-created after the main thread has been terminated, will this result in the goroutine getting terminated as well? Or will the goroutine continue running indefinitely and there is no easy way to terminate it now?

A: If the main functions exists, the program is stopped. Nothing will run any more. It will release any used resource, like file descriptors and database connections.
In the below program, we will never see done being printed.
func main() {
    go func() {
        time.Sleep(time.Minute)
        fmt.Println("done")
    }()

    time.Sleep(time.Second * 3)
}

https://play.golang.com/p/kPKZDdMcduS
If the program with that main function was the foreground process of the container, then the container shuts down as its standard behaviour with containers.
If you run the below example, you can observe how the container shuts down as soon as the sleep finishes.
$ docker run --name sample busybox sleep 3 && docker ps -a
CONTAINER ID   IMAGE     COMMAND     CREATED         STATUS                              PORTS     NAMES
fd4319261a0d   busybox   "sleep 3"   4 seconds ago   Exited (0) Less than a second ago             sample

If the container, the program is running in, is shut down, it's more or less as if you would pull the plug of your computer. Nothing will run on your computer any more. It's impossible.
I would encourage you to create some test scenarios yourself and validate this.


text:
Q: What is "contents: write" permission in GitHub workflow? Recently I've faced an issue https://github.com/kkohtaka/gh-actions-pr-size/issues/9 that has a possible solution as adding contents: write permission to my job:
permissions:
   contents: write
   ...

I've tried to find an explanation for it in https://docs.github.com/en/actions/using-jobs/assigning-permissions-to-jobs but found only supported values like contents: read|write|none.
What is contents: write permission in GitHub workflow? What does it give?

A: The token permissions are based on the GitHub App permission model.
You can refer to the overview for the GitHub App contents permission.


text:
Q: Using thread for interrupting from keyboard I want to make a keyboard interrupt to exit a while loop. Instead of using _getchar() or cin inside the while loop, which wait for the user input, I want to find a way that allows for an optional keyboard interrupt: the loop should continue indefinitely until the user decides to stop it.
For this goal, creating threads could help, but I am very new into the topic. I implemented this in this example code. I use C++ Visual Studio 2019 in Windows.
#include <iostream>  // std::cout
#include <thread>    // std::thread

int exitWhile = 0;
void interrupt()
{
    std::cin >> exitWhile;   // Get "exitWhile" from keyboard
}

int main()
{
    std::thread t(interrupt); // Spawn new thread

    while (exitWhile != 1)  // If keyboard input is "1", exit while loop
    {
       std::cout << "Inside while loop" << std::endl;
       t.join();
    }

std::cout << "Exit while.\n";

return 0;
}

However, the while loop is executed one first time and then waits for the thread "t" to be finished because of the join() function. I would like to run the thread in parallel such that the global variable gets modified at any time, until which the while loop will keep repeating. Any ideas on how to implement this behavior?

A: Dont join in the loop. If you manage to get your thread to change the variable in main(you will probably need to pass it a pointer to exitWhile, also look into atomic variables which are thread safe). Then you need to join after the while loop just to close the thread. Even if this did loop through once, it would fail on second loop as thread t has already been joined.
so first check if thread is joinable, and then join it(after it has served its purpose, so outside the loop). And with threads that dont end normally(a socket thread perhaps) you need to also shut them down first since join doesent end the thread, just makes the code execute in the main thread again.


text:
Q: Incorrect Syntax Near SET. Expecting EXTERNAL I'm trying to check if a stored procedure exists, and then if it doesn't, create it.
I'm getting the error

Incorrect Syntax Near SET. Expecting EXTERNAL

Code:
IF (NOT EXISTS (SELECT *
             FROM INFORMATION_SCHEMA.ROUTINES
             WHERE ROUTINE_SCHEMA = 'dbo'
             AND  ROUTINE_NAME = 'ELMAH_GetErrorXml'))
BEGIN
    CREATE PROCEDURE [dbo].[ELMAH_GetErrorXml]
    (
        @Application NVARCHAR(60),
        @ErrorId UNIQUEIDENTIFIER
    )
    AS

        SET NOCOUNT ON

        SELECT
            [AllXml]
        FROM
            [ELMAH_Error]
        WHERE
            [ErrorId] = @ErrorId
        AND
            [Application] = @Application
END

A: You got that error because that is not the right for checking the existence of a object(procedure) and if not exists then creating it . try something like this.
IF NOT EXISTS (SELECT *
               FROM   sys.objects
               WHERE  object_id = Object_id(N'[dbo].[ELMAH_GetErrorXml]')
                      AND type IN ( N'P', N'PC' ))
  BEGIN
      EXEC('CREATE PROCEDURE [dbo].[Elmah_geterrorxml] (@Application NVARCHAR(60),
                                                        @ErrorId     UNIQUEIDENTIFIER)
            AS
              BEGIN
                  SET NOCOUNT ON

                  SELECT [AllXml]
                  FROM   [ELMAH_Error]
                  WHERE  [ErrorId] = @ErrorId
                         AND [Application] = @Application
              END')
  END

But the simple way is
IF EXISTS (SELECT *
           FROM   INFORMATION_SCHEMA.ROUTINES
           WHERE  ROUTINE_SCHEMA = 'dbo'
                  AND ROUTINE_NAME = 'ELMAH_GetErrorXml')
  BEGIN
      DROP PROCEDURE [dbo].[Elmah_geterrorxml]
  END

GO

CREATE PROCEDURE [dbo].[Elmah_geterrorxml] (@Application NVARCHAR(60),
                                            @ErrorId     UNIQUEIDENTIFIER)
AS
  BEGIN
      SET NOCOUNT ON

      SELECT [AllXml]
      FROM   [ELMAH_Error]
      WHERE  [ErrorId] = @ErrorId
             AND [Application] = @Application
  END

A: SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF EXISTS (SELECT 1 FROM sys.objects where name = 'ELMAH_GetErrorXml' and type ='P')
Drop Procedure [dbo].[ELMAH_GetErrorXml]
Go

CREATE PROCEDURE [dbo].[ELMAH_GetErrorXml]
(
@Application NVARCHAR(60),
@ErrorId UNIQUEIDENTIFIER
)
AS

SET NOCOUNT ON

SELECT
    [AllXml]
FROM
    [ELMAH_Error]
WHERE
    [ErrorId] = @ErrorId
AND
    [Application] = @Application

END

GO
SET QUOTED_IDENTIFIER OFF
GO
 SET ANSI_NULLS ON
 GO

A: Try the following:
CREATE OR ALTER PROCEDURE usp_SomeProcedure
AS
SELECT
'procedure created'


text:
Q: FMX Component style not showing correctly in IDE Below are the sources to a very simple FMX component that simply inherits from a TCustomEdit but with a different Style. What I am going for is to have two buttons on the Windows version of the component and no buttons on the Android component.
When I compile the sources before and run a program with the component, both devices show the components as expected. Windows shows the two buttons, Android doesn't display the buttons.
My problem is, during design time in the IDE, setting the "Style" drop down to Android, the component is displayed using the Windows version. If I "edit the default style" when the Android style is selected, it shows the Edit "background" with a sourcelookup of "Windows 10 Desktopstyle.png", not "AndroidL Lightstyle.png" but also includes the buttons with a sourcelookup of "AndroidL Lightstyle.png".
My assumption is I am missing something is my component design that tells the IDE which version of style to use. Any idea what that is? FYI: this is a very simple component that shows the problem. My more complicated component has the same problem.
unit RHEdit;

interface

uses
  System.SysUtils, System.Classes, FMX.Types, FMX.Controls, FMX.Controls.Presentation, FMX.Edit, FMX.Controls.Model;

type
  TRHEdit = class(TCustomEdit)
  private
    { Private declarations }
  protected
    function GetStyleObject(const Clone: Boolean): TFmxObject; override;
    function DefinePresentationName: string; override;
  public
    { Public declarations }
  published
    property Text;
  end;

procedure Register;

implementation

{$IFDEF ANDROID}
  {$R RHEdit_android.res}
{$ENDIF}
{$IFDEF MSWINDOWS}
  {$R RHEdit_win.res}
{$ENDIF}

uses System.Types, FMX.Styles;

procedure Register;
begin
  RegisterComponents('Samples', [TRHEdit]);
end;

{ TRHEdit }

function TRHEdit.DefinePresentationName: string;
begin
  Result := 'RHEdit-' + GetPresentationSuffix;
end;

function TRHEdit.GetStyleObject(const Clone: Boolean): TFmxObject;
var
  style: string;
begin
  style := 'rheditstyle';
  if (StyleLookup = '') then
    Result:= TStyleStreaming.LoadFromResource(HInstance, Style, RT_RCDATA)
  else
    Result := inherited GetStyleObject(Clone);
end;

end.

RHEdit_android.rc
RHEditStyle RCDATA "RHEdit_android.style"

RHEdit_win.rc
RHEditStyle RCDATA "RHEdit_win.style"

RHEdit_android.style
  object TLayout
    StyleName = 'rheditstyle'
    TabOrder = 12
    FixedHeight = 32
    object TActiveStyleObject
      StyleName = 'background'
      Align = Contents
      SourceLookup = 'AndroidL Lightstyle.png'
      ActiveTrigger = Focused
      ActiveLink = <
        item
          CapInsets.Left = 4.000000000000000000
          CapInsets.Right = 4.000000000000000000
          SourceRect.Left = 94.000000000000000000
          SourceRect.Top = 63.000000000000000000
          SourceRect.Right = 127.000000000000000000
          SourceRect.Bottom = 95.000000000000000000
        end
        item
          CapInsets.Left = 6.000000000000000000
          CapInsets.Right = 6.000000000000000000
          Scale = 1.500000000000000000
          SourceRect.Left = 157.000000000000000000
          SourceRect.Top = 95.000000000000000000
          SourceRect.Right = 206.000000000000000000
          SourceRect.Bottom = 143.000000000000000000
        end
        item
          CapInsets.Left = 8.000000000000000000
          CapInsets.Right = 8.000000000000000000
          Scale = 2.000000000000000000
          SourceRect.Left = 187.000000000000000000
          SourceRect.Top = 122.000000000000000000
          SourceRect.Right = 253.000000000000000000
          SourceRect.Bottom = 186.000000000000000000
        end
        item
          CapInsets.Left = 12.000000000000000000
          CapInsets.Right = 12.000000000000000000
          Scale = 3.000000000000000000
          SourceRect.Left = 337.000000000000000000
          SourceRect.Top = 190.000000000000000000
          SourceRect.Right = 436.000000000000000000
          SourceRect.Bottom = 286.000000000000000000
        end>
      SourceLink = <
        item
          CapInsets.Left = 4.000000000000000000
          CapInsets.Right = 4.000000000000000000
          SourceRect.Left = 94.000000000000000000
          SourceRect.Top = 30.000000000000000000
          SourceRect.Right = 127.000000000000000000
          SourceRect.Bottom = 62.000000000000000000
        end
        item
          CapInsets.Left = 6.000000000000000000
          CapInsets.Right = 6.000000000000000000
          Scale = 1.500000000000000000
          SourceRect.Left = 157.000000000000000000
          SourceRect.Top = 45.000000000000000000
          SourceRect.Right = 206.000000000000000000
          SourceRect.Bottom = 93.000000000000000000
        end
        item
          CapInsets.Left = 8.000000000000000000
          CapInsets.Right = 8.000000000000000000
          Scale = 2.000000000000000000
          SourceRect.Left = 187.000000000000000000
          SourceRect.Top = 57.000000000000000000
          SourceRect.Right = 253.000000000000000000
          SourceRect.Bottom = 121.000000000000000000
        end
        item
          CapInsets.Left = 12.000000000000000000
          CapInsets.Right = 12.000000000000000000
          Scale = 3.000000000000000000
          SourceRect.Left = 337.000000000000000000
          SourceRect.Top = 93.000000000000000000
          SourceRect.Right = 436.000000000000000000
          SourceRect.Bottom = 189.000000000000000000
        end>
      TouchAnimation.Link = <>
    end
    object TLayout
      StyleName = 'content'
      Align = Client
      Locked = True
      Margins.Left = 32.000000000000000000
      Margins.Top = 4.000000000000000000
      Margins.Right = 32.000000000000000000
      Margins.Bottom = 4.000000000000000000
      Size.Width = 0.000000000000000000
      Size.Height = 42.000000000000000000
      Size.PlatformDefault = False
    end
    object TColorObject
      StyleName = 'caretcolor'
      Color = xFF222222
    end
    object TBrushObject
      StyleName = 'foreground'
      Brush.Color = xFF222222
    end
    object TBrushObject
      StyleName = 'selection'
      Brush.Color = x7F33B5E5
    end
    object TFontObject
      StyleName = 'font'
      Font.Size = 18.000000000000000000
    end
  end

RHEdit_win.style
object TLayout
    StyleName = 'rheditstyle'
    TabOrder = 16
    object TActiveStyleObject
      StyleName = 'background'
      Align = Contents
      SourceLookup = 'Windows 10 Desktopstyle.png'
      ActiveTrigger = Focused
      ActiveLink = <
        item
          CapInsets.Left = 7.000000000000000000
          CapInsets.Top = 7.000000000000000000
          CapInsets.Right = 7.000000000000000000
          CapInsets.Bottom = 7.000000000000000000
          SourceRect.Left = 266.000000000000000000
          SourceRect.Top = 81.000000000000000000
          SourceRect.Right = 305.000000000000000000
          SourceRect.Bottom = 110.000000000000000000
        end
        item
          CapInsets.Left = 10.000000000000000000
          CapInsets.Top = 10.000000000000000000
          CapInsets.Right = 10.000000000000000000
          CapInsets.Bottom = 10.000000000000000000
          Scale = 1.500000000000000000
          SourceRect.Left = 399.000000000000000000
          SourceRect.Top = 121.000000000000000000
          SourceRect.Right = 457.000000000000000000
          SourceRect.Bottom = 165.000000000000000000
        end
        item
          CapInsets.Left = 14.000000000000000000
          CapInsets.Top = 14.000000000000000000
          CapInsets.Right = 14.000000000000000000
          CapInsets.Bottom = 14.000000000000000000
          Scale = 2.000000000000000000
          SourceRect.Left = 532.000000000000000000
          SourceRect.Top = 162.000000000000000000
          SourceRect.Right = 610.000000000000000000
          SourceRect.Bottom = 220.000000000000000000
        end>
      SourceLink = <
        item
          CapInsets.Left = 7.000000000000000000
          CapInsets.Top = 7.000000000000000000
          CapInsets.Right = 7.000000000000000000
          CapInsets.Bottom = 7.000000000000000000
          SourceRect.Left = 225.000000000000000000
          SourceRect.Top = 81.000000000000000000
          SourceRect.Right = 264.000000000000000000
          SourceRect.Bottom = 110.000000000000000000
        end
        item
          CapInsets.Left = 10.000000000000000000
          CapInsets.Top = 10.000000000000000000
          CapInsets.Right = 10.000000000000000000
          CapInsets.Bottom = 10.000000000000000000
          Scale = 1.500000000000000000
          SourceRect.Left = 337.000000000000000000
          SourceRect.Top = 121.000000000000000000
          SourceRect.Right = 396.000000000000000000
          SourceRect.Bottom = 165.000000000000000000
        end
        item
          CapInsets.Left = 14.000000000000000000
          CapInsets.Top = 14.000000000000000000
          CapInsets.Right = 14.000000000000000000
          CapInsets.Bottom = 14.000000000000000000
          Scale = 2.000000000000000000
          SourceRect.Left = 450.000000000000000000
          SourceRect.Top = 162.000000000000000000
          SourceRect.Right = 528.000000000000000000
          SourceRect.Bottom = 220.000000000000000000
        end>
      TouchAnimation.Link = <>
    end
    object TLayout
      StyleName = 'content'
      Align = Client
      Locked = True
      Margins.Left = 21.000000000000000000
      Margins.Top = 4.000000000000000000
      Margins.Right = 21.000000000000000000
      Margins.Bottom = 4.000000000000000000
      Size.Width = 0.000000000000000000
      Size.Height = 42.000000000000000000
      Size.PlatformDefault = False
    end
    object TButton
      StyleName = 'minusbutton'
      Align = Left
      CanFocus = False
      Cursor = crArrow
      Margins.Left = 2.000000000000000000
      Margins.Top = 2.000000000000000000
      Margins.Right = 2.000000000000000000
      Margins.Bottom = 2.000000000000000000
      Position.X = 2.000000000000000000
      Position.Y = 2.000000000000000000
      Size.Width = 20.000000000000000000
      Size.Height = 46.000000000000000000
      Size.PlatformDefault = False
      StyleLookup = 'spinbottombutton'
    end
    object TButton
      StyleName = 'plusbutton'
      Align = Right
      CanFocus = False
      Cursor = crArrow
      Margins.Left = 2.000000000000000000
      Margins.Top = 2.000000000000000000
      Margins.Right = 2.000000000000000000
      Margins.Bottom = 2.000000000000000000
      Position.X = 28.000000000000000000
      Position.Y = 2.000000000000000000
      Size.Width = 20.000000000000000000
      Size.Height = 46.000000000000000000
      Size.PlatformDefault = False
      StyleLookup = 'spintopbutton'
    end
    object TBrushObject
      StyleName = 'foreground'
      Brush.Color = claBlack
    end
    object TBrushObject
      StyleName = 'selection'
      Brush.Color = x7F2A96FF
    end
    object TFontObject
      StyleName = 'font'
    end
  end
end


text:
Q: Removing two object from nsmutablearray I have a NSMutableArray with five objects. I want to remove two objects when a certain condition is fulfilled. But it is giving me an error-----* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[NSMutableArray objectAtIndex:]: index 3 beyond bounds [0 .. 2]'
  Here is my code
  -(IBAction)buttonPressed1:(id)sender{
for (int i = 0; i < [objectArray1 count]; i++) {

    if ([[objectArray1 objectAtIndex:3] isEqualToString:@"xyz"])
    {

        NSMutableIndexSet *indexes = [NSMutableIndexSet indexSetWithIndex:3];
        [indexes addIndex:4];
        [objectArray1 removeObjectsAtIndexes:indexes];
        NSLog(@"Hello %@",objectArray1 );
  }
}

IF I remove for{} condition it is working fine. Any help will be appreciated.

A: If you want to remove the objects at indexes 3 and 4, as you seem to be doing here, then don't do it inside a loop. You are taking your array of 5 objects and removing the last 2 objects in it the first time through the loop, leaving you with 3 objects in your array. The next time through your loop you are running the same check on the item at array index 3, and the array no longer has that index because you've deleted it.

A: It seems you are going through the loop 4 times.
If the condition is true, the conditional code is going to be executed 4 times.
You create an index 4.
You remove it.
The second time you remove it, you get a crash.
If I understood correctly what you want to do, this is the code:
if ([[objectArray1 objectAtIndex:3] isEqualToString:@"xyz"] &&
   objectArray1.count == 5) {
   NSMutableIndexSet *indexes = [NSMutableIndexSet indexSetWithIndex:3];
   [indexes addIndex:4];
   [objectArray1 removeObjectsAtIndexes:indexes];
   //less code:
   //[objectArray1 removeLastObject];
   //[objectArray1 removeLastObject];
}


text:
Q: ExtJs Table layout border missing and cell color I am trying to design a simple risk assessment matrix in ExtJs but facing two problems.

*

*border is missing for the cells with combobox in it.

*I want to set the whole cell background red. not just a part of it.

Please look at this fiddle for better explanation.

A: For border you need to use config tdAttrs and for change background color of particular cell you need to use cellCls
In this Fiddle, I have created a demo using your code and used tdAttrs and cellCls.
CODE SNIPPET
Ext.create('Ext.TabPanel', {

    name: 'myContainer',
    id: 'myContainer',

    renderTo: Ext.getBody(),
    items: [{
        title: 'Assessment',
        name: 'assessmentPanel',
        id: 'assessmentPanel',
        layout: {
            type: 'table',
            tdAttrs: {
                style: {
                    border: '1px solid #ccc'
                }
            },
            // The total column count must be specified here
            columns: 5
        },
        defaults: {
            // applied to each contained panel
            bodyStyle: 'padding:30px',
            html: 'Risk',
            scroll: false,
            //border: true

            //margin: '0 15 0 0'
        },
        items: [{
            html: 'Risk',
            //cellCls: 'first-row',
            listeners: {
                afterrender: function (view) {
                    console.log('view config entered!!');
                    //this.up('view').addCls('first-row');
                    //view.addCls('first-row');
                }
            }

        }, {
            html: 'Consequence'
        }, {
            html: 'Likelihood'
        }, {
            width: 20,
            cellCls: 'noborder'
        }, {
            html: 'Risk'
        }, {
            html: 'Service Interruption'
        }, {
            xtype: 'combobox',
            name: 'assessment1',
            id: 'assessment1',
            cellCls: 'demo',
            queryMode: 'local',
            displayField: 'text',
            valueField: 'value',
            editable: false,
            cls: 'bg-trasparent',
            value: 'red',
            store: Ext.create('Ext.data.Store', {
                data: [{
                    text: 'Red',
                    value: 'red'
                }, {
                    text: 'Gray',
                    value: 'gray'
                }, {
                    text: 'Green',
                    value: 'green'
                }, {
                    text: 'Yellow',
                    value: 'yellow'
                }, {
                    text: 'Blue',
                    value: 'blue'
                }]
            }),
            listeners: {
                select: function (combo, record) {
                    combo.el.dom.closest('td').style.background = record.get('value')
                }
            }
        }, {
            html: 'Cell F content'
        }, {
            width: 20,
            cellCls: 'noborder'
        }, {
            html: 'Cell F content'
        }, {
            html: 'Revenue Growth'
        }, {
            xtype: 'combobox',
            name: 'assessment2',
            id: 'assessment2',
            value: 'Minor',
            width: 130,
            queryMode: 'local',
            displayField: 'text',
            valueField: 'value',
            editable: false,
            store: Ext.create('Ext.data.Store', {
                data: [{
                    text: 'Minor',
                    value: 'minor'
                }, {
                    text: 'Moderate',
                    value: 'moderate'
                }, {
                    text: 'Major',
                    value: 'major'
                }, {
                    text: 'Severe',
                    value: 'severe'
                }]
            })
        }, {
            html: 'Cell F content'
        }, {
            width: 20,
            cellCls: 'noborder'
        }, {
            html: 'Cell F content'
        }, {
            html: 'Reputation'
        }, {
            xtype: 'combobox',
            name: 'assessment3',
            id: 'assessment3',
            value: 'Minor',
            width: 130,
            queryMode: 'local',
            displayField: 'text',
            valueField: 'value',
            editable: false,
            store: Ext.create('Ext.data.Store', {
                data: [{
                    text: 'Minor',
                    value: 'minor'
                }, {
                    text: 'Moderate',
                    value: 'moderate'
                }, {
                    text: 'Major',
                    value: 'major'
                }, {
                    text: 'Severe',
                    value: 'severe'
                }]
            })
        }, {
            html: 'Cell F content'
        }, {
            width: 20,
            cellCls: 'noborder'
        }, {
            html: 'Cell F content'
        }, {
            html: 'Legal and Compliance'
        }, {
            xtype: 'combobox',
            name: 'assessment4',
            id: 'assessment4',
            value: 'Minor',
            width: 130,
            queryMode: 'local',
            displayField: 'text',
            valueField: 'value',
            editable: false,
            store: Ext.create('Ext.data.Store', {
                data: [{
                    text: 'Minor',
                    value: 'minor'
                }, {
                    text: 'Moderate',
                    value: 'moderate'
                }, {
                    text: 'Major',
                    value: 'major'
                }, {
                    text: 'Severe',
                    value: 'severe'
                }]
            })
        }, {
            html: 'Cell F content'
        }, {
            width: 20,
            cellCls: 'noborder'
        }, {
            html: 'Cell F content'
        }, {
            html: 'Capital Items'
        }, {
            xtype: 'combobox',
            name: 'assessment5',
            id: 'assessment5',
            value: 'Minor',
            width: 130,
            queryMode: 'local',
            displayField: 'text',
            valueField: 'value',
            editable: false,
            store: Ext.create('Ext.data.Store', {
                data: [{
                    text: 'Minor',
                    value: 'minor'
                }, {
                    text: 'Moderate',
                    value: 'moderate'
                }, {
                    text: 'Major',
                    value: 'major'
                }, {
                    text: 'Severe',
                    value: 'severe'
                }]
            })
        }, {
            html: 'Cell F content'
        }, {
            width: 20,
            cellCls: 'noborder'
        }, {
            html: 'Cell F content'
        }, {
            html: 'Financial'
        }, {
            xtype: 'combobox',
            name: 'assessment6',
            id: 'assessment6',
            value: 'Minor',
            width: 130,
            height: 5,
            queryMode: 'local',
            displayField: 'text',
            valueField: 'value',
            editable: false,
            store: Ext.create('Ext.data.Store', {
                data: [{
                    text: 'Minor',
                    value: 'minor'
                }, {
                    text: 'Moderate',
                    value: 'moderate'
                }, {
                    text: 'Major',
                    value: 'major'
                }, {
                    text: 'Severe',
                    value: 'severe'
                }]
            })
        }, {
            html: 'Cell F content'
        }, {
            width: 20,
            cellCls: 'noborder'

        }, {
            html: 'Cell F content'
        }, {
            height: 20,
            cellCls: 'noborder'
        }, {
            height: 20,
            cellCls: 'noborder'
        }, {
            height: 20,
            cellCls: 'noborder'
        }, {
            width: 20,
            height: 20,
            cellCls: 'noborder'
        }, {
            height: 20,
            cellCls: 'noborder'
        }, {
            html: 'Highest Risk'
        }, {
            html: 'Minor'
        }, {
            html: 'Cell F content'

        }, {
            width: 20,
            cellCls: 'noborder'
        }, {
            html: 'Cell F content'
        }]
    }]
});

CSS CODE


text:
Q: FormData not sending appended file I'm making a Javascript app for file uploading with Drag and Drop support - but I've hit a problem I've been stuck on for days.
It seems that 'dropped' files (in my case via jQuery, .on('drop', function(e){) files aren't actually being sent.
I've been browsing answer after answer on StackOverflow - PLEASE DON'T MARK AS DUPLICATE. THE DUPLICATES DO NOT HELP - I'm yet to find an aspect which I have not considered in my implementation. It's as if this solution is working for everyone else but me...
Don't believe me?
FIDDLE HERE
(Disclaimer: obviously I have modified my solution to not use cross-domain requests, I am using an endpoint I found on Fiddle as a substitute, but it appears to present the same problem I have been experiencing - hopefully it is sufficient as the basis for this example)
The issue is that the upload completes immediately - apparently it is only sending the text data and not uploading the file itself. Reviewing the request payload I see the data is not present.

Javascript
function uploadFile(file){
  console.log("uploadFile");
  var form = new FormData();
  form.append('file', file);
  form.append('hello', 'world');
  $.ajax({
    url: "/echo/js/?js=hello%20world!",
    type: "POST",
    data: form,
    processData: false,
    contentType: false,
    cache: false,
    success: function(data){
      alert("SUCCESS");
    }
  });
}
$(document).ready(function(){

  /* Disable default drag/drop browser behavior. */
  $("html").on('drop', function(e){e.preventDefault(); e.stopPropagation();});
  $("html").on('dragover', function(e){e.preventDefault(); e.stopPropagation();});
  $("html").on('dragenter', function(e){e.preventDefault(); e.stopPropagation();});
  $("html").on('dragleave', function(e){e.preventDefault(); e.stopPropagation();});

  $(".drop_area").on('drop', function(e){
    e.preventDefault();
    e.stopPropagation();
    var files = e.originalEvent.target.files || e.originalEvent.dataTransfer.files;
    console.log(files);
    for (var i = 0; i < files.length; i++) {
      uploadFile(files[i])
    }
  });
});

HTML
<div class='drop_area'>
Drop your file in this div.
</div>

CSS
.drop_area {
  border: 1px solid black;
  background: #ffffff;
  height: 300px;
  width: 50%;
  position: relative;
}

A: After seeing the blank request headers in Chrome, and based on the fast upload speed, I had assumed the files were not sending.
However after adding code to my backend endpoint (via var_dump($_FILES['file']);), I see the following:
array(5) {
  ["name"]=>
  string(14) "two-minute.mp4"
  ["type"]=>
  string(9) "video/mp4"
  ["tmp_name"]=>
  string(36) "/Applications/MAMP/tmp/php/phpXfCu0U"
  ["error"]=>
  int(0)
  ["size"]=>
  int(12904619)
}

The large size attribute appears to indicate quite a lot of data was availible from my upload. It was probably working the whole time. I'll look at this more tomorrow but for the moment the answer may be that:
"It just looks like it's not working from your browser, but it actually is...".
Partial credit to @Alisher Gafurov for convincing me to double-check the backend implementation to verify if the file was indeed not present.

A: I was with the same problem, here I needed to update my php.ini file to increase the value of the config upload_max_filesize.


text:
Q: Remove elements from Array Perl How to remove matching elements from the array? Let say I have array @A [1, 2, 2, 3, 4, 4, 4, 5] and now I have remove element 2 and 3 so I should see @A [ 1, 4, 4, 4, 5] only in the array.

A: You can use grep to filter out elements you don't want:
my @A    = (1, 2, 2, 3, 4, 4, 4, 5);
my @newA = grep { $_ != 2 } @A;
# @newA has elements (1,3,4,4,4,5)


text:
Q: Каким будет значение переменной result после выполнения следующего кода? Почему ответ 5,25?
т.е почему (x + True) = 21, а (4 - y * False) = 4?
x = 20
y = 5
result = (x + True) / (4 - y * False)

A: True = 1
False = 0

Поэтому
4 - y * False = 4 - y * 0 = 4 - 5 * 0 = 4
x + True = 20 + 1 = 21

Ну и 21 / 4 = 5.25


text:
Q: Extract rows from dataframe containing each label In the example dataframe shown below, I have 5 labels (class_name).  There are 31 files (31 rows) in all to work with...
I am attempting to extract 80% (can be variable) of the rows (= 24 rows (integer)).  However, I wanted to ensure that I extract at least 1 row from each class_name
For my attempt, I can only do this manually.  This approach gets tedious as the class_name is much more that 10.  Can you assist me in extracting the correct % rows to contain at least 1 entry from each label (class_name).
Here is my attempt:
import math
import pandas as pd

base_path = 'G:/PandasFileSeperation'
original_df = pd.read_csv(f'{base_path}/Book2.csv')

original_df = original_df.astype(str)
length = original_df.class_name.count()
length

# Get number of groups
dfg = original_df.groupby('class_name')
numgroups = dfg.ngroups
numgroups

# Get the sizes of each group
group_size =  original_df.groupby('class_name').size()

# Get length of original dataframe
Total_dataset_size = len(original_df)

# Get number of Training samples
TrainPercent = 0.80

Train_size = int(Total_dataset_size * TrainPercent)
Train_size

# How can I change this to automatically change the label size length to give at least 1 row from each class?
Label_0_size = 5
Label_1_size = 3
Label_2_size = 7
Label_3_size = 7
Label_4_size = 2

# Training Dataset
label_percent = { 'pigs' : Label_0_size, 'goats' : Label_1_size, 'chickens' : Label_2_size, 'hens' : Label_3_size, 'sheep' : Label_4_size}

flag = True
for label, num_rows in label_percent.items():

  row_num = num_rows

  if label == 'pigs':
    row_num0 = Label_0_size
    df = original_df[original_df['class_name'] == label]
    df = df.head(row_num0)

  elif label == 'goats':
    row_num2 = Label_1_size
    df = original_df[original_df['class_name'] == label]
    df = df.head(row_num1)

  elif label == 'chickens':
    row_num2 = Label_2_size
    df = original_df[original_df['class_name'] == label]
    df = df.head(row_num2)

  elif label == 'hens':
    row_num3 = Label_3_size
    df = original_df[original_df['class_name'] == label]
    df = df.head(row_num3)

  else:
    row_num4 = Label_4_size
    df = original_df[original_df['class_name'] == label]
    df = df.head(row_num4)

  if flag == True:
    Train_df = df
    flag = False
  else:
    Train_df = pd.concat([Train_df, df])

Train_df.to_csv(f'{base_path}/Train_df.csv', encoding='utf-8')

Dataframe:

slice_file_name
fsID
start
end
salience
fold
classID
class_name
original_class

1-1000020520400.wav

1
1
pigs

1-100004024000001.wav

1
1
pigs

1-10000406050001.wav

1
1
pigs

1-1000050120400.wav

1
1
pigs

1-1000050320400.wav

1
1
pigs

1-1000050520400.wav

1
2
goats

1-10000601400001000.wav

1
2
goats

1-1000060340000.wav

1
2
goats

1-100006070500.wav

1
3
chickens

1-100007020800.wav

1
3
chickens

1-100007024000001.wav

1
3
chickens

1-1000070320400.wav

1
3
chickens

1-100007050800.wav

1
3
chickens

1-100007064000001.wav

1
3
chickens

1-100010620400.wav

1
3
chickens

1-100040620400.wav

1
3
chickens

1-10006020500.wav

1
3
chickens

1-10006030500.wav

1
3
chickens

1-100060520400.wav

1
4
hens

1-10007020500.wav

1
4
hens

2-100070420400.wav

1
4
hens

2-100070540000.wav

1
4
hens

2-1313131313004.wav

1
4
hens

2-1313131313043.wav

1
4
hens

2-1313131313044.wav

1
5
sheep

2-150002020500.wav

1
5
sheep

2-150002060800.wav

1
5
sheep

2-150004022040001.wav

1
5
sheep

2-15000406050001.wav

1
5
sheep

2-150006014000001.wav

1
5
sheep

2-150006024000001.wav

1
5
sheep

As a starting, can we do a forloop and start with each class = 1 then increment each class, checking the sum after each iteration until the total classes = Train_size?

A: I think this should help. Sample the dataframe twice: Once using groupby to sample one row for each name, then sample from the rest of the dataframe randomly to complete the 80% training set.
TrainPercent = 0.8
# sample one row for each class_name (5 rows)
one_each = df.groupby('class_name').sample(n=1)
# from the rest of the rows, sample int(0.8*len(df))-len(one_each) number of rows (19 rows)
rest = df.loc[~df.index.isin(one_each.index)].sample(n=int(TrainPercent*len(df))-len(one_each))
# concatenate the two
res = pd.concat([one_each, rest])


text:
Q: Why ajax calls error function, if I add this code? I have jquery script, it posts some data to servlet. Script calls success function, if servlet has only one string of code - response.getWriter().print("message");. If I try to set response content type or flush output stream, anything else, script calls error function. Why?
Here is code of script
$(document).ready(function () {
        $("#login-button").click(function () {
            var userPassword = $("input#userPassword").val();
            var userLogin = $("input#userLogin").val();
            $.ajax({
                type: "POST",
                url: "login",
                dataType: "text",
                data: {login: userLogin, password: userPassword},
                success: function (data) {
                    alert("Successful request! Data is " + data.toString());
                },
                error: function (jqXHR) {
                    console.log(jqXHR);
                }
            });
        });
    });

Result of console.log(jqXHR) if I add any code to servlet is always the same - Object {readyState: 0, responseText: "", status: 0, statusText: "error"}.
Here is code of servlet
public class LoginServlet extends HttpServlet {

  public static final Logger LOGGER = Logger.getLogger(LoginServlet.class);

  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        LOGGER.info("Start calling safe service");
        safeService(request,response);
        LOGGER.info("End calling safe service");
    } catch (Exception e) {
        LOGGER.info("Error while processing loginServlet ",e);
        LOGGER.error("Error while processing loginServlet ",e);
    }

  }

  protected void safeService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    // If I add this code, script calls error function
    /*response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");*/

    response.getWriter().print("welcome.html");

    // Or even this code.
    /*response.getWriter().flush();
    response.getWriter().close();*/
  }

}

Log is clean, there is not any of runtime exception.


text:
Q: Convert a Sql query with group by clause and/or aggregate function into linq to sql? I have a table Auditing logins, I'd like to just extract the latest login for each user, which the below sql accomplishes.
How would I format the sql query into a linq to sql query?
SELECT * FROM AuditTable adt1
    inner join UserTable usr
        on adt1.[UserName] = usr.[User_Id]
WHERE [TimeStamp] = ( SELECT MAX([TimeStamp])
                      FROM AuditTable adt2
                      WHERE adt1.UserName = adt2.UserName)

Another way of writing the query in sql being;
SELECT adt1.[UserName], usr.First_Name, max([TimeStamp]) as [TimeStamp]
FROM AuditTable adt1
    INNER JOIN UserTable usr
        on adt1.[UserName] = usr.[User_Id]
GROUP BY adt1.[UserName] ,usr.First_Name

A: query #2:
from adt1 in dc.AuditTable
join usr in dc.UserTable on adt1.UserName == usr.UserID
group adt1 by adt1.username int ag
select new { UserName = ag.Key, TSMax = ag.Max(ts => adt1.TimeStamp) }
Why the join to the user table? Filter?

A: I got it working... the answer was to use the let keyword.
as an aside I highly recommend using LinqPad when trying to work these things out.
from adt in AuditTable
    join usr in UserTable
        on adt.UserName equals usr.User_Id
group adt by
    new { adt.UserName, adt.Roles, usr.First_Name, usr.Last_Name }
into g
let LastAccessed = g.Max(a => a.TimeStamp)
select new
    { UserName = g.Key.UserName,
      Roles = g.Key.Roles,
      FirstName = g.Key.First_Name,
      LastName = g.Key.Last_Name,
      TimeStamp = LastAccessed
    }


text:
Q: How to determine how much of a table is generated? If I'm generating a table from a slow function, like this:
foo = Table[SuperSlowExpression, {1000}]

is there a way to determine after submission (so it is too late to instrument the call) to find out how many values already have been generated (so that when it takes longer than expected I can find out whether to wait a bit longer or to abort the calculation)?
So is there still a way to get at the information? Note that there is no iteration variable in the call which I could read.
Optimally, I'd also want to get the already calculated values, of course.
Edit:
Since this seems to have been consistently overlooked:
This is about a calculation which is already running. It is no longer possible to make changes to the call of Table or to the expression inside.

A: Similar, with a progress bar:
tEnd = 10;
ProgressIndicator[Dynamic[i], {0, tEnd}]
Table[Pause[1]; i, {i, tEnd}]

A: Suppose you're evaluating something slightly different:
Table[Pause[0.1](*SuperSlowExpression*), {i, 1000}]

You can create a cell containing i, and use Evaluation > Evaluate in Subsession to see the current value of i without interrupting the main evaluation.  In the case where you don't have an iterator variable to inspect, then the question is whether there is some state or property in your SuperSlowExpression that could be evaluated to get an idea of how much progress has been made.

A: If you're using a function that doesn't use iterators such as Scan or Fold you could consider using PrintTemporary, for example
f[x_] := (Pause[2]; Sin[x]);
res = {};
Module[{i = 0, temp},
  Scan[(NotebookDelete[temp];
    temp = PrintTemporary[++i];
    AppendTo[res, f[#]]) &, Range[20]]]

A: Yes, there is.  You can use Monitor
Monitor[
  Table[Pause[1]; i, {i, 10}],
  i
]

Some explanations
Table uses dynamic scoping to localize its variable (i in this case), just like Block. This means that while Table is evaluating, i has a "global" value that one can inspect even from outside the Table if we interrupt the evaluation.
On way of interrupting the evaluation is to request i's value on the pre-emptive link (i.e. using Dynamic expressions) We could just put Dynamic[i] somewhere and it would count up just like Manipulate while the Table is evaluating.
Another way of interrupting the evaluation is through entering a Dialog:  You can use the Evaluation -> Interrupt evaluation... menu item, choose Enter subsession. You will get a prompt where you can inspect the kernel state (including the value of i, Stack[], etc.).  Evaluate Return[] to resume he evaluation.
I have been using both of these techniques extensively to monitor very lengthy evaluations.  The second one even seems to work for parallel evaluations, and least in those cases where I tried it.
Iteration variable and already calculated values
If there is no iteration variable in the Table, just insert one, and use Table[..., {i, 1000}].  Then we can use Monitor or Dynamic[i].
It is not possible to get the already calculated values.  If you want to do this (it would often be desirable to be able to!), you need to implement your own version of Table.  I asked about how to implement an interruptible parallel Table or Map in this question.  The solution I got does not allow inspecting the so far calculated results, but it lets me interrupt the calculation, and continue from where I stopped later.
A table function that allows monitoring partial results
As an example, I provide a custom table function that allows monitoring the partial results.
Try evaluating
Dynamic[table`Results[]]
table[Pause[1]; i^2, {i, 10}]

``tableResults[] could be used in Monitor too.
I am using a linked list to collect the results for better performance than what AppendTo would give. I cannot use Sow/Reap here because they don't allow inspecting the partial results (at least I am not aware of this being possible).
Note: If you use nested tables, only the inner one can be monitored, but all of them will work correctly.

The code:
ClearAll[table, table`result, table`Results]
SetAttributes[table, HoldAll]

table`result = {};

table[expr_, iterator__] :=
 Block[{table`result, table`elem},
  table`result = {};
  Do[
   table`result = {table`result, table`elem[expr]},
   iterator
   ];
  table`Results[]
  ]

table`Results[] := Block[{table`res, table`elem},
  table`res = Flatten[table`result];
  table`elem = Identity;
  table`res
  ]

A: Given your current situation, there is another option that might help if you have set "Enable notebook history tracking" in Preferences > Advanced:

Then, you go to Cell > Notebook history and navigate to your currently evaluating cell and look at the time stamp when you last edited it. Chances are that you edited it just prior to evaluating (note that if you open an old notebook and execute the cell right away, this might not work, because the last edit timestamp will not be what you want it to be).

Now find the current time from your system clock. Assuming you know how long it takes for one evaluation of SuperSlowExpression, you can now simply do:
$$\mathrm{approx\ progress=\frac{current\ time - last\ edited\ time}{time\ for\ one\ evaluation}}$$
This will give you a rough estimate of the progress — enough to make a decision whether to wait a bit longer or to give up.
Remember, this should be a last ditch option! There are many ifs and buts here, but seeing as all the other options require an iterator and you don't have one (and your Table is running), it's worth trying...


text:
Q: Solr sort on latest upcoming timestamp value on multivalued field I have a multivalued field for session timings of groups in timestamp. e.g. session_timings: [1526882026, 1513882026, 1533882026 ]. My sorting logic is the groups should be listed sorted based on their upcoming session time.
For example, Group A has three session_timings = [1, 2, 5]. And Group B also has three session_timings = [1, 6, 7]. If current timestamp is 3, then Group A should come first because next session for Group A is on 5, whereas for Group B its 7. Is this possible with solr sorting? Or do I have to use another way to do this? Any help would be great.


text:
Q: Testing STI Associations with Shoulda-Matchers & FactoryGirl I am having issues with getting a simple STI shoulda-matcher spec to pass correctly.
Here are the associations..
class User < ActiveRecord::Base
end

class Provider < ActiveRecord::Base
    belongs_to :practice_manager, class_name: 'User', foreign_key: :user_id
end

class PracticeManager < User
    has_many :providers
end

..and my factories..
FactoryGirl.define do
    sequence(:email) { |n| "person#{n}@email.com" }
    sequence(:password) { |p| "thepassword123" }
    sequence(:password_confirmation) { |p| "thepassword123" }

    factory :user do
        email
        password
        password_confirmation
    end

    factory :practice_manager, parent: :user, class: 'PracticeManager' do
    end

    factory :provider_user, parent: :user, class: 'ProviderUser' do
    end

    factory :provider do
        sequence(:first_name) { |n| "Sally#{n}" }
        sequence(:last_name) { |n| "Harmon#{n}" }
        sequence(:npi) { |n| n.to_s.rjust(10, '0')}
        sequence(:sf_contact_ident) { |s| s.to_s.rjust(15, '0') }
        practice_manager
    end
end

..as well as the test I am trying to get to pass.
require 'rails_helper'

RSpec.describe PracticeManager, type: :model do
    describe "Relationships" do
        it { should have_many(:providers).class_name('User').with_foreign_key(:user_id) }
    end
end

One thing I found is that I can get the test to pass if I add the class_name: 'User', foreign_key: :user_id to the has_many side of the association, but I'm afraid it's a false positive. It doesn't seem right.
Any suggestions are highly appreciated.

A: I think you're mixing your associations up.
To test the has_many within your PracticeManager model, you simply want:
RSpec.describe PracticeManager, type: :model do
  describe "Relationships" do
    it { should have_many(:providers) }
  end
end

If you want to test your Provider model, then you'd need the extra options:
RSpec.describe Provider, type: :model do
  it { should belong_to(:practice_manager).class_name('User').with_foreign_key(:user_id) }
end


text:
Q: Make server accept connections only from Android app I would like to know if there is any way to make my hosting only accept connections from my App, and reject the connections from any web browser.

A: The best approach is probably going to be to use SSL with client certificates.  This will give you authentication as well as encryption.
You're probably familiar with using SSL via HTTPS to secure your web browser when you pay for something online.  The process is similar except that the server has to also be configured to require a client-side certificate.  In Apache, this is a setting called SSLVerifyClient.  This will force the web server to require a certificate from the client and then to verify it as valid.
Assigning client-side certificates from a root authority like Verisign can be expensive, so you probably want to generate your own.  You can do this using OpenSSL.
Once you have a client certificate, you have to copy the certificate into your application storage on the device.  Then you can use the Keystore object to open it.  Once it's open, you can associate it with your HTTP requests when you use the HttpUrlConnection object.
Since you'll probably generate your own certificate instead of using those from a root authority, you will need to setup a TrustManager in your Android app to accept your self-signed certificates and associate that with the HttpUrlConnection when you make the request.
That's the general strategy and that should be enough to get you started.  If you get stuck on something specific, try asking individual questions about the separate parts.  The Apache and OpenSSL part would probably be better posted on Server Fault.
Here are some links for the server-side stuff:
Client certificates with apache
Client-authenticated_TLS_handshake
Here are links for the Android development:
HTTPS with Client Certificates on Android
android-ssl
FakeX509TrustManager (useful during development)
It looks like all you need are in those links, but I'll summarize the Android code here.  Note that I don't have a test environment for this, so the code is incomplete and untested.  Again, this is just to get you started.
// open the certificate
keyStore = KeyStore.getInstance("PKCS12");
fis = new FileInputStream(certificateFile);
keyStore.load(fis, clientCertPassword.toCharArray());

// create the SSL context
KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
kmf.init(keyStore, clientCertPassword.toCharArray());
KeyManager[] keyManagers = kmf.getKeyManagers();

TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(trustStore);
TrustManager[] trustManagers = tmf.getTrustManagers();

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, null);

// perform the HTTP request
String result = null;
HttpURLConnection urlConnection = null;

try {
    URL requestedUrl = new URL(url);
    urlConnection = (HttpURLConnection) requestedUrl.openConnection();
    if(urlConnection instanceof HttpsURLConnection) {
        ((HttpsURLConnection)urlConnection)
             .setSSLSocketFactory(sslContext.getSocketFactory());
    }
    urlConnection.setRequestMethod("GET");
    urlConnection.setConnectTimeout(1500);
    urlConnection.setReadTimeout(1500);
    lastResponseCode = urlConnection.getResponseCode();
    result = IOUtil.readFully(urlConnection.getInputStream());
    lastContentType = urlConnection.getContentType();
} catch(Exception ex) {
    result = ex.toString();
} finally {
    if(urlConnection != null) {
        urlConnection.disconnect();
    }
}


text:
Q: Best Linear Predictor Assumptions Chapter 6 of Plane Answers to Complex Questions, 4th Edition motivates linear regression through the lens of best prediction. Unfortunately, I'm confused about some assumptions in deriving the best linear predictor.
It's not too hard to show $\hat y(x):=\mathbb E[y|x]$ is the best predictor with respect to the mean squared error, but since this is hard to compute in general, the author restricts attention to a linear approximation of $\hat y(x)$. The linear approximation only requires knowledge of means, variances, and covariances of $x$ and $y$.
Let $V_{xx}:=\text{cov}(x)$ and $V_{xy}:=\text{cov}(x,y)$. The author starts,

Let $\beta_*$ be a solution to $V_{xx}\beta=V_{xy}$, then we will show that the function
  $$
\mu_y+(x-\mu_x)^\top\beta_*
$$
  is the best linear predictor of $y$ based on $x$.

Why is the initial line "Let $\beta_*$ be a solution to $V_{xx}\beta=V_{xy}$" required? This implies $\mathscr C(V_{xy})\subseteq\mathscr C(V_{xx}),$ but I don't see what this provides.

A: You can show this with a little bit of algebra. Because the statement,
$y = \mu_y + (x - \mu_x)^\top\beta$ $\hspace{1cm}$(1)
can be easily written in a way that gives $V_{xx}\beta = V_{xy}$.
 From (1), we have
$E[(x-\mu_x)(y - \mu_y)] = E[(x - \mu_x)(x - \mu_x)^\top]\beta$ $\hspace{1cm}$(2)
and the rest follows by construction. In other words, solving the optimization with constraint (1) is identical with solving the optimization with constraint (2). It's just a matter of which one you want to use to frame your problem.


text:
Q: Sending email without actually signing in to gmail account from flutter app I want to send user an email on order confirmation.  For this I'm using mailer 3.2.1 package.
https://pub.dev/packages/mailer
At below line in below code snippet, I'm getting prompt that saying 'gmail' is deprecated and shouldn't be used. Favor gmailUserXoauth2 as username/password is considered a Less-Secure-Apps.
       final smtpServer = gmail(username, password);

After replacing gmail with gmailUserXoauth2 in above line, I get The method 'gmailUserXoauth2' isn't defined
Below is the code snippet
String username = 'xxx@gmail.com';
String password = 'xxx';

       final smtpServer = gmail(username, password);
                      // Create our message.
                      final message = Message()
                        ..from = Address(username, 'Your name')
                        ..recipients.add('destination@example.com')
                        ..ccRecipients.addAll(
                            ['destCc1@example.com', 'destCc2@example.com'])
                        ..bccRecipients.add(Address('bccAddress@example.com'))
                        ..subject =
                            'Test Dart Mailer library ::  :: ${DateTime.now()}'
                        ..text =
                            'This is the plain text.\nThis is line 2 of the text part.'
                        ..html =
                            "
Test
\n
Hey! Here's some HTML content
";

                      try {
                        final sendReport = await send(message, smtpServer);
                        print('Message sent: ' + sendReport.toString());
                      } on MailerException catch (e) {
                        print('Message not sent.');
                        for (var p in e.problems) {
                          print('Problem: ${p.code}: ${p.msg}');
                        }
                      }

Upon googling this issue I have come across this solution.
https://stackoverflow.com/a/58732280/7290043
This solution gives suggest following

*

*Enable "Access for less secure apps" to use Gmail without OAuth 2.0

*Sign in with Google account using the google_sign_in package and then send email

But I don't want to do either of these. I dont want to send email after signing in to google with google_sign_in package
What do I do now?

A: You can follow the guide here. User login is needed for authentication for emails to be sent from the Flutter app. XOAUTH2 is used in the sample code provided in the guide, it redirects users to a login page for authentication.


text:
Q: Parallelization Of Insertion Sort With openMP, compared to serial version, gives very spiky results Context
Hello!
I was finishing up a slight hands on experience with POSIX pthreads, and OpenMP, trying to compare the both with the serial implementation of Insertion Sort, trying to see which one performs well on what kind of inputs.
The results I got were weird to say the least.
Maybe it could be that my code is buggy. I would say that my pthread implementation sure is and needs a lot of more work since it's a very lousy implementation. However, taking a look at the time it took for OpenMP and Serial, I saw very weird trends.
Code
Before I show you the graph of the time taken that I got, here is the code for each.
For Serial,

static inline void *
insertionSort(void *arrayMetaDataToUnpack)
{
    // UNPACK START
    ull *_Array = ((InsertionSortPacking *)arrayMetaDataToUnpack)->Array;
    size_t sizeOfArray = ((InsertionSortPacking *)arrayMetaDataToUnpack)->ArraySize;
    // UNPACK END

    // Compulsory use of reinterpret_cast to keep everything consistent
    ull *__tempArray = reinterpret_cast<ull *>(_Array);

    for (int i = 1; i < sizeOfArray; i++)
    {
        int __temp = __tempArray[i];
        int j = i - 1;

        while (j >= 0 && __temp <= __tempArray[j])
        {
            __tempArray[j + 1] = __tempArray[j];
            j = j - 1;
        }

        {
            __tempArray[j + 1] = __temp;
        }
    }

    return __tempArray;
}
static inline void *
insertionSort(void *arrayMetaDataToUnpack)
{
    // UNPACK START
    ull *_Array = ((InsertionSortPacking *)arrayMetaDataToUnpack)->Array;
    size_t sizeOfArray = ((InsertionSortPacking *)arrayMetaDataToUnpack)->ArraySize;
    // UNPACK END

    // Compulsory use of reinterpret_cast to keep everything consistent
    ull *__tempArray = reinterpret_cast<ull *>(_Array);

    for (int i = 1; i < sizeOfArray; i++)
    {
        int __temp = __tempArray[i];
        int j = i - 1;

        while (j >= 0 && __temp <= __tempArray[j])
        {
            __tempArray[j + 1] = __tempArray[j];
            j = j - 1;
        }

        {
            __tempArray[j + 1] = __temp;
        }
    }

    return __tempArray;
}

The OpenMP implementation,
static inline void *
openmp_insertionSort(void *arrayMetaDataToUnpack)
{
    // UNPACK START
    ull *_Array = ((InsertionSortPacking *)arrayMetaDataToUnpack)->Array;
    size_t sizeOfArray = ((InsertionSortPacking *)arrayMetaDataToUnpack)->ArraySize;
    // UNPACK END

    // Compulsory use of reinterpret_cast to keep everything consistent
    ull *__tempArray = reinterpret_cast<ull *>(_Array);

#pragma omp for
    for (int i = 1; i < sizeOfArray; i++)
    {
        int __temp = __tempArray[i];
        int j = i - 1;

        while (j >= 0 && __temp <= __tempArray[j])
        {
            __tempArray[j + 1] = __tempArray[j];
            j = j - 1;
        }

#pragma omp critical
        {
            __tempArray[j + 1] = __temp;
        }
    }

    return __tempArray;
}

Again, disclaimer, I'm new to OpenMP, and I might have parallelized the code well, but this is all I know at a beginner stage to use it. It does do the sorting well, without race conditions.
Inputs
So for the inputs, they were,
    const int INPUTSIZE = 25;

    int inputSizes[INPUTSIZE] = {1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000,
                                5500, 6000, 6500, 7000, 7500, 8000, 8500, 9000, 9500,
                                10000, 10500, 11000, 11500, 12000, 12500, 13000};

My program generates a csv file after using clock_t to find the time taken by each method for each input.
Graph
The final graph I got was generated by the csv file mentioned above, it looks like this

Where,

*

*X axis is the input size

*Y axis is the time taken in seconds

*Serial is the serial implementation

*Pthread is the pthread implementation

*OpenMP is the openMP implementation

*Time Taken ... is the time taken for my program to generate an inputSize[i] sized array

Machine Details

*

*Measured time by using the below logic,

    clock_t __start = clock();

    Array = functionName((void *)&packingMetadata);

    clock_t __end = clock();

    double __inputTimeUsed = ((double)(__end - __start)) / CLOCKS_PER_SEC;
    std::cout << "Overall time taken, using " << printStatement << __inputTimeUsed << ".\n";

Where functionName is a function pointer to either the serial version, pthread version, or openmp version. packingMetaData is the packing data as a struct being passed to it, which consists of a pointer to an array created in main() and the array size

*

*Measurements to reduce noise ... not sure what exactly that means

*Compilation command is g++ -std=gnu++17 -std=c++17 insertion.cpp -o insertion -lpthread

*Compiler is g++

*Machine info,
Linux Kernel Version: 5.4.0-47-generic
OS Type: 64-bit
Processors: 8 × Intel® Core™ i7-8665U CPU @ 1.90GHz
Memory: 15.5 GiB of RAM
Problems / Questions
My pthread implementation is bad, got it, that's my fault and can be improved.
What about the OpenMP implementation? Why does that happen? Why are the outputs so zig zagged?
So the things I wanted to ask were many, but mainly,

*

*Why the spikes and randomness? And

*How do I go on seeing how a parallel implementation can be improved further?

A:
Maybe it could be that my code is buggy. [...]. It does do the sorting well, without race conditions.

Actually, yes, you should check results more closely as an insertion sort cannot be parallelized by just adding an omp for and an omp critical. The current code is not working correctly as the insertion can generate wrong results.
Let us make a step back to understand why it is not so simple. Indeed, we try to insert multiple element in parallel. However, insertion require moving element of the array that are greater. Moving the elements can be hardly done in parallel (actually, not efficiently). Putting the while loop in a critical section will make the all sort sequential. So we need to find another way to parallelize the code. More precisely, we need to find independent work that can run in parallel.
One solution is to look for the position of the element to insert in parallel, then perform a barrier, and then move the element in parallel. However, this solution is not very efficient, especially for small array (due to over-synchronizations and and small work-granularity).
A much better solution would be to divide (virtually) the array in N parts, then perform an independent insertion sorts on each parts in parallel, then make a barrier, and finally merge the sorted arrays.
Note that insertion sorts is generally not efficient compared to other algorithm like quick sort or merge sort on quite-big data. If you aims to reach high performance,  it is probably wise to directly implement a parallel quick/merge sort (or even better: a parallel introsort).


text:
Q: How to find records are exist or not from table in mysql table I want to fetch records from first table & check that records are exist in second table or not:
tbl_user

userid      email
-------------------------
1       abc@gmail.com
2       abcd@gmail.com
3       abedd@yahoo.com
4       xyz@gmail.com
5       test@ymail.com

tbl_user_responce

id      responce_email
-------------------------
1       abc@gmail.com
2       abcd@gmail.com
3       abc@yahoo.com
4       xyz@gmail.com
5       abcd@ymail.com

UPDATE
Note: In my secord table email is stored in xml format like following:
<?xml version="1.0" encoding="UTF-8"?>
<user>
<userinfo>
<email>stevemartin148@gmail.com</email>
<status>1</status>
<description>Success</description>
</userinfo>
</user>

i want to fetch those records that are not exist in tbl_user_responce from tbl_user
So from above records i want result like
Email
-----
abedd@yahoo.com
test@ymail.com

Does anybody know how to manage that?
Thanks in advance.

A: How about something like
SELECT  *
FROM    tbl_user
WHERE   NOT EXISTS (
                        SELECT  1
                        FROM    tbl_user_responce
                        WHEREN  tbl_user.email = tbl_user_responce.responce_email
                    )

Or even something like
SELECT  tbl_user.*
FROM    tbl_user LEFT JOIN
        tbl_user_responce ON    tbl_user.email = tbl_user_responce.responce_email
WHERE   tbl_user_responce.responce_email IS NULL

A: The query you're asking for won't use any indexes, but this would seem to do the job as long as there's only one email per "responce";
SELECT email
FROM tbl_user
WHERE email NOT IN (
  SELECT SUBSTRING_INDEX(
           SUBSTRING_INDEX(responce_email,'<email>', -1),
         '</email>',1)
  FROM tbl_user_responce;
)

From the "I'd do an SQLfiddle if it weren't down" dept.


text:
Q: My bash script's if / then check is always evaluating to true I was trying to write a bash script to handle a conditional switch, and it kept evaluating to true every time. So, I stripped it down to this, and I was getting the same behavior of it always echoing whatever parameter I sent it instead of only when sending it -c:
myfunc(){
if [[ $1 == "-c" ]];
  then
    echo $1
  fi
}

A: While I can't answer why this was always evaluating to true, I was able to fix it. I ended up having to remove the quotes from the switch, thus making the working version look like this:
myfunc(){
if [[ $1 == -c ]];
  then
    echo $1
  fi
};

Per Darth Android's suggestion, just keep the quotation marks consistent between the two comparisons, which is safer.
myfunc(){
if [[ "$1" == "-c" ]];
  then
    echo $1
  fi
};


text:
Q: run some script when session end in Yii 1 My session configuration in config file (main.php) is:
'session' => array(
    'class' => 'CDbHttpSession',
    'timeout' => 60*60, // 1 hour
),

And I put this code in layout file:
<?php if (!Yii::app()->user->isGuest) { ?>
    <meta http-equiv="refresh" content="<?php echo Yii::app()->params['session_timeout'];?>;"/>
<?php } ?>

So far, there are no announcement when the session end. When I refresh the browser, the session is already end.
After session (or almost) expired, I want to tell user that the session is going to expire like countdown timer dialog or something.
I have tried this extension http://www.yiiframework.com/extension/timeout-dialog/. but it didn't work for my website with the configuration. The extension show the dialog when the session is 1 minute left, but when I clicked the button to resume the session, it didn't work because the session still running. I know it  because when I refresh the browser, the session is already expired.
So, what I must do?
At least, I want to know how to get the remaining time of the session when browser refreshed, so I can modified the announcement by myself.
thanks :)

A: I think I solved the problem by myself.
Here the explanation:
It's important to be known that Session works on server. When browser accessing to server, session timeout will be restarted. There are no ways to know the remaining time of the session.
So, to warn user that session will expire must be handled in client with javascript or jQuery. I created handlers that will warn user when the website idle (no activities) or when the session timeout is almost expired. User will be warned by a confirmation dialog that asks to user whether would keep sign in or log out. When user decide to keep sign in, client will do ajax to do whatever-script in server (because that will restarted the session timeout).
Because my Yii website using bootstrap 3, So the dialog panel that I create will use bootstrap code.
This is in view layout:

<button id='tombolmodal' style="display:none" type="button" class="btn btn-info btn-lg" data-backdrop="static" data-keyboard="false" data-toggle="modal" data-target="#myModal">Open Large Modal</button>

                   ATTENTION!

                    It seems you are in inactive

                     seconds left to logout your account

            <?php $this->widget('booster.widgets.TbButton',
                array(
                    'buttonType' => 'ajaxSubmit',
                    'context' => 'primary',
                    'label' => 'Keep Sign In',
                    'url' => CController::createUrl('site/keepalive'),
                    'ajaxOptions' => array(
                        'type' => 'GET',
                    ),
                    'htmlOptions' => array(
                        "data-dismiss"=>"modal",
                        'id'=>'staysignin',
                    )
                )
            );
            ?>
            <?php $this->widget('booster.widgets.TbButton',
                array(
                    'context' => 'default',
                    'label' => 'Logout',
                    'htmlOptions' => array(
                        "data-dismiss"=>"modal",
                        "id"=>"forcelogout"
                    )
                )
            );
            ?>

And this is my SiteController:
public function actionKeepalive()
{
    if(Yii::app()->request->isAjaxRequest){
        Yii::app()->session->open();
    }
}

public function actionLock($id)
{
    $user = User::model()->findByPk($id);
    Yii::app()->user->logout();
    $this->render('lock', array( //refers to lockscreen page
        'user'=>$user,
    ));
}

And don't forget to write the code from my question above.
That code worked very well in my website.

This code is still have a weakness. When you log in with same account in different browser, they are not related to each other. they are independent. So, if the session in first browser has expired, the session in other browser may not expired yet or even has already expired earlier.
You can also see the implementation in Yii2 from this link: http://www.hafidmukhlasin.com/2014/10/01/yii2-create-lock-screen-web-application-with-javascript/
Thanks. Correct me if I wrong


text:
Q: Uneven Distribution in rand() ( C language )
I wanted to see if there is any way to generate random numbers with uneven distribution which I would like to customize.
for example:
In 100 generated numbers I would like to have :
10 A
20 B
40 C
10 D
15 E
5  F

And I wanted to say that I'm new to programming so try to help me with your simple answers.
Really Really Thank You.

A: This is a pretty simple, yet often highly effective solution for problems like this:
char *samples = "AABBCCDDEEFFFFF";

char randomSample() {
  return sample[rand() % strlen(samples)];
}


text:
Q: Queue-ing image paths for later upload I'm having difficulties keeping track of my queue and uploading them at a later moment.
The upload image is a asynctask and in the postexecute a mail is going out to send the uploaded picture.
This is my UploadImage AsyncTask. I think i'm doing way too difficult and that it can be done much easier than it is right now.
private class UploadImageTask extends AsyncTask<Void, Void, Integer> {
    ProgressDialog dialog;

    /**
     * Private integer which counts how many times we've tried to upload the
     * Image.
     */
    private int _counter = 0;

    private List<String> imageUploadList = new ArrayList<String>();

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if(AppStatus.haveNetworkConnection(_context)){
            if(isPhotoTaken()){
                dialog = new ProgressDialog(Step4.this);
                dialog.setCancelable(false);
                dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                dialog.setMessage(getString(R.string.uploadingMessage));
                dialog.setTitle(getString(R.string.uploadingTitle));
                dialog.show();
            }
        }
    }

    protected Integer doInBackground(Void... params) {
        init();
        postData();
        return null;
    }
    public void init(){
        _counter = 0;
        _beenHere = true;
        for(String path : imageUploadList){
            Debug.out("Path: "+path);
        }
    }
    public void postData() {
        if (isPhotoTaken()) {
            if(AppStatus.haveNetworkConnection(_context)){
                if(_beenHere){
                    ImageUploader.uploadFile(getPhotoPath(),
                            "http://obo.nl/android-upload-image.php", Step4.this);
                } else {
                    for(String path : imageUploadList){
                        Debug.out(path);
                        ImageUploader.uploadFile(path,
                                "http://obo.nl/android-upload-image.php", Step4.this);
                    }
                }
            } else {
                if (_counter == 0) {
                    _counter++;
                    _activity.runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(_context,
                                    getString(R.string.noInternetImageNotUploaded),
                                    Toast.LENGTH_LONG).show();
                        }
                    });
                    imageUploadList.add(getPhotoPath());
                }
                try {
                    if(_beenHere){
                        _beenHere = false;
                        goToNextIntent();
                    }
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                postData();
            }
        }
    }

    private void goToNextIntent(){
        Intent intent = new Intent(Step4.this, Step5.class);
        intent.putExtra(EXTRA_MESSAGE, (Serializable) _user);
        intent.putExtra(EXTRA_MESSAGE2, _isRepairable);
        intent.putExtra(EXTRA_MESSAGE3, _injury);
        intent.putExtra(EXTRA_MESSAGE4, _category);
        intent.putExtra(EXTRA_MESSAGE5, _inch);
        intent.putExtra(EXTRA_MESSAGE6, _size);
        startActivity(intent);
    }
    protected void onPostExecute(Integer result) {
        if(isPhotoTaken()){
            if(dialog != null){
                dialog.dismiss();
            }
        }
        mailing(_isRepairable);
        new MyAsyncTask().execute(_mail);
    }
}

The line:
if(AppStatus.haveNetworkConnection(_context))

returns a boolean true if the user has a working internet connection. false otherwise.
What I want is to queue all the image paths (and mails sent afterwards) in the desired ArrayList so i can send them all at a later moment when the user has a working internet Connection. Please help me out!

A: You could store your image paths in a list (or something similar) and persist the list, let's say in Shared Preferences. As you finish uploading a picture, you will remove it from that list and  continue to the next one, and so on until your list is empty.
While uploading, if the internet connection drops it will not affect you, you will always have persisted the list of images that are still to be uploaded.
Register a broadcast receiver to listen for wi-fi connection, when it gets connected it could automatically continue the upload - this is just a suggestion.


text:
Q: What is Web SQL Database int max value? In Web SQL Database, what is a int max value?
(exactly in Safari on iOS 7)
I didn't find anything in docs: http://www.w3.org/TR/webdatabase/

A: Currently all implementations of web-sql use SQLite (says Wikipedia and the spec says "User agents must implement the SQL dialect supported by Sqlite 3.6.19").
SQLite's maxint value is 2^63-1 = 9223372036854775807


text:
Q: Can a CoroutineWorker schedule another worker? I would like to schedule another job with a worker. But, I couldn't find in the doc if that is allowed or not.
Something like:
class MyWorker(context: Context, params: WorkerParameters): CoroutineWorker(context, params) {

    override val coroutineContext = Dispatchers.IO

    override suspend fun doWork(): Result = coroutineScope {
        val syncWorker = OneTimeWorkRequestBuilder<MyWorker>()
            .setInitialDelay(3000, TimeUnit.MILLISECONDS)
            .build()

        WorkManager.getInstance(context)
            .enqueueUniqueWork("MyJob", ExistingWorkPolicy.REPLACE, syncWorker)
        Result.success()
    }

A: Yes you can, with one exception.
The only case that can be dangerous is if you are enqueuing an unique worker with a ExistingWorkPolicy.REPLACE from an instance of the same worker (taking your example, you cannot reschedule the work from the same syncWorker):
class syncWorker(context: Context, params: WorkerParameters): CoroutineWorker(context, params) {

    override suspend fun doWork(): Result {
        withContext(Dispatchers.IO) {
            val syncWorker = OneTimeWorkRequestBuilder<MyWorker>()
                .build()

            // DON'T DO THIS!!!
            // You may end up with two instances of the same worker
            // running at the same time
            WorkManager.getInstance(context)
                .enqueueUniqueWork("MyJob", ExistingWorkPolicy.REPLACE, syncWorker)
            Result.success()
        }
    }
}

Also note that coroutineContext is now deprecated. Use instead withContext(Dispatchers.IO) like show in my snippets.