CreateWindowEx function fails but GetLastError() returns ERROR_SUCCESS

Question: I am trying to create a simple window with C/C++ using the native Windows message queue system (without .NET). I followed the MSDN tutorial and wrote some basic code that creates an empty window:
void main()
    {
    HINSTANCE hinst;
    HWND hwndMain;
    WNDCLASSEX wnd;
    MSG msg;

    hinst = GetModuleHandle( NULL );
    memset( &wnd, 0, sizeof( wnd ) );
    wnd.cbSize = sizeof( wnd );
    wnd.lpszClassName = "MainWClass";
    wnd.lpfnWndProc = MainWProc;
    wnd.hInstance = hinst;
    int result = RegisterClassEx( &wnd );
    if( !result )
    {
        printf("RegisterClassEx error: %d\r\n", GetLastError() );
    }

    hwndMain = CreateWindowEx
        (
        0, //extended styles
        wnd.lpszClassName, //class name
        "Main Window", //window name
        WS_OVERLAPPEDWINDOW | WS_HSCROLL | WS_VSCROLL | WS_MINIMIZEBOX, //style tags
        CW_USEDEFAULT, //horizontal position
        CW_USEDEFAULT, //vertical position
        CW_USEDEFAULT, //width
        CW_USEDEFAULT, //height
        (HWND) NULL, //parent window
        (HMENU) NULL, //class menu
        (HINSTANCE) wnd.hInstance, //some HINSTANCE pointer
        NULL //Create Window Data?
        );

    if( !hwndMain )
    {
        printf("Oh shi- %d\n", GetLastError() );
    }
    ShowWindow( hwndMain, SW_SHOWDEFAULT );
    UpdateWindow( hwndMain );
}

When I run/debug the program, CreateWindowEx returns 0 which means it failed. This triggers the error message "Oh shi- [error code]". The most confusing part is that the error message prints to console:

Oh shi- 0

The error code returned by GetLastError() is 0, which is ERROR_SUCCESS!
I am at a total loss; what is happening? I am so confuse...
P.S.
I am using Visual C++ Express 2010 on Windows 7 32-bit. I have written a Windows Procedure elsewhere but it simply returns 0 for all cases. If, however, anyone wants to see it, I will be happy to show it.
I have changed the Project Default character set of my Visual C++ project to "Not Set". I should not need to prefix L to my things.
Edit: added wnd.hInstance = hinst;
Edit: removed the unnecessary (WNDPROC) cast
Edit: added error checking for RegisterClassEx
It turns out that the problem was with Visual C++ Express (or at least not with the code itself). I copied the code to another project and it worked.
Comment: I suppose you're intentionally not using the Visual Studio wizard/templates for educational purposes? Also, `void main()` is not valid C++.
Comment: Yes, I want to get a basic idea of how to use the native Windows message queue system before I start using wizards. The void return type of my main() function should have no bearing on the CreateWindowEx() function even if it is not supposedly valid.
Comment: @CodyGray, which modern versions of Windows are you talking about? Windows 7 at least still supports non-Unicode applications... All hell would break loose if half of the applications in use would stop working.
Comment: I'm not saying you should use the wizard code without understanding it! :-) It's just that this boilerplate stuff is tricky enough to understand without *also* trying to type it all correctly.
Comment: @Joshua: in order to learn good, you need to stop using techniques that prevent learning. `void main` in one such. in absolute terms it's not that bad (it merely prevents the code from compiling with g++ and other compilers), but it is an **acceptance** of Microsoft lock-in coding patterns, and when you accept any of that, you're likely to accept more of it, and so on, and those coding patterns are really really bad (e.g., the error handling in the wizard generated code for window, Does Not Work). In particular, stop using those **C casts**. At once. They hide errors. Cheers & hth.,
Comment: I mostly agree with what Alf says, except that when writing Win32 code, you are often forced to do non-portable, Microsoft-lock-in things. But `void main` is not one of them: the standard code doesn't declare the function that way. Neither are C-style casts. **Never** cast your window procedure function pointer to `WNDPROC`. That just hides errors. Everything should compile without a cast. As for Unicode, as I mentioned in a comment below, you *have* to compile the code as Unicode in order to get it to run on a modern version of Windows. That means either prefixing with `L` or macros.
Comment: Not using Unicode for the character set is irrelevant if you are only programming for Windows, which I am. Windows doesn't break if you don't use Unicode.

Anyway, it turns out it was to do with Visual C++ Express...I created a new project, copied the code over and it worked. How do I close this question?
Comment: a really lazy solution to this is `if (msg == 36 || msg == 129 || msg == 130 || msg == 131) return DefWindowProc(hWnd, msg, wParam, lParam);
    }` at the start of your WndProc. Good for troubleshooting.
Comment: An interesting way to fall into this issue is by trying to assume you get a chance to call `SetWindowLongPtr(hWnd, 0, (LONG_PTR)extradataptr` before any messages get sent to the window by having wndproc call GetWindowLongPtr(hWnd, 0) and have the window get an access violation trying to read the nonexisting `cbWndExtra` data. This happened while I was trying to simulate Java awt/swing JFrame by passing a pointer to an unordered_map as cbWndExtra data; which would be ok if i checked if it was not a null pointer; I added the null check(with DefWindowProc) and everything worked.
Answer: wnd.lpfnWndProc = (WNDPROC) MainWProc;

We can't see the real reason you need to use the cast but it is very fishy.  Windows returns 0 from GetLastError() if it didn't see anything going wrong.  Which can happen if the window procedure is broken.  Like this one:
LRESULT CALLBACK MainWProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    return 0;
}

Windows sends the WM_NCCREATE message to ask for the window to be created.  If that message doesn't get processed then there will be no window.  And no error.  Fix:
LRESULT CALLBACK MainWProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
   return DefWindowProc(hWnd, uMsg, wParam, lParam);
}

Tweak as necessary to customize the window.  Just make sure that DefWindowProc() gets called for every message that you don't want to handle yourself.  And keep Petzold close at hand to avoid the simple mistakes.  And lose the cast.
Comment: @NickMiller `PostQuitMessage` is _not_ called when your window is X'd out. You'll receive a `WM_CLOSE` message for the window, and you'll need to call `PostQuitMessage` in that handler.
Comment: WM_DESTROY is best.  No more main window => quit program.
Comment: Thanks for the feedback! I removed the WNDPROC cast but the problem persisted. Turns out the problem was with Visual C++ (or at least not with the code) since it worked after I copied the code to another project.

P.S. When I said the Window Procedure returns 0 for all cases, I did not mean that it merely has one line of return 0; code. I had a valid Window Procedure case-switch that returns DefWndowProc by default. Thank you!
Comment: Great this helped a lot!  Do you know if the default window procedure will terminate the message loop when closed via the 'x'?  My message loop only translates and dispatches messages, so my assumption is that it would exit when the PostQuitMessage is sent.  I don't know if this is sent when the 'x' is clicked (or other methods such as Alt+F4).
Answer: All modern versions of Windows use Unicode internally, and by default, Visual Studio projects #define _UNICODE/UNICODE, which causes your application to link to the Unicode versions of the Windows headers.
When you're compiling an application as Unicode, however, the character (and thus "string") types are different. Instead of char, they're now wchar_t. That means that you have to explicitly declare your string literals as long strings by prefixing them with an L.
Alternatively, the Windows headers hide all of this behind macros, but it's no longer necessary because Windows has been Unicode for a long time and that's very unlikely to change.
Beyond that, you're missing several things in your initialization of the WNDCLASSEX structure, like the hInstance member. These things all have to be set perfectly, or things will fail. As well, the RegisterClass(Ex) and CreateWindow(Ex) functions must be passed the exact same string values corresponding to the name of the window class, otherwise they will assume you're talking about two different things. Typos are not forgiven!
I highly recommend that you use the Visual Studio wizards to create a blank (but working!) project template.
The correct boilerplate code goes something like this:
#include <windows.h>
#include <tchar.h>

// Define these here to minimize typos, or preferably, load them from a
// resource file at the top of the main function
#define MYCLASSNAME    TEXT("MainWndClass")
#define MYWINDOWNAME   TEXT("Main Window")

// Global variable to keep track of your hInstance
HINSTANCE g_hInstance;

LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
   // If you don't process any of the messages yourself, you
   // must pass them to DefWindowProc for default handling.
   return DefWindowProc(hWnd, uMsg, wParam, lParam);
}

