text:
Q: C# - System.Windows.Forms.Clipboard.GetDataObject() doesnt response Why doesn't System.Windows.Forms.Clipboard.GetDataObject() return when calling it from a different thread and before the main thread stops, after calling System.Windows.Forms.Clipboard.Clear() within the main thread?
I have written a sample program to explain my question:
public class ClipboardDemo
{
    [STAThread]
    public static void Main(string[] args)
    {
        Thread.CurrentThread.Name = "MAIN_THREAD";

        Thread clipboardViewerThread = new Thread(RunClipboardViewer);
        clipboardViewerThread.Name = "CLIPBOARD_VIEWER_THREAD";
        clipboardViewerThread.SetApartmentState(ApartmentState.STA);

        Thread clipboardClearerThread = new Thread(RunClipboardClearer);
        clipboardClearerThread.Name = "CLIPBOARD_CLEARER_THREAD";
        clipboardClearerThread.SetApartmentState(ApartmentState.STA);

        Console.WriteLine("Starting " + clipboardViewerThread.Name + ", expecting initial WM_DRAWCLIPBOARD message...");
        clipboardViewerThread.Start();
        Thread.Sleep(1000);

        Console.WriteLine("Clearing clipboard from " + clipboardClearerThread.Name + ", expecting WM_DRAWCLIPBOARD message...");
        clipboardClearerThread.Start();
        clipboardClearerThread.Join();

        Console.WriteLine("Clearing clipboard from " + Thread.CurrentThread.Name + ", expecting WM_DRAWCLIPBOARD message...");
        Clipboard.Clear();
        Thread.Sleep(1000);

        Application.Exit();
        Console.WriteLine("\t" + Thread.CurrentThread.Name + " stopped!");
    }

    private static void RunClipboardViewer()
    {
        ClipboardViewer viewer = new ClipboardViewer();
        viewer.ViewClipboard();
        viewer.Dispose();
    }

    private static void RunClipboardClearer()
    {
        Clipboard.Clear();
    }
}

internal class ClipboardViewer : NativeWindow, IDisposable
{
    private const int WM_CREATE = 0x0001;
    private const int WM_DRAWCLIPBOARD = 0x0308;
    private const int WM_CHANGECBCHAIN = 0x030D;

    private IntPtr nextViewer;

    public void ViewClipboard()
    {
        base.CreateHandle(new CreateParams());
        Application.Run();
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        switch (m.Msg)
        {
            case WM_CREATE:
                nextViewer = User32Interop.SetClipboardViewer(base.Handle);
                break;
            case WM_DRAWCLIPBOARD:
                if (nextViewer != IntPtr.Zero)
                {
                    User32Interop.SendMessage(nextViewer, WM_DRAWCLIPBOARD, m.WParam, m.LParam);
                }
                Console.WriteLine("\tClipboard changed in " + Thread.CurrentThread.Name + ". Trying to receive data object...");
                Clipboard.GetDataObject();
                Console.WriteLine("\tData object received!");
                break;
            case WM_CHANGECBCHAIN:
                if (m.WParam == nextViewer)
                {
                    nextViewer = m.LParam;
                }
                else if (nextViewer != IntPtr.Zero)
                {
                    User32Interop.SendMessage(nextViewer, WM_CHANGECBCHAIN, m.WParam, m.LParam);
                }
                break;
        }
    }

    private void Dispose(bool disposing)
    {
        if (disposing)
        {
            User32Interop.ChangeClipboardChain(base.Handle, nextViewer);
        }
        base.DestroyHandle();
    }

    ~ClipboardViewer()
    {
        Dispose(false);
    }
}

internal static class User32Interop
{
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr SetClipboardViewer(IntPtr hWndNewViewer);

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern bool ChangeClipboardChain(IntPtr hWndRemove, IntPtr hWndNewNext);
}

The formatted output of this is:
Starting CLIPBOARD_VIEWER_THREAD, expecting initial WM_DRAWCLIPBOARD message...
  Clipboard changed in CLIPBOARD_VIEWER_THREAD. Trying to receive data object...
  Data object received!

Clearing clipboard from CLIPBOARD_CLEARER_THREAD, expecting WM_DRAWCLIPBOARD message...
  Clipboard changed in CLIPBOARD_VIEWER_THREAD. Trying to receive data object...
  Data object received!

Clearing clipboard from MAIN_THREAD, expecting WM_DRAWCLIPBOARD message...
  Clipboard changed in CLIPBOARD_VIEWER_THREAD. Trying to receive data object...
  MAIN_THREAD stopped!
  Data object received!

As you can see in the last three lines, System.Windows.Forms.Clipboard.GetDataObject() returns when the main thread stops, but not earlier. Is there a solution for this problem?

A: You are doing it right, selecting STA for the worker threads and having them pump a message loop.  Except in one: your main thread.  It pumps only by accident.  The Thread.Join() call makes the CLR pump.  But Thread.Sleep() doesn't pump.  You can arbitrarily replace it with this and fix your problem:
    var dummy = new AutoResetEvent(false);
    dummy.WaitOne(1000);

But that's a hack.  I realize this is just a test app, think about what your real one is going to look like.


text:
Q: Memory leak in system library I have been working with iPhone application in which I am using sqlite database. I have checked memory leaks in iPad,iPhone 4 and there is none. But the same code shows a memory leak in iPhone-3GS. So:

*

*If I click on a leak reference, it will show me an unavailable message.

*If I check Hide system library option, it doesn't show me a leak.

I think the following images are enough to understand my question.

redpajama_set_name: RedPajamaStackExchange


text:
Q: New Command for placing 2 figures next to each other Is it possible to code a new command, which use the path of 2 figures with \includegraphics, and positions them next to each other and generates a box around them? One figure should be titled as "False" and the other one as "Correct". I'm using these to improve my script at university and would like to automate this procedure.

A: There are many ways of doing it, and many ways to interpret your specification. The following solution should at least help to say more precisely what you want to have differently.

\documentclass{article}
\usepackage{graphicx}
\newcommand\twofigures[2]{%
  \fbox{%
    \begin{tabular}{@{}cc@{}}
      \includegraphics[width=0.45\textwidth]{#1}
      & \includegraphics[width=0.45\textwidth]{#2}\\
      False & Correct
    \end{tabular}%
  }%
}
\begin{document}
\twofigures{example-image-a}{example-image-b}
\end{document}

A: I'd like to use minipage environment to handle this.
\documentclass{article}
\usepackage{graphicx}
\usepackage{caption}
\newcommand{\TFfigures}[2]{
    \fbox{
        \begin{minipage}{.45\textwidth}
        \includegraphics[width=\textwidth]{#1}
        \captionof{figure}{False}
    \end{minipage}
    \begin{minipage}{.45\textwidth}
        \includegraphics[width=\textwidth]{#2}
        \captionof{figure}{Correct}
    \end{minipage}
    }
}
\begin{document}
    \TFfigures{example-image-a}{example-image-b}
\end{document}

which will give

If you don't want the "Figure 1", we can have a small change: use \captionof* instead of \captionof:
\documentclass{article}
\usepackage{graphicx}
\usepackage{caption}
\newcommand{\TFfigures}[2]{
    \fbox{
        \begin{minipage}{.45\textwidth}
        \includegraphics[width=\textwidth]{#1}
        \captionof*{figure}{False}
    \end{minipage}
    \begin{minipage}{.45\textwidth}
        \includegraphics[width=\textwidth]{#2}
        \captionof*{figure}{Correct}
    \end{minipage}
    }
}
\begin{document}
    \TFfigures{example-image-a}{example-image-b}
\end{document}


text:
Q: How to use maxresult and nextmarker parameter in Azure File Share List REST API I am trying to list all the shares present in Storage Account using List Share REST API (https://learn.microsoft.com/en-us/rest/api/storageservices/list-shares#Authorization). but I am having issues with Authorization header with marker parameter. I guess problem is with $stringtosign variable under $nextmarker If Statement.
$StorageAccount = "XXXXX"
$Accesskey = "XXXXXXX==";
$Version="2019-12-12"
$SharePropObj = @()
$date = [System.DateTime]::UtcNow.ToString("R",[Globalization.CultureInfo]::InvariantCulture)

$stringToSign = "GET`n`n`n`n`n`n`n`n`n`n`n`n"+
           "x-ms-date:$date`nx-ms-version:$version`n" +
           "/$storageAccount/`ncomp:list`nmaxresults:5000"
$hmacsha = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha.key = [Convert]::FromBase64String($accesskey)
$signature = $hmacsha.ComputeHash([Text.Encoding]::UTF8.GetBytes($stringToSign))
$signature = [Convert]::ToBase64String($signature)

$headers=@{"x-ms-date"=$date;
           "x-ms-version"= $version;
           "Authorization"= "SharedKey $($storageAccount):$signature";
           "ContentType"="application/xml"
}
$URI = "https://$storageAccount.file.core.windows.net/?comp=list&maxresults=5000"

Try {
    $response = Invoke-RestMethod $URI -Method 'GET' -Headers $headers

}Catch {
    "Error Occurred. $_.exception.message"
    }
If ($response){

[xml]$Result = [xml]($response -replace '',"")

    $Shareprops = $Result.EnumerationResults.ChildNodes.share | %{

        $share = $_.Name
        $Quota = $_.properties.Quota
        "$share,$Quota"
        }

        $SharePropCol = "ShareName,Quota"
        $SharePropObj += @($SharePropCol,($Shareprops | where {$_.length -gt 1})) | ConvertFrom-Csv -Delimiter ","

        $SharePropObj

   $NextMarker = $Result.EnumerationResults.NextMarker.Split("/")[-1]

   if ($NextMarker){

          #Write-Error "Data for some shares are missed"
          #$SharePropObj = @()
          $date = [System.DateTime]::UtcNow.ToString("R",[Globalization.CultureInfo]::InvariantCulture)

        $stringToSign = "GET`n`n`n`n`n`n`n`n`n`n`n`n"+
                   "x-ms-date:$date`nx-ms-version:$version`n" +
                   "/$storageAccount/`ncomp:list`nmaxresults:5000`nmarker:$NextMarker"
        $hmacsha = New-Object System.Security.Cryptography.HMACSHA256
        $hmacsha.key = [Convert]::FromBase64String($accesskey)
        $signature = $hmacsha.ComputeHash([Text.Encoding]::UTF8.GetBytes($stringToSign))
        $signature = [Convert]::ToBase64String($signature)

        $headers=@{"x-ms-date"=$date;
                   "x-ms-version"= $version;
                   "Authorization"= "SharedKey $($storageAccount):$signature";
                   "ContentType"="application/xml"
        }
        $URI = "https://$storageAccount.file.core.windows.net/?comp=list&maxresults=5000&marker=$NextMarker"

            $response1 = Invoke-RestMethod $URI -Method 'GET' -Headers $headers
            [xml]$Result = [xml]($response1 -replace '',"")

    $Shareprops = $Result.EnumerationResults.ChildNodes.share | %{

        $share = $_.Name
        $Quota = $_.properties.Quota
        "$share,$Quota"
        }

        $SharePropCol = "ShareName,Quota"
        $SharePropObj += @($SharePropCol,($Shareprops | where {$_.length -gt 1})) | ConvertFrom-Csv -Delimiter ","

        $SharePropObj

   }

    }

A: Please change the following code of yours:
1.for $NextMarker, please change this line of code
$NextMarker = $Result.EnumerationResults.NextMarker.Split("/")[-1]

to
$NextMarker = "/$storageAccount/" + $Result.EnumerationResults.NextMarker.Split("/")[-1]

*in the if ($NextMarker){} code block -> for the $stringToSign, please place the marker:$NextMarker prior to maxresults:5000. Change it like below:
$stringToSign = "GET`n`n`n`n`n`n`n`n`n`n`n`n"+
            "x-ms-date:$date`nx-ms-version:$version`n" +
            "/$storageAccount/`ncomp:list`nmarker:$NextMarker`nmaxresults:5000".

3.in the if ($NextMarker){} code block -> for $URI, please also place the marker=$NextMarker prior to maxresults=5000. Change it like below:
$URI = "https://$storageAccount.file.core.windows.net/?comp=list&marker=$NextMarker&maxresults=5000"

I have tested it and it works fine. Please let me know if you still have the issue.


text:
Q: Why does the width of affix column change while scrolling in Bootstrap? In Bootstrap I made two columns one with affix to make it fixed while scrolling and one normal column.
Here is the demo
This is my code so far:

Lorem ipsum

Lorem ipsum

If you check the demo, as soon as you scroll down, the width of the small column which has affix changes. Why is that?
Is there any idea to fix it?
Thanks

A: Because when the small column hits the top of the window, it's position property is set to fixed. If an element is fixed positioned, it is taken out of the normal flow of the page. So, it fills as much space as it need.
You have to set the width for the small column when it becomes fixed.


text:
Q: How to avoid "Property 'click' does not exist on type 'Element'.ts(2339)" error I am trying to use the below jQuery code in my Angular app, needed for a select dropdown component.
document.querySelector('.dropdown-el').click(function(e) {
  e.preventDefault();
  e.stopPropagation();
  $(this).toggleClass('expanded');
  $('#' + $(e.target).attr('for')).prop('checked', true);
});
$(document).click(function() {
  $('.dropdown-el').removeClass('expanded');
});

The issue is, that I've got a TS error: Property 'click' does not exist on type 'Element'. when trying to use it. Is there any way to avoid this one?

A: Click doesnt exist on an Element which is what is returned by the document.querySelector(). You need to cast it as an HTMLElement.

A: You need to cast your element into the HTMLElement via
let myElement: HTMLElement = document.querySelector() as HTMLElement;
myElement.click();

Hope this helps.


text:
Q: stock data to fit for Conv2D - Python tensorflow I am trying to feed stock data to Conv2D. But ran into dimension problem. I have no idea how to solve it and need help. Below are detailed steps that I have implemented.
I have attached data and code in the following link:
https://drive.google.com/drive/folders/1snsQ-96AeRn521oc0aQVlTTd9nHbtyjO?usp=sharing
by the code itself should run. It will download the data automatically. but ive taken out the featuers to simplify the run. So it will have 5 features in the attached code.
but to give you quick glance of
The Problem I had-----------------------
1. Got stock data and generated some features, it looks like:

2. Add time step to it by using:
def reshape_data(X, y, period=28):
n_past = period # number of days to look back in the past and compile into a time series
trainX = []
trainY = np.array(y.iloc[n_past:])
trainY = trainY[..., np.newaxis]
for i in range(n_past, len(X)):
    trainX.append(X[i - n_past:i, 0:X.shape[1]])
trainX = np.array(trainX)
return trainX, trainY

Note:
data can be found here
https://drive.google.com/drive/folders/1snsQ-96AeRn521oc0aQVlTTd9nHbtyjO?usp=sharing
I have applied pca on it. But simply convert it into numpy and apply reshap_data() on trainX should work
trainX, trainY = reshape_data(X_train_pca, y_train, period=30)

3. shape
trainX (5768, 30, 30) # 5768-rows, 30- time steps, 30- # of features

trainY (5768,1)

4. Add 1 axis after train X
trainX = trainX[...,np.newaxis]

trainX is now (5768, 30, 30, 1)

5. Build model

6. fit and run
model.compile(optimizer=Adam(learning_rate=0.01) , metrics="mse", loss='binary_crossentropy')

reduce_lr  = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss',factor=0.5,patience=10,verbose=0,mode='auto',min_delta=0.0002,cooldown=0,min_lr=0.0001)

early_stop = tf.keras.callbacks.EarlyStopping(monitor="val_loss", patience=80, mode="min",  restore_best_weights = True)

history = model.fit(trainX, trainY, epochs=300,
               batch_size= 512, shuffle=False, verbose = 1,
               # validation_data=(testX, testY),
               validation_split=0.2,
               callbacks=[early_stop, reduce_lr] )

7. ERROR

I thought since I have convered the stock into 30,30,1 should looks like a image dataset, which would enable tensorflow to work. But somehow it doesn't

A: Add two layers after your convolution layer:
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(1, activation='sigmoid'))

And do not mix up tensorflow.keras and keras. Rather just use tensorflow.keras for everything.


text:
Q: Как привязать звук к перелистыванию ViewPager2? Создал объект SoundPool. Загрузил в него звук. При каком-либо событии (например, нажатие кнопки) могу воспроизвести этот звук. В программе используется ViewPager2 и RecyclerView.Adapter для его подключения к данным. Мне нужно, чтобы при каждом перелистывании страницы ViewPager2 воспроизводился звук, который я уже загрузил. Я не могу понять на какое событие повесить воспроизведение для того, чтобы воспроизведение начиналось при каждом перелистывании? Или это решается как-то по-другому?

A: За перелистыванием ViewPager2 следит registerOnPageChangeCallback. Следующий код выполняет всё необходимое
viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
        @Override
        public void onPageSelected(int position) {
        super.onPageSelected(position);
            // код для выполнения
        }
    });


text:
Q: Adding subfolders in public folder of next js I am trying to create a website and it uses some files like a folder with images, I have saved these images folder in my public directory of project, it works fine on localhost, but when I try to deploy it with production setting, it cannot access those subfolders of public directory.
The issue here is that when a project is build the files of public directory is sent to _next/static/media directory but the subfolders of public directory are not added. How can I add my subfolders of public directory to media directory so I can access images in it using src='subfolder/image.png'
I tried some next js config settings, or importing the folder using import but non worked. I want my subfolders to be added into media folder after build. I don't want to use import for each file of folder.


text:
Q: Run robot keyword depending on existence of the element Is there a way to get info on whether an element exists on a page or not in Robot framework?
I would like to take one action if element exists on page, or another if element doesn't exist.
In Selenium, I would use findElements(), and that would return a list of elements, or an empty list if nothing is found.
In Robot, however, if I use Get webelements and nothing is found, test breaks with error:
ValueError: Element locator 'id=asdf' did not match any elements.

A: An approach is to get a boolean is the element in the page:
${present}=    Run Keyword And Return Status    Page Should Contain Element   ${your_locator}

, and then control the flow based on the value:
Run Keyword If    ${present}    The keyword(s) if present
                  ...  ELSE     The keyword(s) if NOT present

Instead of Page Should Contain Element you could use Element Should Be Visible.


text:
Q: How can I restore the changes to shell variable? For the purpose of an experiment...
Suppose I did this
bash="unset DISPLAY; export DISPLAY"

so I can make DISPLAY undefined. How can I restore the original value set? Or at least know what it was?

A: In general you write it down before hand.
If you're asking about this in theory, then you simply store the old value somewhere else before modifying it, then put it back whenever you want.
If you're asking about this because now you're screwed and are hoping that there's something that will bail you out, then I have bad news for you...

A: I'm not sure there's an easy way to do this (like cd - to move back and forth between most recent cd commands for instance)
What is the context of doing this .. do you want this to be available automatically? I am not aware of this as a feature of any shell.
One obvious solution would be to explicitly save the variable before you change it, and then later restore it. Using the VENDOR environment variable as an example:
$ echo $VENDOR
intel

Save the original value:
$ pre_VENDOR=$VENDOR
$ echo $pre_VENDOR
intel

Assign a new value:
$ VENDOR='Zippy'
$ echo $VENDOR
Zippy

Restore the original value:
$ VENDOR=$pre_VENDOR
$ echo $VENDOR
intel

A: You can't, there's no undo. Save the value in another variable (or in a file or wherever you like) if you want to have it available later.
old_DISPLAY=$DISPLAY
unset DISPLAY
…
DISPLAY=$old_DISPLAY

If you want to run a single command without the environment variable, use env.
env -u DISPLAY emacs

You can also use the syntax VAR=VALUE COMMAND to set the environment variable VAR to the specified value only for this one command.
$ echo $DISPLAY
:0
$ DISPLAY=:1 xterm & # shows the xterm window on display :1
$ echo $DISPLAY
:0

You can't unset a variable this way, but you can set it to an empty value, which is often good enough.
You can also keep changes local to a subshell. Parentheses delimit commands to perform in a subshell.
$ env | grep -E 'FOO|BAR'
FOO=value_of_FOO
BAR=value_of_BAR
$ (export FOO=other_value; unset BAR; env | grep -E 'FOO|BAR')
FOO=other_value
$ env | grep -E 'FOO|BAR'
FOO=value_of_FOO
BAR=value_of_BAR

You can run a separate shell with a different environment. Type exit or Ctrl+D to return to the parent shell.
$ bash
$ # change the environment, change directories, etc.
$ exit
$ # now you're back to the parent shell with its environment as you left it


text:
Q: Is this proof that $\tan a$ is transcendental correct? First, a proof that $\sin a$ is transcendental, where $a$ is algebraic not zero. Given that,
$$e^{ia}=\cos a + i\sin a$$
if $\sin a$ were algebraic, then $\cos a = \pm \sqrt{1-\sin^2a}\:$  is also algebraic, implying that
$$e^{ia}=\pm \sqrt{1-\sin^2a} + i\sin a$$
is algebraic, but $e^{ia}$ is transcendental (Lindemann theorem). Doing the same thing we can prove that $\cos a$ is transcendental.
If
$$\tan a = \frac{\sin a}{\cos a}$$
were algebraic, then $\sin a / \cos a$ is algebraic, implying that $\sin a$ and $\cos a$ are both algebraic, but this is false.
EDIT: Thanks! I get it now.

A: It is entirely possible for the quotient of transcendental numbers to be algebraic. Rather than that, you are looking for a relation like $$1+\tan^2 x=\frac1{\cos^2 x}$$

A: From
$$
\tan a = \frac{\sin a}{\cos a}
$$
we get
$$
\tan a = \frac{e^{ia} - e^{-ia}}{i(e^{ia}+e^{-ia})}
$$
Solve this for $e^{ia}$.  We conclude that $e^{ia}$ is the solution of a quadratic equation with algebraic coefficients.

A: It might be clearer if you said something like
$$\sin \alpha = \pm\sqrt{\frac{1}{1+\frac{1}{\tan^2 \alpha}}}$$
making it clearer that if  $\tan \alpha$ is algebraic then so too is $\sin \alpha$


text:
Q: Parse URL and create Links On Plain-Text Jade I am getting plain-text in which there could be a URL.
For Example
: learn abc in one day www.englishspeaking.com
Here I am having a URL. I want to convert it has a link. I am using Jade template engine. Is there a way to do this in Jade template engine.

A: Use markdown filter like this
:markdown
  this is the start of the para.
  [a link](http://example.com)
  and this is the rest of the paragraph.

A: You can use already build npm for this. Like this, I found anchrome and its also worked for me


text:
Q: Programming bsxfun at CUDA via CUBLAS or THRUST? I have a vector V that has nx1 items and a matrix M that has nxm item. I want to sum V with all the columns of M with CUDA. Is there any method in THRUST or CUBLAS that can help me to get away the problem?

A: Here What I've done with two down votes
thrust::device_vector<float> dummy_y(N,1);
alpha = 1.0f;
beta = 0.0f;
stat = cublasSger_v2(handle,K,N,&alpha,thrust::raw_pointer_cast(&dummy_y[0]),1,thrust::raw_pointer_cast(&A_sum_vec_d[0]),1,thrust::raw_pointer_cast(&C_d[0]),K);

I replicate the column vector by multiplying row vector, full of 1s, as in the size of matrix and sum with cublasSger. stat is keeping the execution status of the code and you may check for any possible error.


text: Q: Capturing single finger scroll for iframes on mobile safari Is it possible to have an iframe capture the standard (single-finger) scroll on mobile safari? I  have a javascript application that creates a large iframe intended for scrolling. It works great an standard web browsers, but requires the unintuitive two-finger scroll when using mobile Safari.


text:
Q: How to safely communicate between a JS app and an OAuth2.0 server hosted on the same domain? I know the issue of securing connexion between a JS app (let's say just 'app') and an OAuth2.0 server (let's say just 'server') is an age-old question.

However, I can not find a lot of information about the special case where the app and the server are coded by the same entity and stored at the same place (i.e. same domain, or at least, two subdomains of the same domain).
First of all, as far as the OAuth grant type is concerned, I think the right one is the Resource Owner Password Credentials Grant, since the server and the app have the same author. The issue here being that the Client ID and Client Secret are available to the user in the client. This can be dealt with either by developing a proxy on server end or by using short-life tokens and disabling CORS (if I understood correctly). Is there any other property we can take advantage of as far as security is concerned when server and app have the same author?

My second question relates to the optional use of a Facebook Login authentication (or whatever well-known app OAuth login system: Google, Twitter, etc.).
Ideally, I want users to log in using either:

*

*My-app-related credentials (if they registered without using FB login option)

*Facebook credentials (if they registered using FB login option)

The first log in method is the classical one: upon log in, are sent to the server the user credentials along with the client ID and client Secret, we get back an access token and everything works well.
I must confess I'm a bit lost with the second method: upon login, user Facebook credentials are sent to Facebook server, which responds with an access token, and my app get access to my user Facebook information (such as email address and UID). But I do not know what to do with this FB information, and especially what I should sent to my own OAuth server so that:

*

*The user gets connected to my server

*The connection is secure (i.e. no one can impersonate the user by only having to get her Facebook UID for instance).

In other terms, there should be something secret related to Facebook sent to my server but I can not figure what.

A: I have found the answer to my second question, so I share it here:
What should be passed on to the server is the Facebook access token, so that the server can :

*

*make a request using Facebook PHP SDK and the given token

*retrieve user data (such as Facebook UID for instance)

*match it against your website user database (which should have users FB UIDs)

*actually connects the user if there is a match

Step 1. and 2. can be done nicely with the helper class FacebookJavascriptLoginHelper of the FB PHP SDK. In this case, the access token is stored by Facebook Javascript SDK into a cookie that is read server-side by the FacebookJavascriptLoginHelper.


text:
Q: Is it correct to model percent change as a continuous variable? I have data from a longitudinal study where there are 46 subjects, each with 13 observations over time on a given outcome measure.  A prior analysis conducted on this data performed a linear mixed model on the percent change (treatment, baseline value, time, and treatment*time were independent variables in the model).  I am wondering if using raw change as the outcome variable is more correct, especially since baseline value is controlled in the model anyway.

A: Whether this is the best approach depends on what your data looks like, and why the percent change was used.  For example, % change is fairly easy to understand by laypeople, and so it's sometimes preferred when that's the target audience. Including the baseline as a covariate somewhat complicates how that percent would be stated, though, since the expected change would depend on the initial value.
Certainly, to use percent change, the data must be on a scale where 0 means 0.  That is, a 0 must mean an absence of disease or similar.
I think this article does a pretty good job of summarizing some problems associated with modeling percent change: http://allenfleishmanbiostatistics.com/Articles/2012/06/18-percentage-change-from-baseline-great-or-poor/.

In all cases, Analysis of Covariance (ANCOVA) with baseline as the
  covariate was the most efficient statistical methodology.  Analyzing
  the change from baseline "has acceptable power when correlations
  between baseline and post-treatment scores are high; when correlations
  are low, POST [i.e., analyzing only the post-score and ignoring
  baseline – AIF] has reasonable power.  FRACTION [i.e., percentage
  change from baseline – AIF] has the poorest statistical efficiency at
  all correlations."
[Note: In ANCOVA, one can analyze either the change from baseline or
  the post treatment scores as the d.v.  'Change' or 'Post' will give
  IDENTICAL p-values when baseline is a covariate in ANCOVA.]
As an example of his results, when the correlation between baseline
  and post was low (i.e., 0.20) the percentage change was able to be
  statistically significant only 45% of the time.  Next worse, was
  change from baseline with 51% significant results.  Near the top was
  analyzing only the post score at 70% significant results.  The best
  was ANCOVA with 72% significant results.
Furthermore, percentage change from baseline "is sensitive in the
  characteristics of the baseline distribution."  When the baseline has
  relatively large variability, he observed that "power falls."

Also a potential concern: the ratio will blow up as the denominator approaches 0, which can create obvious problems when modeling.

A: The best way to do this is to model the final score as a function your listed independent variables PLUS the baseline score, like this:
final ~ baseline + treatment + time + treatment*time
There are a few important considerations:

*

*You should not model % change (final-baseline/baseline) and include baseline as a predictor, because these variables are structurally correlated. Even worse might be to model raw change (final - baseline) with baseline as a predictor. As baseline changes, you expect the dependent variables to change in both cases, all else equal. Conclusion: If you use % or raw change, do not include baseline as a predictor.

*Modelling percentages as continuous variables is a dying approach, because these variables are typically not normally distributed, by virtue of being bounded at 0 and 1, and also see last comment by TiffTiff. The arcsine square-root (aka angular) transformation has traditionally been used to combat this problem, but is also falling out of favor due to highly conditional efficacy (i.e., it often doesn't work well).

*Modelling raw change, even when baseline is not included as a predictor, is not ideal because you in essence constrain the relationship between baseline and final to be 1:1. Basic algebra to see why:
Here is the raw change model:
final - baseline ~ treatment

which is more precisely,
1*final - 1*baseline ~ b0 + b1*treatment + error

where b0 and b1 are parameters to be estimated. if you rearrange, you get:
1*final ~ b0 + 1*baseline + b1*treatment + error

hence, the parameter describing the relationship between baseline and final is set to 1.0.
If instead you model like this:
final ~ baseline + treatment

that is more precisely
1*final ~ b0 + b1*baseline + b2*treatment + error

If indeed there is not a 1:1 relationship between baseline and final, the parameter estimate b1 will be greater than or less than 1. If it turns out that b1 ≠ 1, you will have more power to test the effect of treatment than if you used raw change, and also get information about the relationship between baseline and final. On the other hand, if b1 = 1, then you should have less power, since you're using up one more degree of freedom.
As far as reporting these stats, I understand why you want to say "The difference between scores increased when the treatment was applied": You want to control for the baseline. But that's exactly what the final ~ baseline + treatment model does, and it does it better. You can say "Scores were higher with the treatment, controlling for the baseline score".


text:
Q: Identifying weak partitions Recently a problem rose to me I'm not really sure what topic it belongs to:
The origin is a "labeling application". There are n objects (say files etc., n abt. 1e6). And there are t properties/ labels (t abt. 1e3). Every of the n objects is assigned to some labels. No restriction. Simple.
Every subset of labels filters (AND) the objects. For some subsets of labels you will get a great amount of objects, but there is no label you can add which "divides" the resulting objects, as none of these objects is labelled by any other label than the ones already used for filter. (BTW: Empty set (for objects) is excluded).
Actually it happens only "by chance" that I trap into such situation. Very unsatisfying.
So I would like to identify a priori those subsets of all my labels which produce such situation. (Kind of closure, or clique, or ...?).
Afterwards order those subsets by number of found objects, so I can invent a new label for each subset, which divides the resulting objects.
It looks like a kind of balanced-tree problem. Or finding a "base" that produces good partitions. Or...?
I'm not good at that but I might think the problem could well be expressed in terms of set-theory (2 sets, a relation, special subset of the relation that fulfill the condition).
I searched this and that way, but none of the well-known problems/ algs seems to fit. (Still I'm no expert in set-theory or database).
I hope anyone has a hint for me?
If it is identified and should be NP complete (which I suspect), may there is an approx. alg./ heuristic...

A: Time and "some" thinking let the solution dawn to me.
The problem can be solved in O [n * t].
(The 2^t monster is gone...)
The biggest hurdle on it was the origin the problem
came from - and the description in that context.
What I was actually searching for is all sets of
objects with equal assigment to labels.
After building a list of all (object, assigment) pairs
the job is only to build the equivalence classes
wrt assigment values.
Just pick out the largest classes - la voilà!
Mathematically it still looks like a kind of "closure" to me.


text:
Q: Is equicontinuity a necessary condition for the result of Arzela- Ascoli Theorem The result shows the existence of a uniformly convergent sub-sequence of the original sequence i.e. some kind of limiting behavior. So, can equi-continuity be relaxed to some kind of limiting ($\limsup) form of it ?
Thanks


text:
Q: Java - get value in field? I dont know how to put this, but im trying to get the value of a value in a field. Here are some of the code (dont ask why i have length and height):
//person class
public person(double w, double h, double l){
        this.width = w;
        this.height = h;
        this.length = l;
    }

//age class (extends person)
    public age(double w, double h, double l, int a) {
        super(w, h, l);
        this.age = a;
    }

//Creating the objects and putting them in an array (in the main class):
public person steve = new age(36.64, 185.64, 44.4, 26);
public person paul = new age(45.64, 178.64, 53.4, 47);

person[] people = new person[2];
people[0] = steve;
people[1] = paul;

Now i need to get the age of the people in the array. How would you do that?

A: Hopefully this helps you understand :)
class Main {
  public static void main(String[] args) {
    Person pixelGrid = new Person();
    pixelGrid.setName("Pixel Grid");
    pixelGrid.setAge(18);
    System.out.println(pixelGrid);
  }
}

class Person {
   protected String sName;
   protected int sAge;

   public void setName(String sName) {
      this.sName = sName;
   }

   public String getName() {
      return sName;
   }

   public void setAge(int sAge) {
      this.sAge = sAge;
   }

   public int getAge() {
      return sAge;
   }

   public String toString() {
      String s = "The Persons Name is: " + getName() + "\n";
      s += "Their Age is: " + getAge() + "\n";
      return s;
   }
}

Output:
The Person's Name is: Pixel Grid
Their Age is: 18

Try it here!

A: To retrieve the age directly from the arrays:
Some minor code change to the main class:
public static void main(String[] args) {
    // TODO Auto-generated method stub

        age steve = new age(36.64, 185.64, 44.4, 26);
        age paul = new age(45.64, 178.64, 53.4, 47);
        age[] people = new age[2];
        people[0] = steve;
        people[1] = paul;

        System.out.println(people[0].age);
        System.out.println(people[1].age);
}


text:
Q: how to get the sum of a CSV column list to print I need to get the sum of the second column in a csv. I have tried several possible solution but at most, I am only getting Totals = set{} where I would expect to get the sum of the list I created from the second column of the csv file. My csv file looks like this:
I am sure it has to be a simple solution I am missing, but I can't figure it out and have spent hours trying different options I've found, here and on other sites. I would really appreciate any help to point me in the right direction. Also, for this, I can't use modules like Pandas. Here is my code.
    import os
    import csv

    budget_csv = os.path.join("../PyBank", "budget_data.csv")

    with open(budget_csv, newline="") as csvfile:
        csvreader = csv.reader(csvfile, delimiter=",")
        #skip header row
        next(csvreader, None)

        # Gets number of rows in csv
        data=list(csvreader)

        row_count = len(data)

        totals = []
        for row in csvreader:
            values = row[1]
            totals.append(values)

        print (totals) #did this just to see if it would print the list of values

    print ("Financial Analysis")
    print ("-------------------------------")
    print ("Total Months: ", row_count)
    print ("Total: ", sum(totals))
    print ("Average Change: ")
    print ("Greatest Increase in Profits: ")
    print ("Greatest Decrease in Profits: ")

    output_file = os.path.join("Analysis.txt")

    #  Open the output file
    with open(output_file, "w") as text_file:
        text_file.write (f"Financial Analysis\n")
        text_file.write (f"-------------------------------\n")
        text_file.write (f"Total Months: " + str(row_count) + "\n")
        #print (f"Total: {}".format(net))
        #print (f"Average Change: ")
        #print (f"Greatest Increase in Profits: ")
        #print (f"Greatest Decrease in Profits: ")

A: you need to iterate on data, not on csvreader once csvreader is cast as list.
for row in data:

A: Figured it out, finally. Created two new variables. Renamed totals = [] to totals1 = []. Then turned the ints in totals 1 into floats using totals2 = [float(integral) for integral in totals1], which was used to get the sum with totals3 = sum(totals2). New code:
     totals1 = [] for row in data:
         values = row[1]
         totals1.append(values)
     totals2 = [float(integral) for integral in totals1] #turns values in totals1 into floats
     totals3 = sum(totals2)

A: when you do data=list(csvreader) you consumed csvreader, so it's at the end of the file and when you try to iterate over it again on this line for row in csvreader: it's empty and total remains empty list. I would also recommend using csv.DictReader.
Not tested, bur something like
import os
import csv

budget_csv = os.path.join("../PyBank", "budget_data.csv")

with open(budget_csv, 'r') as csvfile:
    csvreader = csv.DictReader(csvfile, delimiter=",")
    totals = []
    for row_count, row in enumerate(csvreader, start=1):
        value = int(row['Profit/Losses'])
        totals.append(value)

print ("Financial Analysis")
print ("-------------------------------")
print ("Total Months: {}".format(row_count))
print ("Total: {}".format(sum(totals)))
print ("Average Change: ")
print ("Greatest Increase in Profits: ")
print ("Greatest Decrease in Profits: ")

output_file = os.path.join("Analysis.txt")

#  Open the output file
with open(output_file, "w") as text_file:
    text_file.write ("Financial Analysis\n")
    text_file.write ("-------------------------------\n")
    text_file.write ("Total Months: {}\n".format(row_count))


text:
Q: Run application from html button using php/perl I was wondering if there is any way to open an application or file browser such as nautilus from a local html button using php or perl. The webpage is local and I have php and perl installed. I can run shell scripts that print "Hello World" to the php page, but is there anyway to open an application from the webpage? I am using Debian

A: Ignoring the inherent security risks and issues with permissions, it can be done, yes.  This is assuming the webserver, the web client, and the gui app are all to be run on the SAME box.
Here is an example CGI script that will launch a local X app:
#!/usr/bin/perl
system("export DISPLAY=:0.0;/usr/bin/nedit");

The process (in this case, nedit) will be run as the webserver user (in the case of my CentOS box, apache).  Check the apache error log for the various errors and warnings you will encounter.
You may (likely) need to fiddle with X server settings in order to get things to work.


text:
Q: Primes of the form $x^2 + y^2 + 1$ There are infinitely many primes of the form $x^2+y^2+1$, as proved by Bredihin. Motohashi improved the result by showing that there were $\gg x/\log^2 x$ such primes up to $x$. But we expect $\Theta(x/\log^{3/2}x)$ primes up to $x$; has this result been proved? (Failing that, is anything else known about the density since the 70s? I know Sun & Pan proved the Green-Tao theorem for these primes.)

A: Iwaniec (Acta Arith. 1972) showed that the number of such primes has the order $x/(\log x)^{3/2}$.   His result applies more generally to translates of binary quadratic forms.  One can also show that short intervals contain the right density of such primes: for example, see the work of Matomaki (Acta Arith. 2007).


text:
Q: When to use "lessen", when "decrease", and when "reduce"? Is it appropriate to say this:

*

*I need to reduce the amount of money I spend per month.

*I need to lessen the amount of money I spend per month.

*I need to decrease the amount of money I spend per month.

I don't understand when to use "reduce", "decrease", and "lessen". Can you explain it, please?

A: Offhand I can't think of any contexts where the choice between reduce, lessen, decrease would make any difference to the meaning of an utterance. But there are significant differences as regards how common each verb is...

Note that the above chart shows the transitive usage (someone or something causes the amount to become smaller). But here's another chart showing the intransitive usage (the amount still becomes smaller, but no "agent" is specified)...

...where you'll note that lessen doesn't even occur often enough to chart.

My advice for learners would be to avoid using lessen at all (as this chart shows, it's been falling in popularity for at least three centuries).
As regards the choice between the other two, it's pretty obvious reduce is significantly more common. But no-one would be likely to think you'd made an "uncommon, unusual" choice if you used decrease instead (particularly in intransitive contexts), so it doesn't really matter which one you use. There's no doubt that decrease has been gradually gaining traction, but it still lags well behind reduce.


text:
Q: create table with json php I have a Json result like this :
Array (
[0] => Array (
     [Street] => Street_name
     [status] => Best_Shop
     [Shop] => Array ( [0] => Array (
                    [Name] => Bakery_Shop
                    [Owner] => John
                    [Type] => 0
                    [Food] => Cake
                    [Drink] => Coffee
                    [Best_Customer] => All
                    [a] => Good
                    [b] => Normal
                    [c] => Bad
               [1] => Array (
                    [Name] => Junk_Foodshop
                    [Owner] => Mike
                    [Type] => 0
                    [Food] => Burger
                    [Drink] => Coke
                    [Best_Customer] => All
                    [a] => Good
                    [b] => Normal
                    [c] => Bad )
    [Rate] => Average
    [Signature] => Boss ) )

And i am trying to create a shop table with rows displaying each stat like this :
Name          Owner Type Food   Drink    Best_Customer  a    b      c

Bakery_Shop   John   0   Cake   Coffee       All        Good Normal Bad

Junk_Foodshop Mike   0   Burger Coke         All        Good Normal Bad

I currently have this code written up and although i am getting the data its not quite working the way i want it to be.
****From json_shop.php****

function getAstCard(){
    $json = array();
    $json[0] = array(
        "Street" => "Street_name ",
        "status" => "Best_Shop ",
        "Shop" => $Shop,
        "Rate" => "Average ",
        "Signature" => $conf->get_IXAstUser()
    );
    return $json;
}
**Into jsonTable.php**

    <?php
    include 'json_shop.php';

    $AstCardTable.='
';
    $AstCardTable.='
';
    $AstCardTable.='
';
    $AstCardTable.='
                            Name
                            Owner
                            Type
                            Food
                            Drink
                            Best_Customer
                            a
                            b
                            c

';

    $AstCard = getAstCard();
    if (count($AstCard) > 0) {
        for ($i = 0; $i < count($AstCard); $i++) {
            $AstCardRecord = $AstCard[$i];
                $AstCardTable.='
';
                $AstCardTable.='' . $AstCardRecord['Name'] . '	';
                $AstCardTable.='' . $AstCardRecord['Owner'] . '	';
                $AstCardTable.='' . $AstCardRecord['Type'] . '	';
                $AstCardTable.='' . $AstCardRecord['Food'] . '	';
                $AstCardTable.='' . $AstCardRecord['Drink'] . '	';
                $AstCardTable.='' . $AstCardRecord['Best_Customer'] . '	';
                $AstCardTable.='' . $AstCardRecord['a'] . '	';
                $AstCardTable.='' . $AstCardRecord['b'] . '	';
                $AstCardTable.='' . $AstCardRecord['c'] . '	';
                $AstCardTable.='
';
        }
    } else {
        $AstCardTable.='
';
        $AstCardTable.='Temporarily no data in the list	';
        $AstCardTable.='
';
    }

    $AstCardTable.='
';
    $AstCardTable.='
';

    echo $AstCardTable;

    ?>

Does anyone with experience in this topic and see if any problem about my code? Any help would be greatly appreciated.Thank you .

A: You need to return return $json[0]['Shop']; from getAstCard method.
Otherwise, change the variable in your loop a bit :
$AstCard = getAstCard();
$AstCardShop = $AstCard[0]['Shop'];
if (count($AstCardShop) > 0) {
    for ($i = 0; $i < count($AstCardShop); $i++) {
            $AstCardRecord = $AstCardShop[$i];

            $AstCardTable.='
';
            $AstCardTable.='' . $AstCardRecord['Name'] . '	';
            $AstCardTable.='' . $AstCardRecord['Owner'] . '	';
            $AstCardTable.='' . $AstCardRecord['Type'] . '	';
            $AstCardTable.='' . $AstCardRecord['Food'] . '	';
            $AstCardTable.='' . $AstCardRecord['Drink'] . '	';
            $AstCardTable.='' . $AstCardRecord['Best_Customer'] . '	';
            $AstCardTable.='' . $AstCardRecord['a'] . '	';
            $AstCardTable.='' . $AstCardRecord['b'] . '	';
            $AstCardTable.='' . $AstCardRecord['c'] . '	';
            $AstCardTable.='
';
    }
}


text:
Q: What is the difference between C# , .NET and CLI? What is the difference between C# , .NET and CLI?

A: C# is one of the .NET languages - VB.NET, F# and many more exist.
.NET is a platform (libraries, compiler and runtime) on which code written by any of these languages runs.
CLI is the Common Language Infrastructure - it is a specification that describes the executable code and runtime that make the .NET platform. Apart from the Microsoft one, there are other implementations - mono and Portable.NET the most known.
If you want some more acronyms:

*

*There is also the CLR - the common language runtime, which is the Microsoft implementation of the CLI, mentioned above.

*In addition, on top of the CLR, Microsoft have created the DLR - the dynamic language runtime is a set of services for several dynamic languages such as python and ruby.

A: well, c# is programming language,CLR is the tool or framework so you write your code using c#, CLR convert that codes to Microprocessor's language and all order up to your c# code CLR coordinate memory,microprocessor and other sources, so if you work in that situation or you make a product with this, they say your done your job up to .NET


text:
Q: Ring of integers of $\mathbb{Q}(\sqrt[3]{6})$ I am trying to find the ring of integers of $\mathbb{Q}(\sqrt[3]{6})$. Unfortunately, the discriminant of the basis $\{1, \theta, \theta^2\}$, where $\theta = \sqrt[3]{6}$, is equal to $2^2 (-3)^5$ (so it's not square-free). How can I proceed in this case to find the ring of integers? I could take the prime $2$, and analyze the expressions of the form $(a + b\theta + c\theta^2)/2$ for binary values of $a,b,c$, but maybe there is a more direct approach.

A: $Disc(x^3-6)= -27(-6)^2=3^a2^b$
Since $v_3(6^{1/3})=v_3(6)/3=1/3$ then $\Bbb{Q}_3(6^{1/3})/\Bbb{Q}_3$ is totally ramified of degree $3$ with uniformizer $6^{1/3}$
Similarly $\Bbb{Q}_2(6^{1/3})/\Bbb{Q}_2$ is totally ramified with uniformizer $6^{1/3}$
The uniformizers of the ramified completions are in $\Bbb{Z}[6^{1/3}]$ thus it is a Dedekind domain ie. $$O_{\Bbb{Q}(6^{1/3})} = \Bbb{Z}[6^{1/3}]$$
For $p\ne 2,3$ then $(p)$ is a product of distinct prime ideals of $\Bbb{Z}[6^{1/3}]$, for $p=2,3$ then $(p)=(p,6^{1/3})^3$.
The more elementary solution : check that $(p)=(p,6^{1/3})^3$ for $p=2,3$, since the unramified prime ideals are easily shown to be inversible, this implies every prime ideal is inversible, thus it is a Dedekind domain, thus it is integrally closed ($=O_K$). The point is that (in Dedekind domains) a prime ideal $P$ becomes principal $=(\pi)$ in $(O_K-P)^{-1} O_K$, the uniformizer is $\pi$, from which we obtain a discrete valuation and a $p$-adic completion.

A: If you are interested, a complete determination of the ring of integers $R$ of a pure cubic  field $\mathbf Q(\sqrt [3] m)$, where $m$ is a cube free integer written as $m=hk^2$, withe $h,k$ coprime and square free, can be found in chap.3 of D.A. Marcus' book "Number Fields".
In the general case of a number field $\mathbf Q(\alpha)$, where $\alpha$ is an algebraic integer of degree $n$, thm.13 therein states that $R$ admits an integral basis of the form {$1, f_1(\alpha)/d_1,..., f_{n-1}(\alpha))/d_{n-1}$}, where the $d_i \in \mathbf Z$ , with $d_1|d_2|...|d_{n-1}$, are uniquely determined, and the $f_i \in \mathbf Z[X]$ are monic of degree $i$. In the particular case of $\alpha=\sqrt [3] m$, everything becomes explicit. The (long) exercise 41 op. cit. shows that one can take $f_1(\alpha)/d_1=\alpha$, and $f_2(\alpha)/d_2=\alpha^2/k$ if $m\neq \pm 1$ (mod $9$), $\alpha^2\pm k^2\alpha+k^2/3k$ if $m\equiv \pm 1$ (mod $9$) .


text:
Q: MVC input button onclick does not work after changing it in jQuery I've a dropdownlist and button in a page as below:
@Html.DropDownList("MovieType")

<input id="btnBk" type="button" value="Back" onclick="location.href = '/Test/Index/'"  />

The dropdownlist is populated in the controller:
public ActionResult DDL()
{
    List<SelectListItem> items = new List<SelectListItem>();

    items.Add(new SelectListItem { Text = "Action", Value = "0" });

    items.Add(new SelectListItem { Text = "Drama", Value = "1" });

    items.Add(new SelectListItem { Text = "Comedy", Value = "2", Selected = true });

    items.Add(new SelectListItem { Text = "Science Fiction", Value = "3" });

    ViewBag.MovieType = items;

    return View();
}

When a dropdownlist item is selected, I try to change the button onclick from the original /Test/Index/ to /Test/Index1 :
$(document).ready(function () {
    $('#MovieType').change(function () {
        var href = $('#btnBk').attr("onclick");
        alert(href);
        $('#btnBk').attr('onclick', "location.href='/Test/Index1/'");
        href = $('#btnBk').attr("onclick");
        alert(href);
    })
});

Alert messages indicate that the onclick value is updated. But when click on the Back button after changing, it has no response instead of redirecting to /Test/Index1.
Is something missing?
Thanks in advance,
Ben

A: Remove the onclick attribute from your element and make it like this.
Make full use of jQuery for your operations.
$(document).ready(function () {
      $('#btnBk').click(function(){
             location.href='/Test/Index/';
        });

    $('#MovieType').change(function () {
        $('#btnBk').unbind('click').click(function(){
             location.href='/Test/Index1/';
        });
    })
});


text:
Q: Can I use jquery within my custom Polymer elements? The Polymer documentation says:

Polymer provides a custom API for manipulating DOM such that local DOM and light DOM trees are properly maintained. These methods and properties have the same signatures as their standard DOM equivalents, except that properties and methods that return a list of nodes return an Array, not a NodeList.
Note: All DOM manipulation must use this API, as opposed to DOM API directly on nodes.

Jquery has a lot of useful methods though, which make my life easier, like toggleClass, hasClass, addClass, one...
I have been able to use some of these methods without consequence in my elements, but I am wondering what exactly the semantics are behind the bold part of the above quote, so I can reason about things more clearly.
Note: I'm not talking about using jquery in the main document, I am talking about using it when I am inside the shadow boundary, like in an element's ready callback for instance.

A: You can, actually. You'll just have to use Polymer.dom(this.root).querySelector and wrap that returned element in jquery.
Here's an example. http://jsbin.com/purudu/edit?html,output


text:
Q: How to use a locally installed plugin as a global sbt plugin I'm trying to use a modified version of an sbt plugin (specifically, sbt-quickfix).
After cloning the repo and compiling a modified version, I tried

*

*Setting the version to 0.4.1-SNAPSHOT, doing sbt publishLocal and adding a corresponding addSbtPlugin line to ~/.sbt/0.13/plugins/plugins.sbt

*Creating the following ~/.sbt/0.13/plugins/project/Build.scala:
import sbt._
import sbt.Keys._

object PluginDef extends Build {
  override val projects = Seq(root)
  lazy val root = Project("plugins", file(".")) dependsOn (quickfixPlugin)
  lazy val quickfixPlugin = uri("file:///Users/ohle/Projects/sbt-quickfix/")
}

Using both approaches, I still get an unmodified version of the plugin included in my sbt projects (i.e., the plugin behaves exactly like an unmodified one, and a simple String key I added for testing purposes isn't defined).
Why could the local version still be overridden by the official one?
P.S.: I use scala 2.10 and sbt 13.0 for everything.


text:
Q: R long vectors not supported yet on R 3.3.2 I am trying to simulate hilbertcurve (of Bioconductor package) of level 16 in R. It takes about 4^16=4 Billion points. I want to generate the hilbert curve of genome (size about 3 billion).
But I am getting this error
long vectors not supported yet: memory.c:1668

I am using 64 bit version (R 3.3.2) so my guess is I can use vectors of length > 2^31. Also, my RAM is about 350GB.
The command I am using is
itr=4^16
hc = HilbertCurve(1, itr, 16, mode = "pixel", title = "pixel mode",start_from = "topleft")

Even when I am reading the whole genome sometimes R is crashing in the process.
I have read the other similar questions on this topic but could not find the solution. Please help me what should I use for this problem.


text:
Q: ERROR while ng build --prod "Cannot negate a statement" I am using following command to build angular project (it has some bower components under assets folder):

./node_modules/.bin/ng build --prod --base-href /project

And after running above command I am getting following error :

ERROR in main-es2015.110a0182c67c95b8de43.js from Terser
Error: Cannot negate a statement
at AST_ClassExpression. (/node_modules/terser-webpack-plugin/node_modules/terser/dist/bundle.min.js:1:175355)
at AST_ClassExpression.negate (/node_modules/terser-webpack-plugin/node_modules/terser/dist/bundle.min.js:1:176467)
at /node_modules/terser-webpack-plugin/node_modules/terser/dist/bundle.min.js:1:200508
at AST_If.optimize (/node_modules/terser-webpack-plugin/node_modules/terser/dist/bundle.min.js:1:137605)
at ai.before (/node_modules/terser-webpack-plugin/node_modules/terser/dist/bundle.min.js:1:137382)
at AST_If.transform (/node_modules/terser-webpack-plugin/node_modules/terser/dist/bundle.min.js:1:84306)
at /node_modules/terser-webpack-plugin/node_modules/terser/dist/bundle.min.js:1:84470
at l (/node_modules/terser-webpack-plugin/node_modules/terser/dist/bundle.min.js:1:953)
at e (/node_modules/terser-webpack-plugin/node_modules/terser/dist/bundle.min.js:1:1273)
at kn (/node_modules/terser-webpack-plugin/node_modules/terser/dist/bundle.min.js:1:84444)

Versions :
"terser": "4.6.3"
"terser-webpack-plugin": "3.0.3"
"webpack": "4.39.2"
"@angular-devkit/architect": "0.803.29"
"@angular-devkit/build-optimizer": "0.803.29"
"@angular-devkit/build-webpack": "0.803.29"
"@angular-devkit/core": "8.3.29"
I know we can bypass this by setting optimization param to false in build command but it won't create a minified bundles.
Any suggestion on how to approach on this?

A: In my case, this was not related to library. I have the following code where I got this error:
this.homeService.subscribe((homeEvents: HomeEvents[]) => {
            if (HomeEvents) { // Error in this line.
              this.events.unshift(homeAnnouncement[0]);
            }
          });

The HomeEvents should have been homeEvents that is why its throwing this specific error. HomeEvents is a class, not a variable for if/else statement. Hope this helps others as it took me sometime to find out where and which line is causing the code to break.


text:
Q: How do i make my drop down menu visible beyond the navbar? I'm trying to have a drop down menu within a navbar; however, it only displays until the limit of my navbar when, ideally, id like it to be "in front" of the navbar so to speak.
Dropdown is cut off
I am new to html and CSS so my exploration is somewhat limited. I have implemented one of bootstrap's navbar's and also used their dropdown button html. I expected this to work okay but, as stated, the dropdown seems to be bound within the navbar (assuming this is because it is within the navbar div?) I have also attempted to follow w3schools guide but I didn't succeed with that either.
Sidenote: because of the limited visibility, the "my account" button logs the user out, this is intentional for now lmao.

            {% if not session["id"] %}
                Log In
            {% endif %}
            {% if session["id"] %}
                Languages
                FAQs

                    <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
                        Account
                    </button>

My Account

Log Out

            {% endif %}

    {% if get_flashed_messages() %}

                {{ get_flashed_messages() | join(" ") }}

    {% endif %}

        {% block main %}{% endblock %}

.navbar {
    height: 100;
    overflow: hidden;
}

.navbar-nav {
    align-items: baseline;
    display: flex;
    float: right;
    gap: 3em;
}

.nav-link {
    color: black;
    display: flex;
    float: right;
}

.nav-link:hover {
    color: red;
}

.btn-secondary {
    background: none;
    border: none;
    color: black
}

.btn-secondary:hover {
    background: none;
    border: none;
    color: red;
}

.logo {
    display: flex;
    scale: 0.4;
    transform-origin: left;
}

A: your example should be cut down to just the minimum that displays the issue. you have extra classes, some ASP-like code, etc - none of that is needed and just makes it harder to diagnose.
the issue appears to be that your submenu is contained inside the top-level .navbar element, but you are constraining that to have a height of 100 (and you should include the metric here - 100px? 100cm?) with overflow being hidden. this means that the submenu gets cut off.
you could just remove those constraints.
a better solution would involve a rewrite, so the submenu items are positioned absolutely, in a relatively-positioned placeholder. there are examples of this online. example: https://gist.github.com/SamWM/901853

A: {% if not session["id"] %}
                    Log In
                {% endif %}
                {% if session["id"] %}
                    Languages
                    FAQs

                          Account

*My Account

*Log Out

                {% endif %}

        ...

A: Remove the "overflow: hidden;" style from .navbar css, so your code should be-
.navbar {
    height: 100;
}


text:
Q: Waveform Audio - waveOutWrite gives choppy sound I'm trying to create a C++ program with Waveform Audio library that would be playing AudioFrames (raw audio data, each frame consists of about 1920 bytes)   provided by another program (right now I'm just simulating that by reading file as AudioFrames). Modifying code from this thread I was able to make SoundPlayer class that does the job, but the output I get is extremely choppy. It's gets better with bigger frame sizes, but even with frames as big as 96000 bytes the audio still glitches every second or so (and I need the frames too be much smaller than that).
How can I fix this issue?
Here is the test file I'm using. And here is the code itself:
#include <windows.h>
#include <iostream>
#pragma comment(lib, "Winmm.lib")

constexpr int FRAME_SIZE_IN_BYTES = 1920;

struct AudioFrame
{
    char *Data;
    int DataSize;
};

class SoundPlayer
{
public:

    SoundPlayer()
    {
        // Initialize the sound format we will request from sound card
        m_waveFormat.wFormatTag = WAVE_FORMAT_PCM;     // Uncompressed sound format
        m_waveFormat.nChannels = 1;                    // 1 = Mono, 2 = Stereo
        m_waveFormat.wBitsPerSample = 16;               // Bits per sample per channel
        m_waveFormat.nSamplesPerSec = 48000;           // Sample Per Second
        m_waveFormat.nBlockAlign = m_waveFormat.nChannels * m_waveFormat.wBitsPerSample / 8;
        m_waveFormat.nAvgBytesPerSec = m_waveFormat.nSamplesPerSec * m_waveFormat.nBlockAlign;
        m_waveFormat.cbSize = 0;
    }

    void Play(AudioFrame* af)
    {
        // Create our "Sound is Done" event
        m_done = CreateEvent(0, FALSE, FALSE, 0);

        // Open the audio device
        if (waveOutOpen(&m_waveOut, 0, &m_waveFormat, (DWORD)m_done, 0, CALLBACK_EVENT) != MMSYSERR_NOERROR)
        {
            std::cout << "Sound card cannot be opened." << std::endl;
            return;
        }

        // Create the wave header for our sound buffer
        m_waveHeader.lpData = af->Data;
        m_waveHeader.dwBufferLength = af->DataSize;
        m_waveHeader.dwFlags = 0;
        m_waveHeader.dwLoops = 0;

        // Prepare the header for playback on sound card
        if (waveOutPrepareHeader(m_waveOut, &m_waveHeader, sizeof(m_waveHeader)) != MMSYSERR_NOERROR)
        {
            std::cout << "Error preparing Header!" << std::endl;
            return;
        }

        ResetEvent(m_done); // Reset our Event so it is non-signaled, it will be signaled again with buffer finished

        // Play the sound!
        if (waveOutWrite(m_waveOut, &m_waveHeader, sizeof(m_waveHeader)) != MMSYSERR_NOERROR)
        {
            std::cout << "Error writing to sound card!" << std::endl;
            return;
        }

        // Wait until sound finishes playing
        if (WaitForSingleObject(m_done, INFINITE) != WAIT_OBJECT_0)
        {
            std::cout << "Error waiting for sound to finish" << std::endl;
            return;
        }

        // Unprepare our wav header
        if (waveOutUnprepareHeader(m_waveOut, &m_waveHeader, sizeof(m_waveHeader)) != MMSYSERR_NOERROR)
        {
            std::cout << "Error unpreparing header!" << std::endl;
            return;
        }

        // Close the wav device
        if (waveOutClose(m_waveOut) != MMSYSERR_NOERROR)
        {
            std::cout << "Sound card cannot be closed!" << std::endl;
            return;
        }

        // Release our event handle
        CloseHandle(m_done);
    }

private:
    HWAVEOUT m_waveOut; // Handle to sound card output
    WAVEFORMATEX m_waveFormat; // The sound format
    WAVEHDR m_waveHeader; // WAVE header for our sound data
    HANDLE m_done; // Event Handle that tells us the sound has finished being played.
                   // This is a very efficient way to put the program to sleep
                   // while the sound card is processing the sound buffer

};

int main()
{
    FILE * fileDes;
    fopen_s(&fileDes, "Ducksauce.raw", "rb");
    if (fileDes == nullptr)
        std::cout << "File opening failed.\n";

    int bufferSize = FRAME_SIZE_IN_BYTES;
    char *buffer = new char[bufferSize];

    SoundPlayer sp;

    while (fread(buffer, sizeof(char), bufferSize, fileDes) > 0)
    {
        AudioFrame af;
        af.Data = buffer;
        af.DataSize = bufferSize;
        sp.Play(&af);
    }

    fclose(fileDes);
    delete[] buffer;
    return 0;
}

Edit: Version number 2. Still doesn't work as intended.
#include <windows.h>
#include <iostream>
#pragma comment(lib, "Winmm.lib")

constexpr int FRAME_SIZE_IN_BYTES = 1920;

struct AudioFrame
{
    char *Data;
    int DataSize;
};

class SoundPlayer
{
public:

    SoundPlayer()
    {
        // Initialize the sound format we will request from sound card
        m_waveFormat.wFormatTag = WAVE_FORMAT_PCM;     // Uncompressed sound format
        m_waveFormat.nChannels = 1;                    // 1 = Mono, 2 = Stereo
        m_waveFormat.wBitsPerSample = 16;               // Bits per sample per channel
        m_waveFormat.nSamplesPerSec = 48000;           // Sample Per Second
        m_waveFormat.nBlockAlign = m_waveFormat.nChannels * m_waveFormat.wBitsPerSample / 8;
        m_waveFormat.nAvgBytesPerSec = m_waveFormat.nSamplesPerSec * m_waveFormat.nBlockAlign;
        m_waveFormat.cbSize = 0;

        // Create our "Sound is Done" event
        m_done = CreateEvent(0, FALSE, FALSE, 0);

        // Open the audio device
        if (waveOutOpen(&m_waveOut, 0, &m_waveFormat, (DWORD)m_done, 0, CALLBACK_EVENT) != MMSYSERR_NOERROR)
        {
            std::cout << "Sound card cannot be opened." << std::endl;
            return;
        }
    }

    ~SoundPlayer()
    {
        // Close the wav device
        if (waveOutClose(m_waveOut) != MMSYSERR_NOERROR)
        {
            std::cout << "Sound card cannot be closed!" << std::endl;
            return;
        }

        // Release our event handle
        CloseHandle(m_done);
    }

    void StartPlaying(AudioFrame* af)
    {
        // Create the wave header for our sound buffer
        m_waveHeader.lpData = af->Data;
        m_waveHeader.dwBufferLength = af->DataSize;
        m_waveHeader.dwFlags = 0;
        m_waveHeader.dwLoops = 0;

        // Prepare the header for playback on sound card
        if (waveOutPrepareHeader(m_waveOut, &m_waveHeader, sizeof(m_waveHeader)) != MMSYSERR_NOERROR)
        {
            std::cout << "Error preparing Header!" << std::endl;
            return;
        }

        ResetEvent(m_done); // Reset our Event so it is non-signaled, it will be signaled again with buffer finished

        // Play the sound!
        if (waveOutWrite(m_waveOut, &m_waveHeader, sizeof(m_waveHeader)) != MMSYSERR_NOERROR)
        {
            std::cout << "Error writing to sound card!" << std::endl;
            return;
        }
    }

    void WaitUntilFrameFinishes()
    {
        // Wait until sound finishes playing
        if (WaitForSingleObject(m_done, INFINITE) != WAIT_OBJECT_0)
        {
            std::cout << "Error waiting for sound to finish" << std::endl;
            return;
        }
        // Unprepare our wav header
        if (waveOutUnprepareHeader(m_waveOut, &m_waveHeader, sizeof(m_waveHeader)) != MMSYSERR_NOERROR)
        {
            std::cout << "Error unpreparing header!" << std::endl;
            return;
        }
    }

private:
    HWAVEOUT m_waveOut; // Handle to sound card output
    WAVEFORMATEX m_waveFormat; // The sound format
    WAVEHDR m_waveHeader; // WAVE header for our sound data
    HANDLE m_done; // Event Handle that tells us the sound has finished being played.
                   // This is a very efficient way to put the program to sleep
                   // while the sound card is processing the sound buffer

};

int main()
{
    FILE * fileDes;
    fopen_s(&fileDes, "Ducksauce.raw", "rb");
    if (fileDes == nullptr)
        std::cout << "File opening failed.\n";

    int bufferSize = FRAME_SIZE_IN_BYTES;
    char *buffer = new char[bufferSize];

    SoundPlayer sp;

    // Read first time
    fread(buffer, sizeof(char), bufferSize, fileDes);

    while (true)
    {
        AudioFrame af;
        af.Data = buffer;
        af.DataSize = bufferSize;
        // Start playing, but don't block
        sp.StartPlaying(&af);
        // Prepare the next chunk
        if (fread(buffer, sizeof(char), bufferSize, fileDes) <= 0)
            break;
        // Now block the code, waiting with next chunk already loaded
        // and ready to be played in the next iteration.
        sp.WaitUntilFrameFinishes();
    }

    fclose(fileDes);
    delete[] buffer;
    return 0;
}

Edit 2: It works if I add this before while:
for (int i = 0; i < 3; i++ )
{
    fread(buffer, sizeof(char), bufferSize, fileDes);
    af.Data = buffer;
    af.DataSize = bufferSize;
    sp.StartPlaying(&af);
}

Also I modified while a bit too:
while (true)
{
    // Prepare the next chunk
    if (fread(buffer, sizeof(char), bufferSize, fileDes) <= 0)
        break;
    // Now block the code, waiting with next chunk already loaded
    // and ready to be played in the next iteration.
    sp.WaitUntilFrameFinishes();

    af.Data = buffer;
    af.DataSize = bufferSize;
    sp.StartPlaying(&af);
}

A: You should read the data from disk while the sound plays, not in between buffers!
If you can't read the whole file at once, you should change your Play function so that it doesn't just call WaitForSingleObject. Using it makes your code block and wait until the sound stops playing.
What you need instead is to start playing, then go back to your reading loop, prepare the next buffer, and then wait for the music to end, like so (in SoundPlayer):
void WaitUntilFrameFinishes() {
    // Wait until sound finishes playing
    if (WaitForSingleObject(m_done, INFINITE) != WAIT_OBJECT_0)

    // ... move all the code from Play till the end here
}

Then back in the main loop:
// Read first frame
fread(buffer, sizeof(char), bufferSize, fileDes);

while (true)
{
    AudioFrame af;
    af.Data = buffer;
    af.DataSize = bufferSize;

    // Start playing, but don't block
    sp.Play(&af);

    // Prepare the next chunk
    if (fread(buffer, sizeof(char), bufferSize, fileDes) <= 0) {
        break;

    // Now block the code, waiting with next chunk already loaded
    // and ready to be played in the next iteration.
    sp.WaitUntilFrameFinishes();
}

Ideally you'd also wrap the fread calls into something that can provide chunks in a nicer way.

A: After day of trying to figure out how to go about audio playback based on the documentation alone I found this excellent tutorial. If anyone found this thread while trying to create audio playback using Waveform audio it's a very good point of reference (surely much better than my buggy code above).
About my code I suspect it doesn't work correctly because one is supposed to keep the AudioFrames queue using waveOutWrite() with at least several frames at all time to prevent situation where sound card would have to wait for another AudioFrame.


text:
Q: Auto - Import for .ts Components in Sublime Text 3 I'm working on an AngularJS beginner Tutorial and the mentor is working with another IDE.
I prefer to use SublimeText3 because I am familiar with it. When I am declaring a new component in my app.module.ts (Marked with [1] in the code), then the import of the components ts file (Marked with [2] in the code) should be generated automatically in best case.
Is that possible?
I have installed import.js. But I have to start the generating of the import manually with this plugin - that isn't very helpful.
/** Created by mPiontek on 25.01.2017 */

import {BrowserModule} from "@angular/platform-browser"
import {NgModule} from "@angular/core"

import {AppComponent} from "./app.component";
import UserComponent from './user/user.component'; // [2]

@NgModule ({
    imports: [BrowserModule],
    declarations: [AppComponent, UserComponent],  // [1]
    bootstrap: [AppComponent]
})

export class AppModule {}

A: try to use sublime plugin ImportHelper for autocompletion of imports


text:
Q: Array permutation through rotation and reverse operation Given a 1D array of length n. Is it possible to programmatically  generate all possible permutations with just rotate and reverse operations applied as many times as required. If yes how(algo)? If not why?
Here rotation can be by any d < n,  and reverse means to reverse the entire array and not just in parts.
Example:
    Array:     1,2,3,4
    Reverse:     4,3,2,1
    Rotate by 2:     3,4,1,2
Also given two permutation states A and B of an array. Is it possible to get from state A to state B programmatically  using just rotation and reverse operations in any order. If yes how(algo)? If not why?
Example:
    A:     5,3,1,2,4
    B:     1,5,3,2,4

A: No, you cannot.
Lets say you have any sequence of rotate and reverse operations.  We'll write rotate by x as ROT(x) and reverse as REV.
Given any such sequence, you can transform it into an equivalent sequences consisting of at most one reverse followed by at most one rotation by applying the following rules:
rule 1: ROT(x), REV = REV, ROT(N-x)
For example, applying ROT(1), REV to 1234 gives 1234 -> 2341 -> 1432, and REV, ROT(3) gives 1234 -> 4321 -> 1432 -- the same result
By applying rule 1, we can move all the REV operations to the start.
rule 2: REV, REV = empty_sequence -- reversals cancel each other
Once all the REVs are at the start, we can apply rule 2 until there's at most one.
rule 3: ROT(x), ROT(y) = ROT(x+y % N) -- rotations add
also
ROT(0) = empty_sequence
Once all the ROTs are at the end, we can apply rule 3 until there's at most one.
So... any sequence of operations is equivalent to a sequence with at most one reverse followed by at most one non-zero rotation.  There are only 2N such sequences, but there are N! permutations, so N!-2N permutations cannot be reached by any such sequence.


text:
Q: Tracking user metrics in iOS app? What is a good way to keep track of the areas in an app that a user visits, or the features that he or she uses? I know there are several preexisting open-source frameworks:
Google Analytics SDK for iOS
iloggr analytics
And I know that there are services such as Flurry that also help. Does anyone know of any other options, and has anyone attempted to write a system that can keep track of some simple user metrics? A tutorial or example would be really appreciated.

A: Google Analytics has worked well for me. It's flexible enough that you can add tracking to pretty much everything. I have it set up in my application to track things such as view changes, which buttons are being pressed, issues encountered during media playback, and so on.


text:
Q: Windows Phone equivalent of Badge Icon What are some ways to show either notificationn count or the existence of new unread messages in Windows Phone.
Like in iOS we use the badge icon.

A: In Windows 8 and Windows Phone 8 you can add Badges to your live tiles:

A notification badge conveys summary or status information specific to your app. They can be numeric (1-99) or one of a set of system-provided glyphs. Examples of information best conveyed through a badge include network connection status in an online game, user status in a messaging app, number of unread mails in a mail app, and number of new posts in a social media app. Badges can be displayed on all tile sizes. On Windows, they appear in the lower-right corner of the tile (lower-left corner on a computer set to a right-to-left (RTL) language). On Windows Phone 8.1, they appear in the upper-right corner of the tile (upper-left corner on a computer set to a right-to-left (RTL) language).

Source: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh779719.aspx


text:
Q: Go with Gorilla Mux routing using Angular.js I can't seem to get my routing right. I'm using Gorilla Mux and I'm trying to serve my angular app, so basically my index.html, from any url except them starting with "/foo".
This one works:
func StaticFileServer(w http.ResponseWriter, r *http.Request) {
  http.ServeFile(w, r, config.dir)
}

func main() {

  fs := http.Dir(config.dir)
  fileHandler := http.FileServer(fs)

  router = mux.NewRouter()

  router.Handle("/foo/page", PublicHandler(handler(getAll)).Methods("GET")
  router.Handle("/foo/page/{id}", PublicHandler(handler(getOne)).Methods("GET")

  router.PathPrefix("/{blaah}/{blaah}/").Handler(fileHandler)
  router.PathPrefix("/").HandlerFunc(StaticFileServer)

  ...
}

But there must be an easier way than to explicitly declaring every possible route, like this PathPrefix("/{blaah}/{blaah}/") thingy...
With this one, any other url than /{blaah}/{blaah}/ returns a 404 page not found, instead of index.html.
So I'd like to get everything served (static files etc.) as long as they can be found, but everything else should return /public/index.html.

A: I was also facing the same issue but if we use Gorilla mux we have a clear solution for this.
Because Angular is a single page application so we have to handle that way. I have two folders client and server. Inside client folder I keep my all angular code and inside server folder I keep all server code so static path to render index.html is "client/dist". Here dist folder is a angular build folder.
Go router code is given below-
 func main {
        router := mux.NewRouter()
        spa := spaHandler{staticPath: "client/dist", indexPath: "index.html"}
        router.PathPrefix("/").Handler(spa)
}

spaHandler implements the http.Handler interface, so we can use it
 to respond to HTTP requests. The path to the static directory and
 path to the index file within that static directory are used to
 serve the SPA in the given static directory.
type spaHandler struct {
    staticPath string
    indexPath  string
}

ServeHTTP inspects the URL path to locate a file within the static dir
 on the SPA handler. If a file is found, it will be served. If not, the
 file located at the index path on the SPA handler will be served. This
 is suitable behavior for serving an SPA (single page application).
func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {

    // get the absolute path to prevent directory traversal
    path, err := filepath.Abs(r.URL.Path)
    if err != nil {
        // if we failed to get the absolute path respond with a 400 bad request
        // and stop
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    // prepend the path with the path to the static directory
    path = filepath.Join(h.staticPath, path)

    // check whether a file exists at the given path
    _, err = os.Stat(path)
    if os.IsNotExist(err) {
        // file does not exist, serve index.html
        http.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath))
        return
    } else if err != nil {
        // if we got an error (that wasn't that the file doesn't exist) stating the
        // file, return a 500 internal server error and stop
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    // otherwise, use http.FileServer to serve the static dir
    http.FileServer(http.Dir(h.staticPath)).ServeHTTP(w, r)
}

A: I'm a bit late, but other people may find my answer useful.
Basically Gorilla Mux is doing all of your routings here. I'm assuming you want AngularJS to do the routing for any URL that doesn't start with "/foo".
You can use regex to send any requests that doesn't start with "/foo" to your index.html using:
router.PathPrefix("/{_:.*}").HandlerFunc(StaticFileServer)


text:
Q: Insert data Into MS Access database table using SQL I am trying to insert data into a table in my MS Access database.
When doing so MS Access informs me that I am about to append 1 row.
When I return to the table to check the data I still have a blank table.
If I click on the Filters on the table I can see my data as options but they will not show up in the actual table.
INSERT INTO PATIENTS (PatID, FirstName, LastName, Age, Phone, InsuranceCompany)
VALUES (00000090, 'Luke', 'Howell', 42, 7709999785, 'Blue Cross Blue Shield' );

A: When the INSERT runs without error, but also without actually adding a row to the table, that could be the result of a key violation.  However Access won't notify you if you're using DoCmd.RunSQL to execute the statement.  In other situations, a notice could be suppressed if you have turned SetWarnings off.
Run your INSERT with the DAO.Database.Execute method and its dbFailOnError option.  Also make sure SetWarnings is on ...
Dim strInsert As String
strInsert = "INSERT INTO PATIENTS (PatID, FirstName, LastName, Age, Phone, InsuranceCompany) " & _
    "VALUES (00000090, 'Luke', 'Howell', 42, 7709999785, 'Blue Cross Blue Shield' );"
Debug.Print strInsert '<- view this in Immediate window; Ctrl+g will take you there
DoCmd.SetWarnings True
CurrentDb.Execute strInsert, dbFailOnError

A: So I Figured It Out.
I Was Not In The "Datasheet View"


text:
Q: View Jmeter results in Bitbucket I would like to know what is the right way to view jmeter results in Bitbucket. Is it possible to also integrate results with slack?
Thanks in advance!

A: I don't think it's possible.
If you run your JMeter test in command-line non-GUI mode like:
jmeter -n -t test.jmx -l result.jtl -e -o report

The report folder will contain JMeter's HTML Reporting Dashboard and it will be possible to export it as a build artifact so you and your colleagues would be able to download it and analyze.
Unfortunately currently displaying HTML reports directly in the pipeline page is not supported, you can express your interest in the feature here of you want it to be implemented ever.
If you want to fail your pipeline if test results don't meet your expectations (i.e. response time is higher than expected or percentage of errors exceeds threshold) you can consider switching to an alternative way of launching a JMeter test like via JMeter Maven Plugin or via Taurus tool with Pass/Fail Criteria subsystem enabled


text:
Q: Vertical skip after the hline I have a problem with my table. Basically, I would like to leave a medium skip after the hline before the name of the models (i.e. after the line and before 1. Female).
I tried:
\documentclass{article}
\usepackage{rotating}
\begin{document}
\begin{sidewaystable}
\centering
\footnotesize{
\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}
\caption{\textbf{Sensitivity Analysis II}\label{table5}}
\begin{tabular}{l*{5}{c}}
\hline\hline
&\multicolumn{1}{c}{\textbf{Fst Stage}}&\multicolumn{2}{c}{\textbf{Snd Stage}}&\multicolumn{1}{c}{\textbf{LL}}&\multicolumn{1}{c}{\textbf{$\rho$=0}} \smallskip \\
 &\multicolumn{1}{c}{\textbf{Lagged SF}}&\multicolumn{1}{c}{\textbf{SF}}&\multicolumn{1}{c}{\textbf{Fairness}}& &\\
 &\multicolumn{1}{c}{\textbf{(Country Level)}}&&&&\\
\hline \medskip
1. Female &0.012***& 0.009***& 0.1999***&3,504.223& -0.053***\\
2. Male \medskip\\
3. Europe\\
4. Africa\\
5. Asia\\
6. North America\\
7. South America\\
8. Others \medskip \\
9. Left-Oriented\\
10. Right-Oriented \medskip \\
11. Competition is bad\\
12. Competition is good \medskip \\
13. Married \\
14. Single\medskip \\
15. Turst Others\\
16. No Trust Others \smallskip\\
\hline\hline
\multicolumn{6}{l}{\footnotesize * \(p<0.10\), ** \(p<0.05\), *** \(p<0.01\)}\\
\multicolumn{6}{l}{\footnotesize Standard errors in parentheses}\\
\end{tabular}}
\end{sidewaystable}
\end{document}

Apparently it does not work. No matter where I try to put that skip (before or after hline or after &\multicolumn{1}{c}{\textbf{(Country Level)}}&&&&\\) I cannot leave any skip after the hline.

A: You can use \noalign:
\documentclass{article}

\begin{document}

\begin{tabular}{l*{5}{c}}
\hline\hline
blb\\
\hline\noalign{\medskip}
1. Female &0.012***& 0.009***& 0.1999***&3,504.223& -0.053***\\
\end{tabular}

\end{document}

A: Adding a couple of \\seems to introduce some space. You can add medskip, or vspace{<length>}or other vertical spaces also, even negative.
\documentclass{article}
\usepackage{rotating}
\begin{document}
\begin{sidewaystable}
\centering
\footnotesize{
\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}
\caption{\textbf{Sensitivity Analysis II}\label{table5}}
\begin{tabular}{l*{5}{c}}
\hline\hline \\
&\multicolumn{1}{c}{\textbf{Fst Stage}}&\multicolumn{2}{c}{\textbf{Snd Stage}}&\multicolumn{1}{c}{\textbf{LL}}&\multicolumn{1}{c}{\textbf{$\rho$=0}} \smallskip \\
 &\multicolumn{1}{c}{\textbf{Lagged SF}}&\multicolumn{1}{c}{\textbf{SF}}&\multicolumn{1}{c}{\textbf{Fairness}}& &\\
 &\multicolumn{1}{c}{\textbf{(Country Level)}}&&&&\medskip\\
\hline  \\
1. Female &0.012***& 0.009***& 0.1999***&3,504.223& -0.053***\\
2. Male \\
3. Europe\\
4. Africa\\
5. Asia\\
6. North America\\
7. South America\\
8. Others \medskip\\
9. Left-Oriented\\
10. Right-Oriented \medskip \\
11. Competition is bad\\
12. Competition is good \medskip \\
13. Married \\
14. Single\medskip \\
15. Turst Others\\
16. No Trust Others \smallskip\\
\hline\hline\\
\multicolumn{6}{l}{\footnotesize * \(p<0.10\), ** \(p<0.05\), *** \(p<0.01\)}\\
\multicolumn{6}{l}{\footnotesize Standard errors in parentheses}\\
\end{tabular}}
\end{sidewaystable}
\end{document}

A: Here are some improvements and a simplification of the code of your table. The row numbers are automated and right-aligned, emulating  an enumerate environment, so that the text in the first column is always left-aligned. I also used booktabs, which makes some vertical padding around horizontal lines in tables, and defines an adjustable \addlinespace command , that allows easily separating groups of rows. Last, the makecell package allows for line breaks inside cells, and a common formatting of column/row heads.
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{rotating}
\usepackage{caption, booktabs, makecell}
\usepackage{eqparbox}
\renewcommand\theadfont{\bfseries}
\captionsetup{font=bf}
\begin{document}

\begin{sidewaystable}
  \newcounter{rownum}\setcounter{rownum}{0}
  \setlength\defaultaddspace{1.25ex}
  \centering
  \footnotesize{
    \def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}
    \caption{Sensitivity Analysis II}\label{table5}
    \begin{tabular}{>{\refstepcounter{rownum}\eqmakebox[R][r]{\therownum.}\hskip\labelsep}l*{5}{c}}
      \toprule\midrule
      \multicolumn{1}{c}{}& \textbf{1\textsuperscript{st} Stage} &\multicolumn{2}{c}{\textbf{2\textsuperscript{nd} Stage}}& \textbf{LL}& \boldmath$ \rho=0 $ \\
      \multicolumn{1}{c}{} & \thead{Lagged SF & & & & \\(Country Level)}&\multicolumn{1}{c}{\textbf{SF}}&\multicolumn{1}{c}{\textbf{Fairness}}& &\\
      \cmidrule(lr){1-6}
      \addlinespace
      Female & 0.012*** & 0.009*** & 0.1999*** & 3,504.223 & -0.053*** \\
      Male\\
      \addlinespace
      Europe\\
      Africa\\
      Asia\\
      North America\\
      South America\\
      Others\\
      \addlinespace
      Left-Oriented\\
      Right-Oriented\\
      \addlinespace
      Competition is bad\\
      Competition is good\\
      \addlinespace
      Married \\
      Single\\
      \addlinespace
      Trust Others\\
      No Trust Others\\
      \midrule\bottomrule
      \addlinespace
      \multicolumn{6}{l}{\footnotesize * \(p<0.10\),\quad ** \(p<0.05\),\quad *** \(p<0.01\)}\\
      \multicolumn{6}{l}{\footnotesize Standard errors in parentheses}\\
    \end{tabular}}
\end{sidewaystable}

\end{document}


text:
Q: std::set::emplace complaining about deleted copy constructor Suppose I have the following class in a header file:
//Minimized example to show the issue
class Foo
{
public:
    Foo(); //implemented in .cpp
    Foo(Foo const &foo) = delete;
    Foo(Foo &&foo); //implemented in .cpp
private:
    //member variables
}

I wrote a function that takes in Foo && as a parameter and emplaces
it to a set. Which looks like this:
void bar(Foo &&foo)
{
    //std::set<Foo> mySet defined elsewhere
    mySet.emplace(foo); //Compiler complains using deleted copy ctor
}

The compiler would complain my code was using the =delete'd copy ctor, but
if I change the function body to:
mySet.emplace(std::move(foo));

everything becomes fine.
Why does calling std::move on foo solve this problem?
I'm using Windows 10 and VS 2017.
I found std::unordered_map::emplace issue with private/deleted copy constructor but that was using gcc and might be outdated.
Thanks in advance.


text:
Q: Drawing multiple Tables with one Stage One question currently I am working on a team size seletion screen, So far I did it with checkboxes for team one is finished. Now next to that I wanted to draw another table with the same stage, I don't want to draw with a new Stage in order to save ressources. So my question is it Possible to draw multible tables with one stage next to each other? This is what I currently tried but it didn't work.
So I tried to give a second Table to the constructor something like:
stage.addActor(table,table2)

which did not work.
My second try was something like
stage.addActor(table);
stage.addActor(table2);

which did not work either.
public class TeamSelectScreen implements Screen {

    public SEPGame game;
    public SpriteBatch menuBatch;
    public AssetManager assetManager;
    public Viewport viewport;
    public Stage stage;
    public MenuScreen menuScreen;
    public ButtonGroup<CheckBox> teamSelect;
    public CheckBox Tank1;
    public CheckBox Tank2;
    public CheckBox Tank3;
    public CheckBox Tank4;
    public CheckBox Tank5;

    public TeamSelectScreen(SEPGame game) {
        game = new SEPGame();
        menuBatch = new SpriteBatch();
        assetManager = new AssetManager();
        viewport = new FitViewport(SEPGame.WORLD_PIXEL_WIDTH, SEPGame.WORLD_PIXEL_HEIGHT);
        menuScreen = new MenuScreen(game);
        menuScreen.dispose();

        stage = new Stage(viewport, menuBatch);

        Gdx.input.setInputProcessor(stage);
        assetManager.load(Assetdescriptor.backGround);
        assetManager.load(Assetdescriptor.buttonNotePressed);
        assetManager.load(Assetdescriptor.buttonPressed);
        assetManager.load(Assetdescriptor.skinUI);
        assetManager.finishLoading();

    }

    public void setupScreen() {
        TextureAtlas menuUi = assetManager.get(Assetdescriptor.backGround);
        Skin uiSkin = assetManager.get(Assetdescriptor.skinUI);
        TextureRegion backGroundRegion = menuUi.findRegion(Regionnames.backGround);
        Table table = new Table();
        Table table2 = new Table();
        Label title = new Label("Team Auswahl", uiSkin);

        Tank1 = new CheckBox("Tank 1 Player", uiSkin);
        Tank2 = new CheckBox("Tank 2 Player", uiSkin);
        Tank3 = new CheckBox("Tank 3 Ki", uiSkin);
        Tank4 = new CheckBox("Tank 4 Ki", uiSkin);
        Tank5 = new CheckBox("Tank 5 Ki", uiSkin);

        ChangeListener teamSizeChanger = new ChangeListener() {
            @Override
            public void changed(ChangeEvent event, Actor actor) {

            }
        };

        Tank1.addListener(teamSizeChanger);
        Tank2.addListener(teamSizeChanger);
        Tank3.addListener(teamSizeChanger);
        Tank4.addListener(teamSizeChanger);
        Tank5.addListener(teamSizeChanger);

        Table checkTable = new Table();
        checkTable.defaults().pad(5);
        checkTable.add(Tank1).row();
        checkTable.add(Tank2).row();
        checkTable.add(Tank3).row();
        checkTable.add(Tank4).row();
        checkTable.add(Tank5).row();

        Table checkTable2 = new Table();
        Table checkTable3 = new Table();
        Table checkTable4 = new Table();
        Table checkTable5 = new Table();

        // Team 1
        table.add(checkTable);
        table.padRight(1200);
        table.setFillParent(true);
        table.pack();
        table.setBackground(new TextureRegionDrawable(backGroundRegion));

        // Team 2
        table2.add(checkTable2);
        table2.padRight(1000);
        table.setFillParent(true);
        table.pack();

        // Add 2 Tables?
        stage.addActor(table);
        stage.addActor(table2);

    }

    @Override
    public void show() {

    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        menuScreen.dispose();
        setupScreen();
        stage.draw();
    }
}

A: You're calling table.setFillParent(true) twice but never table2.setFillParent(true).
Another option would be adding a Stack with fill parent to the stage and then adding the two tables to the stack:
Stack stack = Stack(table, table2)
stack.setFillParent(true)
stage.addActor(stack)


text:
Q: Is there a clean way to remove the common ruby object initialization code? Is there a clean way to iterate over the attr_reader attributes and set them?
class Foo
  attr_reader :bar, :baz, ...

  def initialize attrs
    @bar = attrs[:bar]
    @baz = attrs[:baz]
    .
    .
    .

A: If you want the hash keys matches the attribute name, one possibility is to inherit a struct:
class Foo < Struct.new(:bar, :baz, keyword_init: true) # Note the "keyword_init" parameter
end

puts Foo.new(bar: 42, baz: :foo).bar
# => 42

Struct will also create public writers, so if you want them not to be public you have to set them private
FOO_ATTRS = [:bar, :baz]
class Foo < Struct.new(*FOO_ATTRS, keyword_init: true) # Note the "keyword_init" parameter
  # Make method 'my_attribute=' private if needed
  private *FOO_ATTRS.map { |attr| "#{attr}=" }
end

puts Foo.new(bar: 42, baz: :foo).bar

If you want to rename hash keys for a different attribute name:
class Foo
  INITIAL_ATTRS = {
   foo: :@bar,
   bar: :@baz
  }

  attr_reader *(INITIAL_ATTRS.values.map { |k| k.to_s.delete('@').to_sym })

  def initialize attrs
    attrs.slice(*INITIAL_ATTRS.keys).each do |var, value|
      instance_variable_set(INITIAL_ATTRS[var], value)
    end
  end
end

EDIT
Another possibility is to use private attr_writer so you don't have to deal with @ tricks
class Foo
  INITIAL_ATTRS = {
   foo: :bar,
   bar: :baz
  }

  attr_reader *(INITIAL_ATTRS.values)

  def initialize attrs
    attrs.slice(*INITIAL_ATTRS.keys).each do |var, value|
      send("#{INITIAL_ATTRS[var]}=", value)
    end
  end

  private

   attr_writer *(INITIAL_ATTRS.values)
end

Note that if you don't want to translate foo to bar you can use an array instead of a hash for INITIAL_ATTRS. This would simplify the code by removing .values and .keys
class Foo
  INITIAL_ATTRS = [:foo, :bar]

  attr_reader *INITIAL_ATTRS

  def initialize attrs
    attrs.slice(*INITIAL_ATTRS).each do |var, value|
      send("#{var}=", value)
    end
  end

  private

   attr_writer *INITIAL_ATTRS
end


text:
Q: Reference or example using SkinId with TMS Intraweb Components There is a property in the TIWDBAdvWebGrid component called SkinId.  I wasn't able to find documentation for it, and wonder if the TMS Intraweb components are skinnable, and if so, how its done.  Any link to documentation or brief explanation would be much appreciated.

A: Visit CGDevTools they have a jQuery components suite to use with Intraweb all with theme support for professional skin user interface.

A: I have learned that skins are not supported with Intraweb at this time.


text:
Q: Qual a finalidade do método OnModelCreating e como ele funciona? Estou estudando Fluent API e estou com essa dúvida, vi que este método pode ser vazio, sem nenhuma implementação. Então qual a utilidade dele e como funciona o método OnModelCreating que fica na classe de contexto que pertence a classe DbContex?

A: Segundo a documentação da MSDN a respeito:

This method is called when the model for a derived context has been initialized, but before the model has been locked down and used to initialize the context. The default implementation of this method does nothing, but it can be overridden in a derived class such that the model can be further configured before it is locked down.

Traduzindo:

Este método é chamado quando o modelo para um contexto derivado foi inicializado, mas antes que o modelo foi bloqueado e usado para inicializar o contexto. A implementação padrão deste método não faz nada, mas pode ser substituído em uma classe derivada de tal forma que o modelo pode ser ainda configurado antes de ser bloqueado.

Ele serve para definir associações extras entre modelos, chaves primárias, estrangeiras, realizar algumas ações de verificação sobre o contexto, etc.
As associações são definidas através da Fluent API.
Opinativamente falando, trabalhar com o OnModelCreating é menos interessante que definir as associações dentro de cada Model através de atributos. Isto porque, conforme o sistema cresce, a complexidade de configuração da base por este método do contexto vai aumentando, e a manutenção fica mais difícil.
Temos várias respostas a respeito da Fluent API aqui no site. Acho que vale a pena dar uma olhada.