int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
                       LPTSTR lpCmdLine, int nCmdShow)
{
    // Save the instance handle in a global variable.
    g_hInstance = hInstance;

    // Register your window class.
    // (A full-featured app will probably want to set additional members.)
    WNDCLASSEX wcex = {0};
    wcex.cbSize = sizeof(wcex);
    wcex.lpfnWndProc = WndProc;
    wcex.hInstance = hInstance;
    wcex.lpszClassName = MYCLASSNAME;
    if (!RegisterClassEx(&wcex))
    {
        MessageBox(NULL, TEXT("Call to RegisterClassEx failed!"), NULL, MB_OK);
        return 1;
    }

    // Create your main window.
    HWND hwndMain = CreateWindowEx(0, MYCLASSNAME, MYWINDOWNAME, WS_OVERLAPPEDWINDOW,
                                   CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL,
                                   hInstance, NULL);
    if (!hwndMain)
    {
        MessageBox(NULL, TEXT("Call to CreateWindowEx failed!"), NULL, MB_OK);
        return 1;
    }

    // Show your main window.
    ShowWindow(hwndMain, nCmdShow);
    UpdateWindow(hwndMain);

    // Run the main message loop.
    BOOL bRetVal;
    MSG msg;
    while ((bRetVal = GetMessage(&msg, NULL, 0, 0)) != 0)
    {
        if (bRetVal == -1)
        {
            MessageBox(NULL, TEXT("Error encountered in message loop!"), NULL, MB_OK);
            return 1;
        }
        else
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

    return (int) msg.wParam;
}

Comment: I have changed the Project Default character set to "Not Set". I also do not own a non-Express version of Visual Studio which is why I cannot use wizards =(

I have got a dispatch message loop elsewhere but I have not included it because it would not work anyway since CreateWindowEx is not succeeding in the first place.
Comment: You don't want "Not Set". You want Unicode; it's the default. All versions of Windows NT are natively Unicode. The last version of Windows that used non-Unicode ("ANSI") applications was Windows 98. I doubt you're running that still. Things will not work unless you compile as Unicode. If you don't like all the `TEXT()` macros, etc. you can just prefix string literals with an `L`. Fair enough about Express, though. The sample code I posted should work out of the box.
Comment: @CodyGray, the last version of Windows that didn't natively support Unicode was Windows ME. Anyway, all systems based on Windows 2000 support both Unicode and non-Unicode applications.
Answer: In my case i had to handle WNC_NCCREATE manually. DefWindowProc returned zero for WNC_NCCREATE, i fixed that with:
LRESULT CALLBACK MainWProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    if (uMsg == WNC_NCCREATE)
        return true;
    return DefWindowProc(hWnd, uMsg, wParam, lParam);
}

Answer: Try initializing all of the members/properties of the window class. In other words, set the remaining members. For example:
winclass.lpfnWndProc = WinProc1;
winclass.hInstance = hInstance;
winclass.hbrBackground = CreateSolidBrush(RGB(250,250,250));
winclass.lpszClassName = "mwClass";
winclass.lpszMenuName = NULL;
winclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
winclass.hCursor = LoadCursor(NULL, IDC_ARROW);
winclass.style = CS_DBLCLKS | CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
winclass.cbClsExtra = 0;
winclass.cbWndExtra = 0;

Just change the class name as needed.
Comment: The code in question already zero-initializes the `WNDCLASSEX` structure, so doing it all over again is rather pointless. Besides, if window class registration failed, the call to `CreateWindowEx` would fail, but have `GetLastError` return a non-zero value. The problem this proposed answer attempts to fix is not the problem the question is asking about.
Comment: By the way, WNDCLASSEX wcex = {0} does not initialize all of the memory occupied by the object. I also had this problem and when I initialized all of the members of the window class, the window appeared.
Comment: The OP is calling `memset`. Regardless, `WNDCLASSEXW wcex = {0};` zero-initializes ALL memory. It's a hard language rule, and I don't know of a single compiler that fails this. Though zero-initialization isn't sufficient for the `EX` version; you'll also need to properly set its `cbSize` member (which this proposed answer doesn't). Some contributions are best just deleted. This is one of those.
Answer: I had the same problem.
In my case its just that i used visual sutdio without admin rights.
And i discovered that in this case i cant debug my application.
In debug mode without admin right, CreateWindowEx return null with error code result to 0 like you.
But if you go to your build directory you can use your app (not in debug mode).
So if this the case fro you too, just start visula studio with admin right and its done.
I think there is almost a way to use visual studio debug mode with admin right without start visual stuido with admin password each time. i dont know how to do that, but i think it may be possible.


How Video streaming is implemented in popular online education websites

Question: I need to build a web based video player. Something like coursera/udemy. I would like to know the following.

Where we can store videos (Blob,Db..etc)?
Say I uploaded video in Blob storage. How can I make sure nobody is able to download this videos?
What should be an ideal video streaming architecture(BE+FE) if I am expecting 500 concurrent users?
Do I really need to build a video streaming Back End or I can simply use services like vimeo to get this done?
I inspected how Udemy is doing, i could find the following. It looks like they are using some blob to store videos. But when I tried to access this directly it says I cannot. How this works?
Answer: There can be no way to protect your video from a determined sophisticated hacker. In the very worst case, they can record the video from their screen using a iPhone.
You can learn more about blob: URL e.g. here. The bottom line: it's a browser-side object, it's not to store videos.
You definitely can use streaming services, but this will even further reduce your control. OTOH, it's not worth your effort to develop some new streaming architecture if you only expect 500 concurrent streams.
Comment: Thanks. Finally i decided to go with vimeo


Como fazer uma div que se expande e mostra o conteúdo oculto?

Question: Quero fazer um bloco que expanda para baixo dando informações de festa e eventos, mas estou com muita dificuldade, pois não sei como fazer 2 divs ativarem ao mesmo tempo o mouse over.
esse é meu código html:

25/02/2014

A-TRAIDOS

E esse é o código CSS:
#eventos{
    width:810px;
    height:500px;
    background:#666;
    float:left;

}

.eventos-blocos{
    width:250px;
    height:100px;
    float:left;
    background-color:#CCC;
    margin:8px;
    border:2px solid #FFF;
    transition:all 700ms;
    -moz-transition:all 700ms;
    -o-transition:all 700ms;
    -webkit-transition:all 700ms;
    position:relative;
    top:0px;
    left:0px;

}

.eventos-blocos:hover{
    border:2px solid #0C9;
    height:150px;

}

.eventos-blocos p{
    font-family:Tahoma, Geneva, sans-serif;
    font-size:10px;
    color:#FFF;
    animation-direction:alternate;
    margin-bottom:-20px;
    margin-left:3px;
    margin-top:3px;
}

.eventos-blocos h3{
    font-family:Tahoma, Geneva, sans-serif;
    font-size:14px;
    color:#FFF;
    margin:3px;

}

Quando a div é acionada pelo mouseover a div de baixo sempre se afasta demais, parecendo um bug.
Comment: Pode explicar mais detalhadamente o problema, eu coloquei **[teu código no JSFiddle](http://jsfiddle.net/4vwfjfv2/)** e aparentemente está funcionando corretamente, a única modificação que fiz, foi adicionar um `overflow:hidden` na tua classe `.eventos-blocos`.
Answer: Não entendi muito bem o que tu quer, mas se você quer que as informações apareçam quando é acionado o mouseover você deve colocar:
**overflow:hidden;**

.eventos-blocos{
width:250px;
height:100px;
float:left;
background-color:#CCC;
margin:8px;
border:2px solid #FFF;
transition:all 700ms;
-moz-transition:all 700ms;
-o-transition:all 700ms;
-webkit-transition:all 700ms;
position:relative;
top:0px;
left:0px;
overflow:hidden;

}
Comment: Cara, muito obrigado, consegui.. \õ/


Unsolicited SSH connection

Question: I've have had an Ubuntu 8.04 server running and on the Internet for a few days....I have Ports 21 and 22 open for FTP and SSH...All other ports are closed.
I ran
netstat

And found this
Active Internet connections (w/o servers)

Proto Recv-Q Send-Q Local Address           Foreign Address         State

tcp6       0     68 10.7.1.71%134645824:ssh 184.108.40.206%8:47777 ESTABLISHED

It appears as if 18.104.22.168 has established an SSH connection to the server...and is sending packets out... Is it possible for someone to establish an SSH connection without  authenticating?
I did Reverse DNS lookups on the address...and it seems to oringnate from China according to this resource...
http://www.ipaddresser.com/

I assume most servers are fending off stuff like this all the time, but is it unusual to have someone sit on a port like this? And is there an way to block certain IP's at the server level?
The server is sitting behind a substantial Cisco firewall ..
Answer: All "ESTABLISHED" means is that the tcp session is open.  It does not mean that they have successfully authenticated.  Nmap, for example, will create a complete, legal TCP session when scanning port 22.  (It's verifying that the daemon is sshd, checking version strings, etc.)  This person could be running a simple port scanner or even attempting to brute-force your passwords.
To figure out what's actually happening, you'll need to spend some quality time with your logs.  Spend most of your time looking for successful and failed logins.  Also just running "who" will let you know if someone is actually logged in via that connection.
The output of last can also be useful.
Answer: Insyte beat me to it.
To drop all connections from that IP:
iptables -A INPUT -s 184.108.40.206 -j DROP
Answer:
Don't run ssh on port 22.
Don't allow connections to whatever port you do run ssh on from the entire internet.
** If you need to connect from random locations install knockd.
Don't run ftp.
Comment: Can I come visit you at your secure mountain compound someday? ;)
Comment: My advice exactly. For even better security than knockd, require an IPSEC VPN connection to network and tunnel your SSH traffic over that. I.e. don't expose your SSH server to the world.
Answer: You can use a package such as BlockHosts to stop all unsolicited connections of this kind.  Here's a nice tutorial - it's for Debian Etch but nearly all of it applies to Ubuntu as well.
Answer: I run a program called fail2ban which reads the logs of common daemons such as ssh and ftp. It uses regular expressions to monitor failed login attempts in those logs, and updates firewall rules to block the ip's of would be intruders.  You can customize the behavior of fail2ban in ways such as how many failed attempts before an ip is blocked and how long it stays blocked.  It works very well and I'm quite pleased with it.  Check it out here.
Though I'm not familiar with gareth_bowles' BlackHosts, I suspect it is similar to fail2ban.
Comment: DenyHosts is a similar thing but extremely easy to install and set up. Also has a online collaboration so you can share your blocked IPs with other servers running DenyHosts and block the baddies that have tried to crack others before they try you. I think fail2ban is a more recognised solution to this problem though.

Unsolicited SSH connection


$\int_{0}^{\infty}e^{-st}h(t)dt=0 \Rightarrow h(t)=0.$

Question: Suppose $h(t)$ is continuous function and $\int_{0}^{\infty}e^{-st}h(t)dt=0 ~\forall~ s>s_{0}$, then prove that $h(t)=0$.
I know "if a function is continuous, non-negative or non-positive, and its integration is zero, then function must be zero", which is intuitively clear.
But here asked question is beyond my knowledge. Here, exponential function is doing some miracle, but how?
Would you like to help me?
Comment: is there any additional condition on $h(t)$ or $s$ ?
Comment: @RealHilbert The down votes aren't surprising considering the criteria used by the community at the moment. Questions must include your thoughts. You basically just said you couldn't get started. I sympathize and I don't even vote according to these criteria, but it as it is.
Comment: Since it doesn't work for a particular $s$, it's probably for every $s> s_0$.
Comment: $s$ can be assumed some positive real number, and no additional condition on $h(t)$.
Comment: This result I needed in order to prove uniqueness of inverse laplace transform.
Comment: its nice to see people here are with limited knowledge, amazed with -ve marking.
Comment: Are you requiring that the integral is $0$ for all $s\gt0$ or just a particular $s$? This kind of information is needed and may be the reason for some of the downvotes.
Comment: @Farnight: yes, I know, but it should be added to the question.
Comment: I don't fee l like typing an answer right now, so [here](http://web.mit.edu/jorloff/www/18.03-esg/notes/laplaceuniqueness.pdf)'s a proof that works for functions bounded by an exponential function.
Comment: @Farnight, haha...thanks for your quick typing and for saving my money. everything is fair but I did not like an additional restriction on function h(t).
Comment: If you have conditions on $h$ such that the integral becomes an holomorphic function with respect to $s$ (with real part greater than $s_0$, say), then you can apply the uniqueness theorem for holomorphic functions. Maybe [Morera's theorem](http://en.wikipedia.org/wiki/Morera%27s_theorem) could be of help...
Answer: Here is an argument:
Technical modification. Fix any $s_1 > s_0$, and let
$$ H_0 (x) = \int_{0}^{x} e^{-s_1 t}h(t) \, dt \quad \text{and} \quad H(x) = e^{s_1 x}H_0 (x). $$
Then $H_0(x)$ is differentiable and $H_0(x) = o(1)$ as $x \to \infty$. Then for any $s > s_1$, we have
$$ \int_{0}^{R} e^{-st} h(t) \, dt
= \left[ e^{-(s-s_1)t} H_0(t) \right]_{t=0}^{t=R} + (s - s_1) \int_{0}^{R} e^{-(s-s_1)t} H_0(t) \, dt. $$
Taking $R \to \infty$, we find that
$$ \int_{0}^{\infty} e^{-st} H(t) \, dt = \int_{0}^{\infty} e^{-(s-s_1)t} H_0(t) \, dt = 0 $$
as well. Moreover, we have an exponential bound $H(x) = o(e^{s_1 x})$. From now on, we work with $H$ instead of $h$.
Main argument. Fix any $s > \max\{s_1, 0\}$. The exponential bound says that $t \mapsto e^{-st}H(t)$ is integrable on $[0, \infty)$. Now for any polynomial $p(x) = \sum a_k x^k$, we have
$$ \int_{0}^{\infty} p(e^{-st})e^{-st}H(t) \, dt = \sum a_k \int_{0}^{\infty} e^{-(k+1)st}H(t) \, dt = 0. $$
Now let $\varphi$ be any continuous function supported on a compact subset of $(0, 1)$. By the Stone-Weierstrass theorem, we can approximate $\varphi$ by a polynomial w.r.t. the supremum norm. So
$$ \left| \int_{0}^{\infty} (p(e^{-st}) - \varphi(e^{-st})) e^{-st}H(t) \, dt \right| \leq \| p - \varphi\|_{\infty} \int_{0}^{\infty} e^{-st}|H(t)| \, dt. $$
shows that, by taking $p \to \varphi$, we have
$$ \int_{0}^{\infty} \varphi(e^{-st})e^{-st}H(t) \, dt = 0 $$
as well. Now the integrand of the LHS is zero outside some compact interval, hence by an easy modification of the fundamental theorem of calculus of variation shows that $H \equiv 0$. Consequently, $h \equiv 0$ as well.
Comment: Appreciate your efforts. I will take some time to understand your proof as I am not pure mathematician.
Comment: (+1) Nice application of some useful machinery (Stone-Weierstrass and FTCoV). By finding an explicit approximation to $\delta(x-\alpha)$ that is made up of functions orthogonal to $h(x)$, some of the machinery is not required.
Comment: @robjohn, Thank you. I agree that Bernstein polynomial gives a short-cut proof. (Even some versions of Stone-Weierstrass proof exploit this nice family of polynomials, so my proof may be considered indirect.) By the way, depending on what type of integral OP is considering, the technicality I have introduced seems necessary. For example, if $h(x) = e^{x^2} \sin(e^{2x^2})$ then the Laplace transform exists only in improper sense when $s > 0$.
Answer: The assumption is equivalent to
$$
\int_0^\infty e^{-sx}\left(e^{-s_0x}h(x)\right)\,\mathrm{d}x=0\tag{1}
$$
for all $s\gt0$
Since
$$
\begin{align}
\int_0^\infty\left(e^{-x}-e^{-2x}\right)^n\,\mathrm{d}x
&=\int_0^\infty e^{-(n-1)x}\left(1-e^{-x}\right)^n\,\mathrm{d}e^{-x}\\
&=\int_0^1t^{n-1}(1-t)^n\,\mathrm{d}t\\
&=\frac{n!(n-1)!}{(2n)!}\tag{2}
\end{align}
$$
define
$$
f_n(x)=n\binom{2n}{n}\left(e^{-x}-e^{-2x}\right)^n\tag{3}
$$
Then
$$
\int_0^\infty f_n(x)\,\mathrm{d}x=1\tag{4}
$$
Furthermore, for $x\gt0$,
$$
0\lt4\left(e^{-x}-e^{-2x}\right)\le1\tag{5}
$$
and if $x\ne\log(2)$, then the right inequality is strict.
According to $(10)$ from this answer,
$$
\binom{2n}{n}\le\frac{4^n}{\sqrt{\pi(n+\frac14)}}\tag{6}
$$
Combining $(3)$, $(5)$, and $(6)$, we get that for $x\gt0$
$$
0\lt f_n(x)\le\sqrt{\frac{n}\pi}\,\left[4\left(e^{-x}-e^{-2x}\right)\right]^n\tag{7}
$$
so that outside any neighborhood of $\log(2)$, $f_n(x)$ eventually tends monotonically to $0$.
$(4)$ and $(7)$ imply that $\frac{\log(2)}\alpha f_n\left(\frac{\log(2)}\alpha x\right)$ is an approximation of $\delta(x-\alpha)$.
According to the assumption, for any $n$ and $\alpha$,
$$
\int_0^\infty\frac{\log(2)}\alpha f_n\left(\frac{\log(2)}\alpha x\right)\left(e^{-s_0x}h(x)\right)\,\mathrm{d}x=0\tag{7}
$$
Since $h(x)$ is continuous, $(7)$ implies that $h(x)=0$ for $x\ge0$.


Powershell - add string after 14th 24th 36th 46th and 55th character following a word

Question: We have many files which contain header lines beginning with HDR that need to be updated for clarity.  I am new to coding in powershell and would like to know how I can update the code below to accomplish this.
Example:
Before:
HDR,9345561421,20220510,1536838657,20220510,5550810,111003

After:
HDR, INV-9345561421, DATE-20220510, PO-1536838657, DATE-20220510, ORDER-5550810, CUST-111003

Get-ChildItem 'C:\SFTP\Whirlpool\Invoices\*.csv' | ForEach {
     (Get-Content $_) | ForEach  {
    $_.Insert(HDR, ,"INV-").Insert(HDR, .........., ,"NVDATE-").Insert(HDR, .........., ........,  ,"PO-").Insert(HDR, .........., ........, ..........,   ,"PODATE-").Insert(HDR, .........., ........, .........., ........,   ,"ORDER-").Insert(HDR, .........., ........, .........., ........, .......,   ,"SHIPTO-")
} | Set-Content $_
}

The solution below provided by Santiago Squarzon worked perfectly.
$head = 'INV', 'DATE', 'PO', 'DATE', 'ORDER', 'CUST'
foreach($csv in Get-ChildItem 'C:\SFTP\Whirlpool\Invoices\*.csv') {
    $newContent = switch -Regex -File $csv.FullName {
        '^HDR' {
            $i = [ref] 0
            [regex]::Replace($_, ',', { ', ' + $head[$i.Value++] + '-' })
            continue
        }
        Default { $_ }
    }
    Set-Content -LiteralPath $csv.FullName -Value $newContent
}

Comment: The Csvs always have the same number of headers? and, just to clarify, you only want to change the first line of the Csvs (the header) not all lines
Comment: Hello.  Yes.  There will always be 6 items of the same length after the word HDR in each header.  However the header line represents the beginning of a new invoice and it can appear several times within a file as there are several different invoices within each file.
Answer: Assuming you want to replace any line starting with HDR and said line has the same number of items comma-separated (5 commas in total), you could use this call to Replace(String, String, MatchEvaluator):
$head = 'INV', 'DATE', 'PO', 'DATE', 'ORDER', 'CUST'
$line = 'HDR,9345561421,20220510,1536838657,20220510,5550810,111003'
$i = [ref] 0
[regex]::Replace($line, ',', { ', ' + $head[$i.Value++] + '-' })

# Produces this output:
# HDR, INV-9345561421, DATE-20220510, PO-1536838657, DATE-20220510, ORDER-5550810, CUST-111003

You can combine above logic with a switch using the -File parameter to read your files and the -Regex parameter to target the lines starting with HDR (^HDR):
$head = 'INV', 'DATE', 'PO', 'DATE', 'ORDER', 'CUST'
foreach($csv in Get-ChildItem 'C:\SFTP\Whirlpool\Invoices\*.csv') {
    $newContent = switch -Regex -File $csv.FullName {
        '^HDR' {
            $i = [ref] 0
            [regex]::Replace($_, ',', { ', ' + $head[$i.Value++] + '-' })
            continue
        }
        Default { $_ }
    }
    Set-Content -LiteralPath $csv.FullName -Value $newContent
}


Interactive reinforcement learning in R?

Question: Which library in R allows to do interactive temporal (depending on sequence of events) learning?
I need to perform a task similar to game playing as shown in this example:
http://cs.stanford.edu/people/karpathy/convnetjs/demo/rldemo.html
Answer: The correct term you are looking for is "Online Reinforcement Learning" (instead of Interactive). The temporal aspect is implicitly present in nearly each RL problem, hence not mentioned explicitly.
Due to the fact that multiple subdomains have been connected here, I guess that there is no single R package providing all the functionality. The problem solved by Mnih et. al. in Playing Atari with Deep Reinforcement Learning can be broken in multiple pieces.

Input is a single frame / image. So you need a package to transform it into a real matrix and more basic image preprocessing (cropping, scaling etc.)
The State-Action-Value-Function is computed using a deep convolutional neural network, so you need an R package for that one. Architecture described depends on the type of the images.
The surrounding Q-Learning code is very easy (see page 5 for the algorithm), hence I would not bother with wrangling it into calls to an RL package, but write it yourself.

If you are not restricted to R you may find pointers in the other attempts to reproduce the results from the paper

https://github.com/kuz/DeepMind-Atari-Deep-Q-Learner
https://github.com/kristjankorjus/Replicating-DeepMind
https://github.com/spragunr/deep_q_rl

Weakly linked Question: R libraries for deep learning


Android studio orange gradle file

Question: Hi all after a recent commit I noticed two extra folders being generated in my project directory that I have never seen before Image I dont know if I should ignore it or be worried, anyone have any idea? It is an orange gradle file and an orange build file
Answer: The build directory contains e.g. build outputs and intermediate files. The .gradle directory contains e.g. cached versions of your project's dependencies.
These are generated and updated at build time and are nothing to worry about. You should not include them in version control either.
Comment: I think I have included them in version control should I remove them @Iaalto
Comment: They are in the Android Studio default .gitignore but if you have them in version control, it's better that you remove them there. No need to track generated files.

Android studio orange gradle file


Should the response variable meet the assumption of constant variance?

Question: Information about the data:
The tensile strength of a synthetic fibre used to make cloth for men's shirts is of interest to a manufacturer. It is suspected that the strength is affected by the percentage of cotton in the fibre. Five levels of cotton percentage are of interest: 15%, 20%, 25%, 30% and 35%. Five observations were taken at each level of cotton percentage; the 25 observations were run in random order. The data collected from the experiment are given in the table below. Y denotes the response variable, that is, the tensile strength, measured as resistance to a fixed stress on a scale from 0 to 50. The means of Y for the different levels of cotton percentage, and the overall mean response, are also given.
Table

Problem to solve:
The idea is to analyze the data with an analysis of variance.
Let $Y_{ij}$ be the $i$th replicate of the response variable taken at the $j$th level of the factor representing the percentage of cotton. Which of the following assumptions (below) is needed for the analysis to be appropriate? The objective is to justify and explain why the assumptions that have not been chosen are inadequate or otherwise inappropriate.
Assumptions

I have read extensively but I still am confused with the following concepts:-

What does the notation $N(\mu_j,σ^2)$ stand for?
Should the observations from $Y_{ij}$ be from a sample with both a normal distribution and constant variance?
Would it be reasonable to model the relationship between strength and percentage cotton (as a continuous variate) using a simple linear regression model?
Answer:
What does the notation $N(\mu_j,σ^2)$ stand for?

Read as "from a normal distribution with mean $\mu_j$ (mu-j) and variance $\sigma^2$ (sigma-squared)" (i.e. standard deviation $\sigma$). This is simply saying that the mean in each group may differ but the variance is constant, and that the population distributions the samples are drawn from are normal.

Should the observations from $Y_{ij}$ be from a sample with both a normal distribution and constant variance?

On normality:

The individual sample is only five numbers; the sample can't be "normal" as such. It's the population from which the sample is drawn that is assumed to be normally distributed (and then only when it comes to doing hypothesis tests or finding confidence intervals (etc) that make that assumption).

You can't really determine that a sample is drawn from any distribution. You can sometimes tell that it isn't.

Even then, it may not be important that it isn't, since in real situations data are almost never actually drawn from a normal distribution. Our distributional assumptions are generally false, but they may well be reasonable approximate models and may lead us to tests with good properties if the distribution from which the data are drawn are reasonably close to normal (even in cases when we could tell that they aren't).

common situations where we can immediately tell that we don't actually have normal distributions are (a) when the values are necessarily positive (truly normal distributions always include some probability of being less than 0, so if your values can't be negative they can't actually be normal) and (b) when the values are integers (the data are drawn from some discrete distribution but the normal distribution is not discrete). [But as already mentioned, this may not really matter - our models are approximations]

On constant variance:

Similar remarks apply here. The sample standard deviations won't be equal. It's the population from which the sample is drawn that is assumed to have constant variance (or standard deviation).

You can't really determine that the samples are drawn from distributions with the same variance. You can sometimes tell that they aren't.

Even then, it may not be important that it isn't the case, since in real situations the samples are almost never actually drawn from distributions with identical spread -- if the population variances were nearly equal, it won't matter all that much, and when the sample size is the same in every group the test is pretty insensitive to this assumption. In any case, it's possible to do a test that doesn't assume constant variance (for example, via a Welch-Satterthwaite type procedure), and this may very often be a good choice, if you're not confident that the assumption would be reasonable.

Note that if you did sample from distributions that have the same standard deviation, the sample standard deviations would differ, and with small samples like these they could differ quite a bit (you typically expect bigger variation in standard deviation than you have here even when the assumption is exactly true). These standard deviations are reasonably close together and given the equal sample sizes, I wouldn't bother worrying about the assumption any further; it won't present any substantial problems for the properties of the test.

Would it be reasonable to model the relationship between strength and percentage cotton (as a continuous variate) using a simple linear regression model?

It may sometimes be reasonable to do something like that but keep in mind that it's quite possible that the relationship is not linear. Indeed, often in an experiment like this the aim is to find approximately where the outcome (tensile strength in this case) is highest precisely because it's known/believed that it likely occurs "somewhere in the middle" of the range of possible input values (while a linear model would always place the highest strength at one of the ends).
In this case we can readily see that this is the situation here (i.e. relationship isn't anywhere close to linear, and the higher values are not at either end):

Ultimately whether to use something like anova or a linear regression or perhaps some form of curvilinear model depends on what you're trying to achieve (what it is you want to find out) -- the choice should be made before you collect the data you want to use for inference; you should avoid making assumptions that you don't feel confident would be reasonable before you collect the data (whether of normality, constant variance, linearity and so on). [Failing that, at least collect enough data to split the sample so you're not performing inference on the same data you used to pick a model.]
Typically with an industrial process like this you're not "in the dark" as to how the process operates and may well have a good sense of the typical mean and variation in the output as the main input or inputs change, so that you can start such an experiment with tenable assumptions.
Comment: Thank you Glen_b, I am feeling more confident after reading your answer. Many thanks


Using mod_wsgi with mpm_itk: socket permission issue

Question: I'm using mod_itk as MPM for increased security in shared environment. I also have a Firefox Sync Server within one of the VHosts I host. That vhost is restricted to a certain user via AssignUserId user group.
The problem is that the socket /var/run/wsgi...whatever.sock is chmodded srwx------ and owned by Apache's wwwrun. While I configured the vhost with
WSGIProcessGroup sync
WSGIDaemonProcess sync user=djechelon group=djechelon processes=1 threads=5

I still get the error that Apache wants to access a socket that is not accessible and because of this gets an error.
Is it possible to configure mod_wsgi in order to create different sockets with different owners for different applications or to chmod its socket in a different way (less secure)?
Currently, I'm running Firefox Sync as the only WSGI application. Moving it to a vhost that doesn't AssignUserId could solve this problem but will force me to change URL (and buy an additional SSL certificate), so I wouldn't consider this
Answer: You need mod_wsgi 3.3 or later, and the mod_wsgi source must be compiled against a full Apache with developer header files corresponding to the ITK MPM. You cannot use a binary of mod_wsgi compiled against worker or prefork MPM as the ITK support you need is a compile time thing.
Unfortunately the Linux distros who provide ITK MPM variant of Apache as an option, don't seem to provide httpd-dev or apache2-dev package variants corresponding to that same ITK MPM. As a result, people usually end up having to build up their own Apache from source code with ITK MPM and proper header files with ITK version of mpm.h to get it to work.
Comment: Accepted because I gave up on recompiling Apache on a production server :) I simply chose to disable AssignUserId for that vhost. Compromise is the keyword :)


Windows 2003 drops static IP address

Question: Our web server in the past day has dropped two static IP addresses.  When they are dropped, they are still listed in the IP Properties, but if you perform a "cmd" -> "route PRINT" they are not.  Removing the IP from the IP properties, and adding them back corrects this, but any idea on how they are dropping?  There are no helpful entries in the system logs.
Comment: Since @Joe has indicated that this might somehow be hardware/driver-related, I am curious: what make/model of integrated or add-on NIC is this issue affecting, and what is the driver version? Same question goes to Joe.
Comment: try arp -d * Could be something funky going on with your DHCP.
Answer: I encountered a very similar scenario on a 2003 server we have set up.  I ended up having to replace the NIC to correct the issue.  I would not see any entries in the system events, the ip address would just switch from static to dhcp.
Swapping out the NIC solved the issue for me.
Comment: Swapping it out with an identical device, or with one using of a different make/chipset/hardware revision/driver/nvram content?
Comment: It was swapped with an identical device from a decommissioned server.  This was a dell server btw, and while this is the first time I've run into nic issues on server, it is not the first time I've run into nic issues with dell hardware.  I have had several nic issues with Optiplex 740s, especially when running linux.
Comment: @Miles Erickson I can't comment yet directly to your response.  Just to be honest, this was a couple of years ago so I could not honestly say what the make and driver was of the device.  I want to say they were Broadcom NetXtreme cards, but I'm pulling that from old memory.

Windows 2003 drops static IP address


Dúvida group by oracle

Question: Quero fazer um group by entre duas tabelas fazendo um inner join.
A tabela de empregado e a tabela empregado no posto. Eu quero que retorne a mais recente entrada em um posto de um dado empregado. Mas só estou conseguindo isso tendo que suprimir duas colunas da query, que é o posto do contrato e a data de entrada no posto:
select
       max(entrada_posto),
       e.id ,

       --ep.fk_posto_contrato,
       e.admissao,
       e.demissao,
       --ep.entrada_posto,
       ep.saida_posto

  from TB_EMPREGADO e

    inner join TB_EMPREGADO_NO_POSTO ep

     on e.id = ep.fk_empregado

group by

       e.id ,

       --ep.fk_posto_contrato,
       e.admissao,
       e.demissao,
       --ep.entrada_posto,
       ep.saida_posto

Cujo resultado é:
"MAX(ENTRADA_POSTO)","ID","ADMISSAO","DEMISSAO","SAIDA_POSTO"
"10/09/2018","1","10/09/2018","",""
"01/10/2020","43","09/13/2019","",""

O resultado completo com todas as colunas, dá 2 registros para o id 43, e eu só preciso do último:
"MAX(ENTRADA_POSTO)","ID","FK_POSTO_CONTRATO","ADMISSAO","DEMISSAO","ENTRADA_POSTO","SAIDA_POSTO"
"01/10/2020","43","42","09/13/2019","","01/10/2020",""
"10/09/2018","1","21","10/09/2018","","10/09/2018",""
"10/09/2019","43","41","09/13/2019","","10/09/2019",""

Há alguma forma de preservar essas colunas e só trazer a data de entrada no posto mais recente, para dado id de empregado?
Answer: Faça um with ou coloque essa informação numa sub-query entre as suas colunas:
Exemplo 1:
WITH ultima_entrada AS(
SELECT fk_empregado,
       MAX(entrada_posto) entrada_posto
  FROM tb_empregado_no_posto
 GROUP BY fk_empregado
)

SELECT MAX(entrada_posto),
       e.id,
       e.admissao,
       e.demissao
  FROM tb_empregado e
 INNER JOIN ultima_entrada ep
    ON e.id = ep.fk_empregado

Exemplo 2:
SELECT (SELECT MAX(entrada_posto) entrada_posto
          FROM tb_empregado_no_posto
         WHERE e.id = ep.fk_empregado) entrada_posto,
       e.id,
       e.admissao,
       e.demissao
  FROM tb_empregado e

Answer: Bruno Warmling,
Obrigado pelas dicas. Tentei as soluções, usando os dois exemplos e não fui muito feliz no primeiro utilizando todas colunas da tabela empregado_no_posto. Pode ser que esqueci algum detalhe.
No exemplo 1 usei assim:
WITH ultima_entrada AS(
SELECT fk_empregado,
       MAX(entrada_posto) entrada_posto
  FROM tb_empregado_no_posto
 GROUP BY fk_empregado

)

SELECT
       MAX(ep.entrada_posto),
       e.id,
       e.admissao,
       e.demissao,
       ep2.entrada_posto,
       ep2.saida_posto,
       ep2.atualizacao,
       ep2.fk_contexto
  FROM tb_empregado e
 INNER JOIN ultima_entrada ep
    ON e.id = ep.fk_empregado
 INNER JOIN tb_empregado_no_posto ep2 ON e.id = ep2.fk_empregado

group by
e.id,
e.admissao,
e.demissao,
ep2.entrada_posto,
ep2.saida_posto,
ep2.atualizacao,
ep2.fk_contexto

Ainda assim retornou os três registros.
No exemplo 2 retornou corretamente, porém ao acresentar as outras colunas, usando um inner da tabela empregado_no_posto retornou as três linhas:
SELECT (SELECT MAX(entrada_posto) entrada_posto
          FROM tb_empregado_no_posto ep
         WHERE e.id = ep.fk_empregado) entrada_posto ,
       e.id,
       e.admissao,
       e.demissao,
       ep2.saida_posto
  FROM tb_empregado e
       inner join tb_empregado_no_posto ep2 on ep2.fk_empregado = e.id

Testei outra abordagem, parecido com o exemplo 2 que funcionou. Eu adicionei mais uma comparação no inner join no exemplo 1, acrescentando outro inner. Funcionou, ficou extenso e não muito bonito, aí vai:

INNER JOIN tb_empregado_no_posto ep2 ON e.id = ep2.fk_empregado and
  ep2.entrada_posto = ep.entrada_posto

WITH ultima_entrada AS(
SELECT fk_empregado,
       MAX(entrada_posto) entrada_posto
  FROM tb_empregado_no_posto
 GROUP BY fk_empregado

)

SELECT
       MAX(ep.entrada_posto),
       e.id,
       e.admissao,
       e.demissao,
       ep2.entrada_posto,
       ep2.saida_posto,
       ep2.atualizacao,
       ep2.fk_contexto
  FROM tb_empregado e
 INNER JOIN ultima_entrada ep
    ON e.id = ep.fk_empregado
 INNER JOIN tb_empregado_no_posto ep2 ON e.id = ep2.fk_empregado and ep2.entrada_posto = ep.entrada_posto

group by
e.id,
e.admissao,
e.demissao,
ep2.entrada_posto,
ep2.saida_posto,
ep2.atualizacao,
ep2.fk_contexto

Aqui o resultado final:
"MAX(EP.ENTRADA_POSTO)","ID","ADMISSAO","DEMISSAO","ENTRADA_POSTO","SAIDA_POSTO","ATUALIZACAO","FK_CONTEXTO"
"10/09/2018","1","10/09/2018","","10/09/2018","","06-NOV-19 02.47.50.720476 PM","1"
"01/10/2020","43","09/13/2019","","01/10/2020","","10-JAN-20 04.35.40.642123 PM","1"

Aqui a solução que traz o mesmo resultado do exemplo 1 adaptado:
select ID,FK_POSTO_CONTRATO,FK_EMPREGADO, maior_data.entrada, SAIDA_POSTO,ATUALIZACAO,FK_CONTEXTO FROM tb_empregado_no_posto ep

inner join

(

select ep2.FK_EMPREGADO chave ,max(ep2.ENTRADA_POSTO) entrada FROM tb_empregado_no_posto ep2 group by fk_empregado

) maior_data

on maior_data.chave = ep.fk_empregado and maior_data.entrada = ep.entrada_posto

Comment: Se houver uma solução mais efetiva, por favor me digam.

Dúvida group by oracle


A linearly dependent matrix whose set of rows is linearly independent

Question: Consider the 2 by 2 square matrix whose entries are all the number $1$. Clearly, both the rows and column are linearly dependent. However, the set of rows(as well as the set of columns) is simply the singleton $\{(1,1)\}$, which is linearly independent. So, what is going on? Can someone clarify this issue for me?
Answer: When we talk about a set of vectors $v_1, \ldots, v_k$ being linearly independent, we do allow some of the vectors to be the same. (So the usage of the term "set" is a little different than in other contexts where it does not allow duplicates.)
So you ask whether the columns of a matrix are linearly independent or not, you should keep columns that appear more than once.
Comment: So, it is not a set then, but a multiset.


How to link a field to node title in view

Question: I created a content type. I have three fields: title, body, city.
I added two contents.
I can see nodes at:
http://www.example.com/?q=content/we-buy-houses-nj
http://www.example.com/?q=content/we-buy-houses-va
I created a view as following:
I added title field first (excluded from display).
I selected city field. For rewrite results, change the path to "content/[title]"
Result:
I can see the city field is hyperlinked. When I click each link, I get URL as following and page can not be found:
http://www.example.com/?q=content/We%20Buy%20Houses
http://www.example.com/?q=content/We%20Buy%20Houses
How do I remove the %20 so page can be found in my case?
Comment: **Just a side note:** You should enable clean urls by going to `/admin/config/search/clean-urls`. This will get rid off the `?q=` part which is bad for SEO.
Comment: Thank you. It was a helpful tips. I just cleaned the urls. Now, I do not see ?q=.
Answer: You get %20 because the browser replaces/fixes/auto-corrects the empty space between your title with %20 as empty spaces are not allowed in URLs.
EX: If you try to go to drupal.org/Hello World, browser url changes/corrects it to drupal.org/Hello%20World.

Here is another possible option:
Add Path as a field, and checkmark exclude from display.
Make sure Content: Path is above Content: Cities, if not please re-arrange it.
Then in cities, for link path put [path]


How to remove multiple hashtags from the start of a paragraph using regex?

Question: I want to remove multiple hashtags from the beginning of a paragraph.
#abc #def This is a test paragraph. #ads I only want to remove the first hashtags and keep the rest.
How should I remove the hashtags at the beginning of the paragraph?
I'm using a no-code platform to work. So there are limitations for me to write code. But I'm using the replaceRegex function for doing this. The platform works on javascript.
What I have
var.a = "#abc #def This is a test paragraph. #ads I only want to remove the hashtags at the beginning and keep the hashtag at the center.

Function
{{replaceRegex var.a '/(?<! \w\s+)(#[a-zA-Z]+ *)/g' " "}}

Actual Result
   This is a test paragraph.  I only want to remove the hashtags at the beginning and keep the hashtag at the center.

Expected Result
 This is a test paragraph. #ads I only want to remove the hashtags at the beginning and keep the hashtag at the center.

Comment: Did the answers below work for you?
Answer: You could use
^#[a-zA-Z]+(?: +#[a-zA-Z]+)* *

^ Start of string
#[a-zA-Z]+ Match # and 1+ chars a-zA-Z
(?: +#[a-zA-Z]+)* Optionally repeat 1+ spaces, # and 1+ chars A-Z
 * match optional spaces

If you want to match whitespaces you can use \s but note that it can also match a newline.
regex demo
You can replace the match with an empty string.
For example using Javascript:

const regex = /^#[a-zA-Z]+(?: +#[a-zA-Z]+)* */gm;
const str = `#abc #def This is a test paragraph. #ads I only want to remove the hashtags at the beginning and keep the hashtag at the center.`;
console.log(str.replace(regex, ''));
Answer: You can use
^(?:\s*#[a-zA-Z]+)+\s*

See this regex demo.
NOTE: If there can be any Unicode letters and you are using an ECMAScript 2018+ compliant JavaScript environment, you might use
/^(?:\s*#\p{L}+)+\s*/u

where \p{L} matches any Unicode letter.
Details:

^ - start of string
(?:\s*#[a-zA-Z]+)+ - one or more repetitions of

\s* - zero or more whitespaces
#[a-zA-Z]+ - # and one or more ASCII letters

\s* - zero or more whitespaces


How can I tell if .net framework winforms code is callable from .net core6?

Question: I tried a simple proof of concept creating a solution with one of each project and displaying a Framework 4.7.2 MessageBox.Show("Hello world"). This worked fine, as did displaying a winform.
However I have run into problems referencing dlls.
If I reference a .net framework dll in my .net core6 project I see a small yellow triangle against the package reference and a message

Package 'MyDLL 2.0.0-CI-20220210-212727' was restored
using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2,
.NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1,
.NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8' instead of
the project target framework 'net6.0-windows7.0'. This package may not
be fully compatible with your project.

I guess I could just put my framework winforms code in a .exe and call it via a command line shell.  But I was hoping for a better way, whilst still not doing the full .net core port.
I need the mid step because I have common code that is used by vb6 via com interop.
Is there any better strategy than just try and see?
I have asked this related question.
Comment: When you're .NET Core you're .NET Core all the way. No, you can't just use a Framework assembly in Core without porting it (except in really trivial cases where the assembly uses, say, nothing more than .NET 2 metadata and no platform-specific code, but that's vanishingly unlikely -- most such code would target some version of .NET Standard). COM interop is a scenario that should actually be possible in .NET 6, although I'm not familiar with the details, but to make that work in one process you'll need to recompile the assembly regardless.
Comment: I guess not seeing the yellow triangle is the answer.
Comment: I asked a related question ~https://stackoverflow.com/questions/71086536/can-i-write-a-winforms-ui-that-is-callable-from-both-net6-and-vb6
Answer: The hint is the yellow triangle showing in the nuget packages in VS2022.
As Jeroen says, I should not use the framework library without porting it to core.


Freebase Query with "JOINS"

Question: ... Yeah, yeah, I know traditional joins don't exist.  I actually like the freebase query methodology in theory, just having a little trouble getting it to actually work for me : )
Anyone have a dumb-simple example of getting Freebase data via MQL that pulls from two different "tables"?  In particular, I'm trying to get automotive data... so for example, pulling fields from both /automotive/model_year and /automotive/trim_level.
I've read the documentation (for hours actually).  There's a distinct possibility that I'm looking right at such an example somewhere and just not seeing it because my OLTP brain just doesn't comprehend what it's seeing.
* Note * ... that the two "types" I'm working with above are siblings, not parent/child.  Does freebase even allow joining data between sibling nodes... I see examples of queries pulling from parent/child, but not from siblings I don't think (or I've overlooked them).
Comment: What do you want to do with the data? I think I do not get the use case, yet. BTW: There is no /automotive/trim_year.
Comment: my bad... trim_level... right in query, wrong in question post.  not sure that the use case is relevant... but am working my way towards a year/make/model/etc set of drop-downs to specify a vehicle.
Answer: Basically, could you not just restrict the queries according to the user's input?
When the user selects the year, you get all makes that have a matching model year:
<code>[{
  "model_s": [{
    "model_years": [{
      "year": [{
        "type":    "/type/datetime",
        "value<":  "2010", // User input
        "value>=": "2009" // User input
      }],
      "type": "/automotive/model_year"
    }],
    "type": "/automotive/model"
  }],
  "id":   null,
  "name": null,
  "type": "/automotive/make"
}]
</code>
If the make is selected and you need the models for that make and year:
<code>[{
  "model_years": [{
    "year": [{
      "type":    "/type/datetime",
      "value<":  "2010", // User input from above
      "value>=": "2009" // User input from above
    }],
    "type": "/automotive/model_year"
  }],
  "id":   null,
  "name": null,
  "type": "/automotive/model",
  "make": [{
    "id":   "/en/volkswagen", // User input
    "type": "/automotive/make"
  }]
}]
</code>
Or did I just not understand your problem correctly?
Comment: +1 very helpful... will look more closely tomorrow evening and likely award as selected answer.  thank you!
Comment: yep, i think that's it.  in fact, i think it may be better than the way i was planning on trying to do it.  thanks again.
Comment: lol... +1 more to your thank-you comment (and +20 to various other of your deserving questions/answers on StackOverflow)... I'm just now getting back to this and appreciating how much your answer has really helped.

Freebase Query with "JOINS"


Does it matter if I use correlations or regression coefficients to suggest areas to focus on to improve overall customer satisfaction?

Question: I am working with customer satisfaction data where the dependent variable is "Overall satisfaction" and the independent variables are satisfaction with various areas such as customer support, delivery etc.
I want to suggest areas where the company should focus on in order to improve overall satisfaction.
Option 1: I could look at correlations between the 'Overall satisfaction" and the independent variables and suggest that the company focus on the top 3 positive correlations as areas for improvement.
Option 2: I can use a linear regression and suggest that the company should focus on the areas associated with the 3 highest regression coefficients.
Are the two options equivalent? If not, which one is the better approach?
Comment: Just because one variable correlates more highly with overall satisfaction does *not* mean that changing it will have the greatest effect on overall satisfaction. I agree with @NickCox. If the problem you have stated is not your real problem, then please withdraw your post and re-post your real problem. If it *is* your real problem, listen to Nick.
Comment: I don't think this management speak, which no doubt is (a) correct enough (b) what you have to work with, bears on my point at all. I said descriptive statistics: I wasn't implying that you just look at means, but at the fine structure of who is most dissatisfied. There are other pitfalls too, e.g. high correlations go with high range of responses in practice. More crucially, you are asking which is better of two methods? My reply is that neither method sounds focused on the real problems.
Comment: Even within your limits: Candour compels me to say that your question seems a false choice to me. If you run the regressions, the correlations are there for free; indeed you need scatter plots too. Why commit yourself in advance to a particular criterion? Your context is what defines your problem. Why throw it away?
Comment: It means that there is a relationship in the data, but that doesn't mean that changing one thing will change the other. Basically, neither correlation nor regression solves your problem.
Comment: This seems indirect to me. You (should) want to know what the most dissatisfied customers are dissatisfied about. That's not really a regression or correlation issue. For example, I can be very happy with quality of website, friendliness of staff, promptness of delivery but as mad as anything because the product just _doesn't work_.  Multiply me, say, because that's a widespread problem, but regressions and correlations are not optimal to find us. That's descriptive statistics and basic exploration first: these mad people, what are they mad about?
Comment: True but you also want to prioritize on areas where you think it will have the highest impact. I could be very dissatisfied in two areas but only one of which is critical to making me extremely unhappy overall. It is important then to not just look at the means but to also look at which areas drive overall satisfaction so that the company can decide where to devote limited resources if improving overall satisfaction is a goal they want to accomplish.
Comment: I understand the point you are making but let us pretend for a moment that I need to know the answer as to whether options 1 or 2 are equivalent or not for the purpose of assessing the relative contribution of the independent variables to the dependent variable. If it helps let us abstract away from the context of satisfaction and look at the issue independent of any context. I would be happy to hear about the relative pros and cons of both these options even if they are the wrong tools/approaches.
Comment: Right. Let us stop the discussion here as it is getting far from where I want the focus to be.
Comment: Fair enough; I think you understand my point but you should see whether others can produce answers more interesting to you.
Comment: @PeterFlom Why not? Doesn't a high, positive correlation mean that if one variable is high the other is also likely to be high? If the argument is that correlation is simply association and not causal then the same can be said for regression as well.
Answer: If I understand correctly, customers rate the company in various aspects of the transaction, and then, customers again give an overall score. This is the real-world structure. Making an assumption that customers are reasonably rational (i.e. consistent in their opinions), it means that somehow, they, in their minds, construct some sort of "weighted average" in order to go from the partial scores to the overall score.
Then you should use the regression approach, which reflects the above situation. Using partial correlation coefficients does not capture how one reasonably believes that the customers thought and acted when scoring the company.
This regression is in the spirit of "hedonic index regression", if we view "overall satisfaction" as the "price" of the "product" named "transacting with company", and the regressors as "features" of the product (that are provided in different levels for each customer, and hence their variability).
If the rankings are consistently coded (say, a higher number means a higher level of satisfaction for the partial scores and for the overall score), then a higher estimated regression coefficient on a partial score will indicate that this aspect of the transaction "bears more heavily" (has a higher marginal effect) on "overall satisfaction", and so indeed, focusing and improving on the areas with the higher regression coefficients, should yield larger benefits in overall satisfaction.
But also, in order to finally decide on the prioritization, one should also look how the various areas compare in average score. Say "customer support" has a higher regression coefficient than "delivery", but also, "customer support" is on average rated already very high by customers, compared to "delivery". Then the efforts to further improve "customer support" may be more costly and difficult, compared to improving "delivery". So while one unit of increase in customer support satisfaction may yield higher overall satisfaction increase compared to one unit increase in "delivery", this one unit increase may be more costly to achieve in customer satisfaction than in delivery, offsetting partially, or fully, the economic gains from the increase in "overall satisfaction".
Of course this last issue is not a statistical question, but I mentioned it so that any prioritization suggestion based on statistical analysis, at least mentions this aspect that must be taken into account for the final decisions.
Comment: Pearson's coefficient totally ignores the fact that the dependent variable "Y" varies not just because of one explanatory variable, but because of all. Then it will give you the degree of _covariance_, but not the degree of _effect_ of the explanatory variable on "Y", which is what you are after.
Comment: I agree on the thought process part. However, why would just looking at the correlations between "Overall Satisfaction" with the components be not enough? By the way, I do not mean partial correlation but the Pearson's product-moment correlation coefficient.


Regarding a number theory proof

Question: Before I begin I should mention that I have only recently started studying number theory.
It is required to prove that there are no positive integers  $a,b,n>1$ such that
$$a^n - b^n\mid a^n+b^n$$
that is $k$ can never be an integer if
$$\frac{a^n+b^n}{a^n-b^n} = k$$
Now if $b|a$ then we can write
$$\frac{(a/b)^n+1}{(a/b)^n-1} = k$$
which is clearly not true for all $a/b$. However I have no idea how to prove the general result. Help will be appreciated.
Comment: Are $a,b$ real numbers or natural numbers?
Comment: What if $n=2$ and $a=\sqrt3$ and $b=\sqrt 2$
Comment: @HEIFETZ I think the statement is not true if $a,b$ are real numbers. For example, as given above, $(\sqrt (m+1))^2 - (\sqrt m)^2 = 1$, which is a divisor of $(\sqrt (m+1))^2 + (\sqrt (m))^2 = 2m+1$ for all values of $m$.
Comment: I have corrected the mistake. a b and n are all positive integers greater than 1.
Comment: Ok. In that case, there is an answer.
Comment: No, you haven't corrected the mistake. On line two it still talks about *real* numbers.
Answer: Set $\gcd(a,b)=d$, $a=da_1$ and $b=db_1$, then $\gcd(a_1,b_1)=1$. We proceed by proof by contradiction. If $a^n-b^n\mid a^n+b^n$, then $a_1^n-b_1^n\mid a_1^n+b_1^n$, so $a_1^n-b_1^n\mid2a_1^n$ and $a_1^n-b_1^n\mid2b_1^n$, leading to $a_1^n-b_1^n\mid\gcd(2a_1^n,2b_1^n)=2$. Hence $a_1^n-b_1^n\mid2$.
Without loss of generality we assume $a>b$, and so $a_1>b_1$. Since $a_1^n-b_1^n\mid2$ we have $a_1^n-b_1^n=1$ or $2$, but $$a_1^n-b_1^n=(a_1-b_1)(a_1^{n-1}b_1+a_1^{n-2}b_1^2+\cdots+a_1b_1^{n-1})>n\geq2,$$ which is a contradiction!
Answer: Notice if $a^n - b^n|a^n + b^n$ then $a^n - b^n|a^n + b^n + a^n - b^n = 2a^n$ and $a^n - b^n| a^n + b^n -(a^n- b^n) = 2b^n$.
So if $p|a^n - b^n$ and $p$ is prime either $p = 2$ or $p|a$ and $p|b$.
Let $d = \gcd (a,b)$ and let $a = a'd; b = b'd$ then $\frac{a^n - b^n}{a^n + b^n}= \frac {a'^n - b'^n}{a'^n + b'^n}$ and $a^n - b^n| a^n + b^n \iff a'^n - b'^n|a'^n + b'^n$.
So $a'^n - b'^n|2a'^n$ and $a'^n- b'^n|2b'^n$ and for any prime $p \ne 2$ if $p|a'^n - b'^n$ then $p|a'$ and $p|b'$ so $p|\gcd(a'b') =1$ which is impossible.  So no prime other than $2$ divides $a'^n - b'^n$.
So $a'^n - b'^n = 2^m$.  But only $2$ can't divide both $a'$ and $b'$ so $a'^n - b'^n = 2$ or $a'^n - b'^n = 1$.
So $(a'^n - b'^n) = (a'-b')(a'^{n-1}+ a'^{n-2}b'+ ... + a'b'^{n-2} + b'^{n-1})$.
Clearly $a'-b' < (a'^{n-1}+ a'^{n-2}b'+ ... + a'b'^{n-2} + b'^{n-1})$ and $(a'^{n-1}+ a'^{n-2}b'+ ... + a'b'^{n-2} + b'^{n-1}) > 0$ so
$a -b = 1$ and $(a'^{n-1}+ a'^{n-2}b'+ ... + a'b'^{n-2} + b'^{n-1})= 2$
$(a'^{n-1}+ a'^{n-2}b'+ ... + a'b'^{n-2} + b'^{n-1}) = 2$ is only possible if $n= 1$.  And indeed if $a-b =1$ then $1|a+b$ but... $n$ must be bigger than $1$ and that is impossible.

Regarding a number theory proof


Modern Core Data Performance with UUID

Question: I have a Core Data application with:

549 Account entities with myJournals relationship (one to many)
24000 Ledger entities with myJournals relationship (one to many)
57000 Journal entities with myAccount and myLedger (one to one) inverse
relationship

Each entity has a uuidKey string attribute with a UUID string imported from an online database.
I'm trying to run the app on an iPhone 5S. Inserting objects is relatively fast, but finding and linking the relationships is longer than anticipated.
let debugTime = NSDate()
let thisRequest = NSFetchRequest(entityName: "Ledgers")
let keyLeft = NSExpression(forKeyPath: "uuidKey")
let keyRight = NSExpression(forConstantValue: ledgerKey)
let keyPredicate = NSComparisonPredicate(leftExpression: keyLeft, rightExpression: keyRight, modifier: NSComparisonPredicateModifier.DirectPredicateModifier, type: NSPredicateOperatorType.EqualToPredicateOperatorType, options: NSComparisonPredicateOptions.allZeros)
thisRequest.predicate = keyPredicate
thisRequest.fetchBatchSize = 1
thisRequest.fetchLimit = 1
println("DEBUG COMMENT: \(debugTime.timeIntervalSinceNow) time to create thisRequest.")
var keyError: NSError? = nil
if let keyArray = self.managedObjectContext!.executeFetchRequest(thisRequest, error: &keyError) {
    if keyArray.isEmpty {
        myLedger = nil
    } else {
        if let thisLedger = keyArray[0] as? Ledgers {
            println("DEBUG COMMENT: \(debugTime.timeIntervalSinceNow) time to find thisLedger.")
            myLedger = thisLedger
        } else {
            myLedger = nil
        }
    }
}
println("DEBUG COMMENT: \(debugTime.timeIntervalSinceNow) time to link myLedger.")

I get log times like this:
DEBUG COMMENT: -9.20295715332031e-05 time to create thisRequest.
DEBUG COMMENT: -0.174275994300842 time to find thisLedger.
DEBUG COMMENT: -0.174659013748169 time to link myLedger.
DEBUG COMMENT: -0.00464397668838501 time to find and link myAccount.

0.092 milliseconds to create the NSFetchRequest is fine.
174 milliseconds to find the Ledger? On an indexed UUID string when there are 24k Ledgers?!? When I need to link this to 57k Journals?
Faster is always better. 4 milliseconds to find a link myAccount when there are 549 accounts is slightly disappointing but acceptable. For the Ledger search I was expecting about 25-50 milliseconds, not 174!
I'm running this in its own core data store and context:
    // Initialize the persistent store coordinator for the sync session.
    let url = appDel.applicationDocumentsDirectory.URLByAppendingPathComponent("FoodyCoreModel.sqlite")
    self.syncStore = NSPersistentStoreCoordinator(managedObjectModel: appDel.managedObjectModel)
    var error: NSError? = nil
    var failureReason = "There was an error creating or loading the application's saved data."
    let storeOptions: [NSObject: AnyObject] = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
    self.syncStore.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: storeOptions, error: &error)

    // Initialize the managed object contextfor the sync session
    self.syncContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType)
    self.syncContext.persistentStoreCoordinator = self.syncStore
    let nmp = NSMergePolicy(mergeType: NSMergePolicyType.MergeByPropertyStoreTrumpMergePolicyType)
    self.syncContext.mergePolicy = nmp

Is this reasonable performance to expect with an iPhone 5S? I've read many of the Core Data performance questions here, but many of them date from years ago. I was hoping that iOS 8 and more recent devices would be significantly faster. I'm not trying to do a MATCHES or CONTAINS search, just EQUALS on an indexed text field!
I've read the  Core Data Performance Guide. Is there something I'm missing or am I just expecting too much from a mobile device?
Comment: P.S. Search performance seems to get significantly worse with any Entity type that has more than 15000 rows. Anyone else notice this?
Comment: Have you read this... from The Pragmatic Bookshelf – "Core Data, 2nd Edition, Data Storage and Management for iOS, OS X, and iCloud" (Jan 2013) by Marcus S. Zarra, and in particular Chapter 4 titled "Performance Tuning". Also, and forgive me this is just a guess, but have you tried switching the left and right joins?
Comment: Most of the Ledgers have two Journals. Querying from each Ledger (Ledger.uuidKey == Journal.uuidLedger) doesn't seem any faster than the other way around.
Answer: The most likely slowdown in your code is that you're fetching Ledger instances one at a time, and you say there are 24,000 of them. That's going to be a major bottleneck no matter what. Fetching is a relatively expensive operation, regardless of whether you're using a string ID in the predicate, so your code is going to be spending most of its time fetching.
You should be fetching in batches instead of one at a time. Collect 50 or 100 or so uuidKey values into an array and use a predicate format like "uuidKey in %@" with the array as the substitution variable. Process that batch, and repeat until done.
For more detail on how to import data efficiently, refer to Apple's "Efficiently Importing Data" guide, especially the section called "Implementing Find-or-Create Efficiently".
As an aside, using println like this is a really poor way to measure performance. Use Instruments. It'll give you more detail with less overhead and without cluttering up your code, and will help you nail down exactly where bottlenecks are.
Comment: The Ledgers were already imported. Then I start downloading Journals, 1000 at a time. I did use a uuidKey in to compare Journals with what is already in the database. A dict of uuidKey: JSON for all 1000. A set of all 1000 journalKeys. A set of matching journal keys. Loop through and compare dateModified to see what is unchanged vs updated. Subtract unchanged and updated from all keys to get the Journals to insert. As I've said in my original question, I've read Efficiently Importing Data. Part of my mistake seems to be setting the relations one at a time. I'll have to see how much memory...
Comment: You're still fetching Ledgers one at a time, which is still likely to be the main performance problem.
Comment: ... I'll have to see how much memory a dict [uuidKeyString: NSManagedObjectID] of all of the Ledgers takes.

Modern Core Data Performance with UUID


Cricket ball bounced over keeper and landed outside the boundary line!

Question: Consider this situation :
A short boundary behind the wicket and the pitch is having an extra(or abnormal) bounce. A fast bowler bowls a bouncer which flies over the keeper and lands outside the boundary.
Will this be given as 6 runs ?
Was there any incident like this in the history of cricket?
Comment: It's hard to find dupes here :/ I searched for dupes but found none.May be because other question is about intentionally bowling a six and mine is about accidentally , Anyway it is a duplicate.
Answer: This is a highly unusual case but I have seen it happen in local recreational cricket from a bouncer.
The correct decision for this is to award 4 byes.  Boundary 6 can only be scored from the bat.
from Law 19 5c ,

A Boundary 6 will be scored if and only if the ball has been struck by
  the bat and pitches beyond the boundary.
Comment: This is not gaurenteed it is possible for it to happen without being either wide or no ball.
Comment: While 4runs may be correct , it will also be taken as wide or as no-ball , so there will be an additional run , hence total will be 5runs.
Comment: @BenWhyll Yesterday, in ENG vs BAN Jofra Archer bowled out Tamim Iqbal and the ball went directly over the keeper's head to six and ICC in their twitter handle posted "Have you ever seen a ball go for 'six' after hitting the stumps?" Did they just say it for the sake of posting it and gain views or they really mean it?
Comment: @jay they are just trying to get views as you suggest.  Also I would be surprised if the ICC Twitter account is run by someone who knows the laws.  This is rare so people won't have seen it.
Answer: This is a highly exceptional case. There is no record of this having occurred in any professional cricket match. If a ground has such a short boundary behind the wicket, it cannot be used for professional cricket. If a pitch causes such abnormal bounce, it will be deemed dangerous and the match will be called off.
As Ben Whyall mentions, the ball needs to strike the bat for it to be given a 6.
Comment: @BenWhyall Ah! I should do some better research. Edited that part out!
Comment: Hi, as per my answer and the link a boundary 6 may only be scored from the bat.


using a function from a string of text PHP

Question: I would like to know if it is possible to store the following
ee()->session->userdata('group_id') as a string in a variable.
Then to use it but as the function written inside.
Ultimately something that would look like
//request posted from somewhere
$request = "ee()->session->userdata('group_id')";
$myValue = $request // But here the function inside would be in place leaving the value of `$myValue` the id from the function and not the string.

I have another system that requires to utilise the foreign class ee() and i am hoping to create a bridge by posting a string and returning the return value and not the function string.
Comment: It is, but it's generally considered very bad practise, and can be highly dangerous if the string comes from user input, and if there's any errors in the string of code, then it's hard to debug
Comment: It cannot be overstated how bad of an idea this is.
Comment: [eval();](http://php.net/manual/en/function.eval.php) `Caution: The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.`
Answer: The function you are looking for is called eval. But be very careful with this function, as it is considered to be very harmful! Sanitize your strings!
Here is a quote from the PHP manual (linked above):

Caution
  The eval() language construct is very dangerous because it allows
  execution of arbitrary PHP code. Its use thus is discouraged. If you
  have carefully verified that there is no other option than to use this
  construct, pay special attention not to pass any user provided data
  into it without properly validating it beforehand.
Comment: I need only a few values so i will do it another way. the security issue wouldn't be too much hassle but the risk nonetheless isnt worth it for me. The idea came to mind of opening up a port for ease of use and although possible i think its not quite the great idea i had hoped for. I am glad to have learned about eval today though! many thanks
Comment: i had a suspicion it would be shady business. I cannot think of a better solution as yet but i guess i will have to. Many thanks.
Comment: No problem. If you want, you can post another question asking how it could be done better and give an example what exaclty you need it for. Just as a suggestion.


DBMS.OUTPUT.PUT_LINE prints null value in first iteration of loop

Question: I am trying to output increment values for each row in a dataset. For some reason every row except the first row prints a numeric value.
DECLARE CURSOR active_invoices_curs IS
 SELECT vendor_id, invoice_date, sum(invoice_total) as sum_invoice
 FROM active_invoices
 GROUP BY vendor_id, invoice_date
 ORDER BY vendor_id ASC;
 last_vendor_id active_invoices.vendor_id%TYPE;
 last_invoice_total_sum active_invoices.invoice_total%TYPE;
 invoice_row active_invoices_curs%ROWTYPE;
 invoice_increment number;
BEGIN
 FOR invoice_row in active_invoices_curs LOOP
  IF invoice_row.vendor_id != last_vendor_id OR invoice_row.vendor_id IS NULL THEN
   invoice_increment := invoice_row.sum_invoice;
  ELSE
   invoice_increment := invoice_row.sum_invoice - last_invoice_total_sum;
  END IF;
  last_vendor_id :=invoice_row.vendor_id;
  last_invoice_total_sum := invoice_row.sum_invoice;
  DBMS_OUTPUT.PUT_LINE('vendor '||invoice_row.vendor_id||'''s increment on '||invoice_row.invoice_date||' is: '||invoice_increment);
 End Loop;
End;

Expected Output:
vendor 37's increment on 17-MAY-14 is: 116
vendor 37's increment on 19-MAY-14 is: 108
...
Actual Output:
vendor 37's increment on 17-MAY-14 is:
vendor 37's increment on 19-MAY-14 is: 108
...
Answer: Because, last_invoice_total_sum has no initial value, and it seems your first iteration falls in ELSE case, and So invoice_row.sum_invoice - last_invoice_total_sum;(which is assigned to invoice_increment variable)  gives null result.
To initialize that variable those following methods might be used :

last_invoice_total_sum active_invoices.invoice_total%TYPE := 0; may
be assigned in the declaration part

or

last_invoice_total_sum := 0; before for loop

or

(last_invoice_total_sum,0) be applied within ELSE part of IF statement as invoice_increment := invoice_row.sum_invoice - nvl(last_invoice_total_sum,0);
Comment: How is the result null? Its basically saying 116 - NULL  right? Shouldn't that result in an error message?
Comment: @NickJung No, doesn't give error. Arithmetical operations with a null value gives null result. As an example, `116 * null` would give null also.


Javascript Raphael to create and remove multiple text points

Question: I have some code that prints text at specific points
group = paper.set();

for (var i = 0; i < numClicks; i++){
    group.push(paper.text(clicksX[i], clicksY[i], "TEST"));
}

That works great and the "TEST" shows up perfectly. However, I now want to remove all the "TEST" strings from my paper (to start again). How do I do this?
I've tried:
group.clear()

group.remove()

group.forEach(function(txt){txt.remove();})

and
group.forEach(function(txt){group.exclude(txt)})

but nothing seems to work. Any ideas what I'm missing?
Thanks,
Ed
Comment: This line group.forEach(function(txt){txt.remove();}) works for me. Could you put your example on a jsfiddle so we can see whats happening.
Comment: Thanks Ian, you're right - I just had it in the wrong place in my code. Thanks so much for the sanity check!!
Answer: group.forEach(function(txt){txt.remove();}) does work if it's in the right place in the script.
Thanks to Ian!


get to previous page with destination d6

Question: For example i have a button which has onclick event (redirecting to a user login page). When a user clicks on that button browser redirects him to page user/login, but when he's successfully logined in - how to redirect it back to the previous page? Tried module login_destination, but didn't worked for me..
Answer: In your onclick event, add a destination=previous_path along with your redirection url.
ie: yoursitename.com/user?destination=previous_path
Comment: Yeah thanks, but does it completely reload the previous page when i come back to it?
Answer: Server side example, using drupal_get_destination:
// Login link that redirects back to current path
$login = l(t('Login'), 'user/login', array('query' => drupal_get_destination()) ;
// debug
drupal_set_message($login);

and as an onclick attribute, example using an image:
$url = url('user/login', array('query' => drupal_get_destination());
$image_path = path_to_theme().'/images/login.png'; // or drupal_get_path
$login = theme('image', $img_path, t('Login'), t('Login'), array('onclick' => 'javascript:location.href='.$url)); // or jquery.onclick it
// debug
drupal_set_message($login);

Note, this is OTTOMH
Personally, I'd do it server side for reliability.


how to erase an image drawn by canvas?

Question: <code>  @Override
  protected void onDraw(Canvas canvas) {
   // TODO Auto-generated method stub
      Log.d("dd","draw");

            mBitmap=BitmapFactory.decodeResource(this.getResources(),R.drawable.image1);

            canvas.drawBitmap(mBitmap, srcRect,dstRect,null);
            mBitmaps=BitmapFactory.decodeResource(this.getResources(),R.drawable.paintball);
              canvas.drawBitmap(mBitmaps, 180,200,null);
        }
</code>
Answer: <code>Canvas.drawColor(Color.BLACK)
</code>
or to your bg color.

how to erase an image drawn by canvas?


Quando usar o termo "url" ou "link"?

Question: Esses dias comecei um "pequeno debate" aqui no TI a respeito desse assunto. Percebi que várias funções, onde retornávamos o caminho da imagem (para o navegador), estava com o nome de getImageLink.
Por exemplo:
public function getImageLink() {

      return $this->base_url . '/imagens/' . $this->id . '.jpg';
}

O retorno disso seria:
'http://meusite/imagens/1.jpg'

Daí eu comecei a pensar que talvez "link" se referisse à uma "url" utilizada com a tag . Não sei se minha afirmação está correta, mas no final decidi mudar o nome dos métodos, que passaram a se chamar getImageUrl.
Eu peguei o costume ao ouvir as pessoas falando "link" e "url" quando se trata do endereço de um site que digitamos na barra de navegação do navegador, por exemplo.
Perguntas

Do ponto de vista da programação, eu deveria chamar esse "caminho da imagem" (para o navegador), de "url" ou "link"?

O que é "link" e o que é "url"? Qual é a diferença entre um e outro?

Para ser "link", tem que ser algo clicável?
Comment: Especificamente sobre URL: http://pt.stackoverflow.com/q/43224/101
Answer: O "caminho" de uma imagem, ou qualquer recurso, é sempre uma URL.
A sigla URL significa "Localizador Uniforme de Recursos" e descreve o padrão de nomeação do endereço de qualquer coisa que possa ser acessada numa rede.
O termo "Hiperlink" é derivado do conceito de Hipertexto e fortemente associado à Web.
Por conta da onipresença da Web, os 2 termos se tornaram quase intercambiáveis já que todo link vai apontar para uma URL, e quase toda URL que você acessa vem de um link. Informalmente não vai haver distinção ou problema em se usar os 2 termos à vontade.
No caso de uma função como a do seu exemplo, o que está sendo retornado é uma URL, não um hiperlink. Esse vai ser o caso para a maioria das funções desse tipo, a não ser que elas existam para montar um hiperlink dentro de uma página de hipertexto.
Acho difícil que qualquer pessoa lendo seu código vá se confundir se você usar getImageLink ao invés de getImageURL, mas o correto nesse caso seria getImageURL.

Quando usar o termo "url" ou "link"?


My dataframe contains a time column with 'W' and 'S' differentiating 'Summer' and 'Winter'. how to convert this without losing any data?

Question: Here is my data looks like:

when I convert this column into DateTime without specifying format using, I get random picks with NaT.

if I specify the format as format="%Y-%m-%d %HW%M:%S,%f" I get only Winter dates, and with the format as format="%Y-%m-%d %HS%M:%S,%f" I get only summer dates converted.
Is there is any way to I can get all the data gets converted to DateTime format without any NaT's?
Comment: use a "or"  condition and specify both formats as you have mentioned in this format="%Y-%m-%d %HW%M:%S,%f". Also, put your sample data in a format so that anyone can copy it and work on it.
Comment: `df['updtime'] = pd.to_datetime(pd.to_datetime(df['updtime']).strftime('%Y-%m-%d %H-%M-%S'))`
Answer: One solution it to replace the character W ans S with empty and do the formatting.
<code>df['updtime'] = pd.to_datetime(df['updtime'].replace(to_replace ='[W|S]', value = '', regex = True), format='%Y-%m-%d %H%M:%S,%f')

</code>


No matching client found for package name 'com.example.pc.fireApp'

Question: I have this mistake when I sync my graddle. I think the problem comes from the google service.json file.
"No matching client found for package name 'com.example.pc.fireApp'".
My graddle :

 apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.example.pc.fireApp"
        minSdkVersion 19
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.google.firebase:firebase-core:16.0.1'
}
 apply plugin: 'com.google.gms.google-services'

Thanks
Answer: Thats because you recently changed your package name in your app and your google-services.json file is not with that package
you have 2 options, first one is changing it manually
put your package "com.example.pc.fireApp" in all the places it requests package_name
Project - google-services.json file

option 2 is deleting it and connect again with firebase ( Recommended since the first option will change the package at client side , it will work but you will see a different package in your firebase console and can lead to problems in the future )
go to Tools in your IDE, Firebase and connect with any service , remember to delete google-services.json before


Cutomize Delete button react-admin

Question: Is there any way to customise DeleteButton button in react-admin to add a confirmation message like 'Do you want to delete item?'. Currently on clicking on DeleteButton it directly deletes the item without asking for a confirmation. I tried adding title attribute to delete button but it does not get fired.
Here is my code
//This worked with admin-on-rest, but not working with react-admin
const CategoryDeleteTitle = translate(({ record, translate }) =>
        {translate('Delete')}
        {record && `${record.code} ${record.name}`}
    );

const EditActions = ({ basePath, data, resource }) => (
    <CardActions>
        <ShowButton basePath={basePath} record={data} />
        <ListButton basePath={basePath} />
        <DeleteButton title={<CategoryTitle />} basePath={basePath} record={data} resource={resource} />

    </CardActions>
);

export const CategoryEdit = (props) => (
    <Edit actions={<EditActions />} title={<CategoryTitle />} {...props}>
        <SimpleForm>
            <DisabledInput source="id" />
            <TextInput source="name" />
        </SimpleForm>
    </Edit>
);

Comment: How do I add a alert?
Comment: give me some time. i'll post the answer
Comment: Thank you so much. I have edited the question to show what I have tried.
Answer: We now handle deletions in an optimistic way, providing an undo mechanism instead of a confirmation dialog.
If this doesn't suit you, you can follow the UPGRADE GUIDE which leads to this page of the documentation: https://marmelab.com/react-admin/CreateEdit.html#actions
Note that you'll have to create and handle your confirmation dialog using something like react-modals and dispatch the DELETE action yourself.
Comment: Thanks Gildas I have customised `DeleteButton` to show the confirmation dialog.
Answer: You can use this gist with custom actions like:
const UserEditActions = ({ basePath, data, resource }) => (
    <CardActions>
        <ListButton basePath={basePath} />
        <DeleteButtonWithConfirmation basePath={basePath} record={data} resource={resource} undoable={false} />
        <RefreshButton />
      </CardActions>
    );

export const UserEdit = ({ ...props }) => (
  <Edit {...props} actions={<UserEditActions />} >
    <CreateEditForm title={<EntityTitle label="User" />} />
  </Edit>
);

Comment: The gist does not mention licensing information. Can you add MIT information on it?
Comment: @Tzahi - Updated.
Answer: In react-admin v3, there is now a DeleteWithConfirmButton :-)
Comment: I cannot see any reference to this component in v3.7.0 : https://marmelab.com/react-admin/Reference.html Can you explain a bit more ?
Comment: Didn't find anything regarding this in the documentation
Comment: Yeah, but there is it https://github.com/marmelab/react-admin/blob/eb3c1acbf4ecc81793b8e790e11a6f84f9bdbc1b/packages/ra-ui-materialui/src/button/DeleteWithConfirmButton.tsx
Answer: According to the documentation "https://marmelab.com/react-admin/CreateEdit.html" create:
const CustomToolbar = props => (
    <Toolbar {...props} classes={useStyles()}>
        <SaveButton />
        <DeleteButton undoable={false} />
    </Toolbar>
);

import from react-admin button you need like this:
import {
    Toolbar,
    SaveButton,
    DeleteWithConfirmButton
} from 'react-admin';

see all available names here https://github.com/marmelab/react-admin/tree/master/packages/ra-ui-materialui/src/button, and change DeleteButton on ImportedButton like this:
 export const CustomToolbar = props => (
    <Toolbar {...props} classes={useStyles()}>
        <SaveButton/>
        <DeleteWithConfirmButton/>
    </Toolbar>
);

And change in the code, where you need <SimpleForm toolbar={<CustomToolbar />}>.

Cutomize Delete button react-admin


Probability that the sum of 50 dice throws is $\geq 195$

Question: The question is:
A cyclist is going for a bike journey of $1950$ kilometres. Every morning he tosses a die, and if the outcome is $k$, where $k = 1, 2,\dots,6$, he cycles $10k$ kilometres on that day. Find the probability that he will finish his route within $50$ days or less.
I took the question to mean what I've put in title (I don't know if that's correct), and when I attempted it I got about $0.889$ (edit I actually got $0.4562$, realised I made a mistake)
How do you answer this question?
Comment: Using normal approximation for the binomial distribution, normalize and use a phi table.
Answer: Your interpretation of the problem seems correct.
The mean of a single die throw is $\frac72$. The variance of a single die throw is $\frac{35}{12}$.
For $50$ die throws, these are multiplied by $50$: $175$ and $\frac{875}{6}$.
To approximate the Binomial Distribution $\ge195$ we compute the Normal Distribution $\frac{194.5-175}{\sqrt{\frac{875}{6}}}$ standard deviations above the mean.
The probability of being at least $1.61475$ standard deviations above the mean is approximately $5.318\%$.
Answer: You can work out this probability exactly with the following method.
The probability that the sum of $n$ dice is equal to $s$ is the coefficient on $x^s$ in the polynomial
$$
\left(\frac{1}{6}x+\frac{1}{6}x^2+\frac{1}{6}x^3+\frac{1}{6}x^4+\frac{1}{6}x^5+\frac{1}{6}x^6\right)^n.$$
The probability that the sum of 50 dice is at least 195 is then the sum
$$ \sum_{i=195}^{300} a_i$$
where $$ \left(\frac{1}{6}x+\frac{1}{6}x^2+\frac{1}{6}x^3+\frac{1}{6}x^4+\frac{1}{6}x^5+\frac{1}{6}x^6\right)^{50} = \sum_{i=50}^{300} a_i x^i.$$
With a computer algebra system, you can calculate that the probability is exactly
$$ \frac{14335043218171457162351380541553904985}{269427092488254686881046533485512097792} = 0.053205648644... $$
Comment: The approximation I compute in my answer gives about $5.318\%$. Pretty close.
Comment: @robjohn It sure is! Cheers!
Answer: Hint:  The expected value of one die is $3.5$, so for $50$ it is $175$.   The distribution is symmetric, so the chance must be less than $\frac 12$  What is the variance of one die?  What is the variance of $50$?  How many standard deviations do you need to be above the mean?
Comment: @IBOED2: it should be the mean of the squares minus the square of the mean, then multiply that by $n$.
Comment: I got the variance of 50 as $$(91/6 - 3.5)*50^2$$ is that right?
Answer: Let $X$ be the random variable that takes on the values of a six-sided die.
The question here about the probability the sum of $50$ throws exceeding $195$ is the same as asking the probability that the sample mean $\bar{X}$ exceeds $195/50=3.9$.
The Central Limit Theorem says that the distribution of $\bar{X}$ is basically normal. So, compute $P(\bar{X}\geq 3.9)$ for the (practically) normally distributed variable $\bar{X}$. (The parameters of the distribution are derived from those of $X$, of course.)