text:
Q: How do I detect if a panel is in the viewable window? Using Winforms and vb.net VS 2012:
If I have a large scrollable panel and I put a bunch of smaller panels inside the larger one. When I scroll the larger panel up or down, some of the smaller panels will scroll out of view. My question is, can I put a listener on the smaller panels so that the smaller panel knows when it has scrolled out of view?
I can't use the .visible property because that is always set to true even when the panel is not in the window. I also know I can set the .focus property to bring it back into view, but it can still lose focus when in the viewable window as soon as something else takes focus.
So is there a property or something that I can listen for that detects when the panel has scrolled out of view? And if not, is there something else I can do to detect this?
Thanks.

A: From the Scroll() and MouseWheel() events of the Panel, use code like this:
Private Sub Panel1_Scroll(sender As Object, e As ScrollEventArgs) Handles Panel1.Scroll
    CheckVisibility(sender)
End Sub

Private Sub Panel1_MouseWheel(sender As Object, e As MouseEventArgs) Handles Panel1.MouseWheel
    CheckVisibility(sender)
End Sub

Private Sub CheckVisibility(ByVal pnl As Panel)
    Dim results As New List(Of String)

    Dim pnlRectScreen As Rectangle = pnl.Parent.RectangleToScreen(pnl.Bounds)
    For Each child As Control In pnl.Controls
        Dim childRectScreen As Rectangle = pnl.RectangleToScreen(child.Bounds)
        If pnlRectScreen.IntersectsWith(childRectScreen) Then
            If pnlRectScreen.Contains(childRectScreen) Then
                results.Add(child.Name & ": Completely Visible")
            Else
                results.Add(child.Name & ": Partially Visible")
            End If
        Else
            results.Add(child.Name & ": Not Visible")
        End If
    Next

    ListBox1.DataSource = Nothing
    ListBox1.DataSource = results
End Sub

If you want to know when it becomes hidden only, then track the current visibility with a Dictionary() and do something when it changes to hidden.  Here's a more robust example:
Public Enum ControlVisibility
    Hidden
    PartialyVisible
    FullyVisible
End Enum

Private VisibiltyState As New Dictionary(Of Control, ControlVisibility)

Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
    Dim pnl As Panel = Panel1
    Dim pnlRectScreen As Rectangle = pnl.Parent.RectangleToScreen(pnl.Bounds)
    For Each child As Control In pnl.Controls
        Dim childRectScreen As Rectangle = Panel2.RectangleToScreen(child.Bounds)
        If pnlRectScreen.IntersectsWith(childRectScreen) Then
            If pnlRectScreen.Contains(childRectScreen) Then
                VisibiltyState.Add(child, ControlVisibility.FullyVisible)
            Else
                VisibiltyState.Add(child, ControlVisibility.PartialyVisible)
            End If
        Else
            VisibiltyState.Add(child, ControlVisibility.Hidden)
        End If
    Next
End Sub

Private Sub Panel1_Scroll(sender As Object, e As ScrollEventArgs) Handles Panel1.Scroll
    CheckVisibility(sender)
End Sub

Private Sub Panel1_MouseWheel(sender As Object, e As MouseEventArgs) Handles Panel1.MouseWheel
    CheckVisibility(sender)
End Sub

Private Sub CheckVisibility(ByVal pnl As Panel)
    Dim NewVisibility As ControlVisibility
    Dim pnlRectScreen As Rectangle = pnl.Parent.RectangleToScreen(pnl.Bounds)
    For Each child As Control In pnl.Controls
        Dim childRectScreen As Rectangle = pnl.RectangleToScreen(child.Bounds)
        If pnlRectScreen.IntersectsWith(childRectScreen) Then
            If pnlRectScreen.Contains(childRectScreen) Then
                NewVisibility = ControlVisibility.FullyVisible
            Else
                NewVisibility = ControlVisibility.PartialyVisible
            End If
        Else
            NewVisibility = ControlVisibility.Hidden
        End If

        ' has it changed?
        If VisibiltyState(child) <> NewVisibility AndAlso NewVisibility = ControlVisibility.Hidden Then
            Debug.Print(child.Name & " has become hidden: " & DateTime.Now.ToString("h:mm:ss.ffff"))
        End If

        VisibiltyState(child) = NewVisibility
    Next
End Sub


text:
Q: Newtonsoft Json deserialize, JProperty and JObjects? Im trying to deserialize a json-text/string by simply doing:
var jObject = JsonConvert.DeserializeObject<JObject>(myjsonstring);

The thing is that I later on need to iterate through the jObject.. since I will "serialize" it back to XML later on using a speciall format. But this deserialization give me a JProperty and a JObject for each "node" in the json.. is there any way to tell the serializer that Im only intressted of the JProperties or the JObjects.
=============
Edit
To explain it abit more..
the thing is that if i later on would type the following in the VS-watch:
jObject

It would give the result:
{ "myjson":{ "mytest":"myvalue" } }

And
jObject.Children().First()

would give me the following result/respons from the watch:
{"myjson":{ "mytest":"myvalue" } }

But the result/respons that I think would be more logical would be:
{ "mytest":"myvalue" }

Since thats the actuall Child object of the "myjson"-property.. so the question is.. how do I get that behavior that I actually want? or am I missing something?

A: To access value inside JObject I use JToken :
JToken child = jObject["myjson"];

If you want retrieve the value in a string you can serialize the JToken
string childInString = JsonConvert.SerializeObject(child);

Hope that help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to read file bytes from byte offset? If I am given a .cmp file and a byte offset 0x598, how can I read a file from this offset?
I can ofcourse read file bytes like this
byte[] fileBytes = File.ReadAllBytes("upgradefile.cmp");

But how can I read it from byte offset 0x598
To explain a bit more, actually from this offset the actual data starts that I have to read and before this byte offset it is just header data, so basically I have to read file from that offset till end.

A: Try code like this:
    using (BinaryReader reader = new BinaryReader(File.Open("upgradefile.cmp", FileMode.Open)))
        {
            long offset = 0x598;
            if (reader.BaseStream.Length > offset)
            {
                reader.BaseStream.Seek(offset, SeekOrigin.Begin);
                byte[]fileBytes =  reader.ReadBytes((int) (reader.BaseStream.Length - offset));
            }
        }

A: If you are not familiar with Streams, Linq, or whatever, I have simplest solution for you:
Read entire file into memory (I hope you deal with small files):
byte[] fileBytes = File.ReadAllBytes("upgradefile.cmp");

Calculate how many bytes are present in array after given offset:
long startOffset = 0x598; // this is just hexadecimal representation for human, it can be decimal or whatever
long howManyBytesToRead = fileBytes.Length - startOffset;

Then just copy data to new array:
byte[] newArray = new byte[howManyBytesToRead];

long pos = 0;

for (int i = startOffset; i < fileBytes.Length; i++)
{
    newArray[pos] = fileBytes[i];
    pos = pos + 1;
}

If you understand how it works you can look at Array.Copy method in Microsoft documentation.

A: By not using ReadAllBytes.
Get a stream, move to potition, read rest of files.
You basically complain that a convenience method made to allow a one line read of a whole file is not what you want - ignoring that it is just that, a convenience method. The normal way to deal with files is opening them and using a Stream.


text:
Q: Typescript inference error - variable with type string changes to undefined inside for loop I'm using await-to-js library for error handling (the to method in the example below comes from the library)
For some reason, the type of a variable changes to string | undefined inside of a for..of loop, when the value of the same variable is string outside of the loop.
Consider the following example (see testMethod for error):
function to<T, U = Error>(
    promise: Promise<T>,
    errorExt?: object
): Promise<[U, undefined] | [null, T]> {
    return promise
        .then<[null, T]>((data: T) => [null, data])
        .catch<[U, undefined]>((err: U) => {
            if (errorExt) {
                const parsedError = Object.assign({}, err, errorExt);
                return [parsedError, undefined];
            }

            return [err, undefined];
        });
}

async function retrieveAccessToken(): Promise<string> {
    const randomNumber = Math.random();

    if(randomNumber < 0.5) {
        throw new Error("Failed");
    }

    return "testToken";
}

function printAccessToken(accessToken: string) {
    console.log(accessToken);
};

async function testMethod(): Promise<boolean> {
    const accessTokenPromise = retrieveAccessToken();

    const [err, accessToken] = await to(accessTokenPromise);

    if(err){
        console.log("Failed");
        return false;
    }

    // No error here
    printAccessToken(accessToken);

    for(let i = 0 ; i < 5; i++){
        // Error! Type Argument of type 'string | undefined' is not assignable to
        // parameter of type 'string'.
        printAccessToken(accessToken);
    }

    return true;
}

This seems to be solved by adding a if check on accessToken e.g. if(!accessToken) however it doesn't make sense why the type of accessToken is string | undefined inside of the for loop but string outside of it?
Typescript playground

A: TypeScript has issues analyzing types in destructuring syntax. To get the expected behavior, assign the resolved value of to to a local variable, and reference accessToken after checking err.
Change:
    const [err, accessToken] = await to(accessTokenPromise);

    if(err){
        console.log("Failed");
        return false;
    }

Into:
    const toResult = await to(accessTokenPromise);

    const [err] = toResult;
    if(err){
        console.log("Failed");
        return false;
    }
    const [, accessToken] = toResult;

Playground link


text:
Q: BIND does not answer authoritatively I want to use BIND as a public nameserver for the companies domains. I'm using a fresh installation of ubuntu server 20.04.1 and BIND 9.16.1. The issue is that BIND never answers authoritatively. I can see this using dig. To locate the issue I tried it with a single and minimal zone "example.com" but without any success. The zone file is db.example.com:
example.com.        86400    IN    SOA    ns1.example.com.    hostmaster.example.com. (
                                      1     ; Serial
                                      900   ; Refresh
                                      300   ; Retry
                                      86400 ; Expire
                                      600 )  ; Negative Cache TTL
example.com.        86400    IN    NS    ns1.example.com.
example.com.        86400    IN    MX    10 mail.example.com.
ns1.example.com.    86400    IN    A     123.123.123.123
mail.example.com.   86400    IN    A     125.125.125.125

Of course, the IP addresses above are not the real IP addresses, but the IP address for ns1.example.com is the public IP address of the system BIND is running on. named-checkzone is happy with it. In named.conf.local only the following lines are added:
zone "example.com" {
    type master;
    file "/var/lib/bind/db.example.com";
};

named.conf.options:
options {
    directory "/var/cache/bind";
    dnssec-validation auto;
    auth-nxdomain no;
    listen-on { any; };
    listen-on-v6 { any; };
    recursion no;
};

Using dig with ANY I can see all records in the zone file but BIND always answers AUTHORITY: 0. Also the A records do not appear in the answer section but in the additional section. Unfortunately I'm not allowed to post the original output of dig because it looks like spam. The zone is configured as master and the NS record points to the IP address of the server BIND is running on. Another thought was that BIND may try to query "example.com" from root and knows that it is not really the authoritative nameserver. So I also tried the same with the domain "example.invalid" that really should not exist anywhere. The result was the same as for "example.com". I never had this issue before. What else can I try to solve this issue?

A:
BIND always answers AUTHORITY: 0.

That's normal and it doesn't mean the response wasn't authoritative. Quite the opposite, this section is meant to contain records which tell the client that the authority is somewhere else – for example, if you queried a nameserver hosting the parent com zone or even the root zone, you would get a "referral" response which contains NS records in this section.
As far as I know, an actual authoritative response should never contain any records in this section.
So in other words, you're looking at the wrong part of dig's output. To find out whether a response was authoritative or not, look at the "flags" section – the aa flag (Authoritative Answer) is the indicator.

Also the A records do not appear in the answer section but in the additional section

That's also normal. They will not appear in the answer section because your example.com domain does not have any A records.
However, it has some record types (NS and MX) which reference another domain name which has A records. Normally a second query would be necessary to resolve them to actual addresses, but the DNS server can optionally include those A/AAAA records in the Additional section.
So when you query dig example.com MX, the Answer section will have the MX records for example.com (i.e. exactly what you queried), and the Additional section will have the A/AAAA records for mail.example.com (which you didn't query for, but the server included them to speed things up).


text:
Q: How to power a phone with no battery properly? I have an LG G3 phone that I want to use as a stationary device and leave it hooked up permanently.
I prefer not to do it with a battery for various understandable reasons.
My questions are:
What parts do I need to convert USB 5V to 3.8V?
(I guess a voltage regulator, but is that all I need? and which one to get?)
What other factors (like currant) should be considered and how to deal with them?
Thanks!

A: In theory, I don't see why applying the specified battery voltage on the correct battery terminals would not work. Try to avoid overvoltages!
Obvious reasons are not obvious to everybody. I assume you don't want the battery in the loop so you don't have to worry about it aging over time, bloating and potentially causing problems?
A linear voltage regulator would probably do the trick. I would personally add a good amount of capacitance between the regulator and the phone to smooth out any sudden changes in your phone's power consumption. If you want to ensure you never go over a safe voltage, a Zener diode would be your friend.
Good luck, and let us know of the outcome!

A: There should be no big problem to replace internal battery with external DC source. In my former place of work the software people routinely (and without any reservations!) used various benchtop variable PSU to feed phones and tablets under development directly to battery connector, because the internal charger management firmware/software was broken at the time.
From your level, the module like "Mini LM2596s 3A DC to DC Buck Converter Power Supply Step Down Module" will do the job. You can set the output voltage to something in the range between 3.6 to 4.2 V, although the phone might still be confused regarding "battery charge status". If the confusion won't be gone after several power-on-off cycles, then you are out of luck, since phones use pretty sophisticated methods to check battery health status.
Also, if the battery has a built-in thermal sensor (usually as a third contact on battery case) , you might need to simulate "good thermal status" by connecting a 10k resistor to ground. Your battery (BL-53YH) does have two additional contacts, but in recent phones they are used for stick-on near-field antenna, so no worry about them.
However, it might have more economical sense to get a cheap replacement battery from e-Bay or AliExpress, they seem to be in $10 range in qty.1. At least the risk will be much less than from developing a regulator in battery fromfactor on your own, with AC-DC wall supply (or carrying a USB cable), or other ugly stuff.

A: Why don't you just plug the USB into your phone ?
And if you want to convert 5V to 3.8V you have multiple possibilities. You could use a LM2576 or directly divide the voltage with resistors.

A: I have just put 5 volts right on the + and - of were the battery would go. They do have another pin I guess for sense.
I did it on 2 old cellphones that the battery went bad on. But they only stay going for about a day. It thinks the battery is draining down very low so it turns off. I guess have to put something on the 3rd pin but I don't know what.
I just solder the wires on the pins and made a hole in the back cover to put the wire though were the battery would go.
Did a little video on YouTube of it.
-Raymond Day


text:
Q: excel vba to copy/paste data fron another sheet if conditions match Sheet saskaita faktura
Sheet darbinis
hopping to find help here. Can't get data from one sheet to another using conditions.
My question:
I will use example :
if sheet1 cell d22 = sheet2 column B cells 3(4;5;6;..), then
sheet1 cell P3 data copy and paste to sheet2 column C cells 3(4;5;6;..)
this should happen if i click button.
Thank you in advance.
Darius
Adding code:
Sub bandymas()

If Sheets("Sàskaita-Faktûra").Range("d22") = Sheets("Darbinis").Range("D:D") Then
Sheets("Sàskaita-Faktûra").Range("P3").Copy
Sheets("Darbinis").Range ("O:O")
PasteSpecial Paste:=xlPaste, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Application.CutCopyMode = False
    End If

End Sub

A: P is the source, o is destination, you can  adjust
Sub bandymas()
LastRow = Sheets("Darbinis").Cells(Sheets("Darbinis").Rows.Count, "D").End(xlUp).Row
dim i
i=0
for each c in Sheets("Darbinis").Range("D1:D" & lastRow)
    i=i+1
    If Sheets("Sàskaita-Faktûra").Range("d22") = c Then
       Sheets("Darbinis").Range("O" & i) = Sheets("Sàskaita-Faktûra").Range("P3").value
    endif
next
End Sub

A: I found a solution, code looks:
Private Sub CommandButton2_Click()

Range("P3").Select
    Selection.Copy
    Range("P5").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False

lastrow = Sheets("Darbinis").Cells(Sheets("Darbinis").Rows.Count, "D").End(xlUp).Row
Dim i
i = 0
For Each c In Sheets("Darbinis").Range("D1:D" & lastrow)
    i = i + 1
        If Sheets("Sàskaita-Faktûra").Range("d22") = c Then
       Sheets("Darbinis").Range("O" & i) = Sheets("Sàskaita-Faktûra").Range("P5").Value
    End If
Next
End Sub

then it work as it suposed.


text: Q: I need an MPI Simulator I want to know the performance of an C application using MPI on a computing cluster, but I only have one server, whose CPU are Intel Xeon E5-2692v2 with Accelerator card(XEON PHI). Is there any tools can simulate it? I know one called MPI-SIM, but, unfortunately, it's written for IBM SP2 and a little old.


text:
Q: Find a and p in the given question
I would be grateful if someone helps me with this question.
I get $p$ but to get $a$, the term with $a$ vanishes.
I checked continuity at $x=1$ for finding $p$.
$p$ comes out to be $-2$.

A: As $f(x)$ is differentiable for $x\in(0,2)$ we know that the  limit $$\lim_{n\to\infty}\dfrac{ax(x-1)\left(\cot^n\left(\dfrac{\pi x}4\right)\right)+px^2+2}{\left(\cot^n\left(\dfrac{\pi x}4\right)\right)+1}$$ is finite, and $f(x)$ is continuous for $x\in(0,2)$.
$$$$
Let $$L=\lim_{n\to\infty}\dfrac{ax(x-1)\left(\cot^n\left(\dfrac{\pi x}4\right)\right)+px^2+2}{\left(\cot^n\left(\dfrac{\pi x}4\right)\right)+1}$$
$$\Rightarrow L=\lim_{n\to\infty}\dfrac{ax(x-1)+(px^2+2)\left(\tan^n\left(\dfrac{\pi x}4\right)\right)}{1+\left(\tan^n\left(\dfrac{\pi x}4\right)\right)}$$
$$$$
For $x\in(1,2)$, $\dfrac\pi4<\dfrac{\pi x}{4}<\dfrac{\pi}2\Rightarrow 0<\cot\left(\dfrac{\pi x}4\right)<1\Rightarrow\cot^n\left(\dfrac{\pi x}4\right)\to 0 $ as $n\to\infty$
$$$$
Hence $$L=\lim_{n\to\infty}\dfrac{ax(x-1)\left(\cot^n\left(\dfrac{\pi x}4\right)\right)+px^2+2}{\left(\cot^n\left(\dfrac{\pi x}4\right)\right)+1}=\dfrac{0(ax(x-1))+px^2+2}{0+1}=px^2+2$$
$$$$
We need that the limit is equal to $0$ as $x\to 1^+$ for the function to be continuous. Hence $\lim_{x\to1^+}px^2+2=0\Rightarrow p=-2$.
$$$$
Let $L_1$ and $L_2$ be the limits (of $f(x)$) from the left and from the right of $x=1$  respectively.
$$$$
Thus $$L_2=\lim_{n\to\infty}\dfrac{ax(x-1)\left(\cot^n\left(\dfrac{\pi x}4\right)\right)+2-2x^2}{\left(\cot^n\left(\dfrac{\pi x}4\right)\right)+1},x\to1^+$$
$$L_1=\lim_{n\to\infty}\dfrac{ax(x-1)+(2-2x^2)\left(\tan^n\left(\dfrac{\pi x}4\right)\right)}{1+\left(\tan^n\left(\dfrac{\pi x}4\right)\right)},x\to1^-$$
$$$$
Now, for $x\in(0,1)$, $\tan^n\left(\dfrac{\pi x}4\right)\to0$ as $n\to\infty$ $$$$For $x\in(1,2)$, $\cot^n\left(\dfrac{\pi x}4\right)\to 0$ as $n\to\infty$.
$$$$
Thus, $$L_2=\dfrac{2-2x^2}{2},x\to 1^+$$
$$\Rightarrow L_2=\lim_{h\to 0}\dfrac{2-2(1+h)^2}{2}=\lim_{h\to0}\dfrac{-2h^2-4h}{2}=\lim_{h\to0}\dfrac{-2h(h-2)}{2}=\lim_{h\to0}\dfrac{2h(2-h)}{2}$$
$$$$
$$L_1=\dfrac{ax(x-1)}{2},x\to1^-$$
$$\Rightarrow L_1=\lim_{h\to 0}\dfrac{a(1-h)(1-h-1)}{2}=\lim_{h\to 0}\dfrac{a(1-h)(-h)}{2}$$
$$$$
Now it is given that $f(x)$ is differentiable for $x\in(0,2)$. Thus, $f(x)$ is continuous for $x\in(0,2)$. Thus $f(x)$ must be continuous at $x=1$. Therefore, $L_2$ must be equal to $L_1$ (and both must be respectively equal to $f(1)=0$). Equating both $L_2$ and $L_1$,
$$$$
$$\lim_{h\to0}\dfrac{2h(2-h)}{2}=\lim_{h\to 0}\dfrac{a(1-h)(-h)}{2}$$
$$\Rightarrow \lim_{h\to0}\dfrac{2h(2-h)}{2}-\lim_{h\to 0}\dfrac{a(1-h)(-h)}{2}=0$$
$$$$We now use the property $\lim_{x\to a}f(x)\pm\lim_{x\to a}g(x)=\lim_{x\to a}(f\pm g)(x)$
$$$$
$$\Rightarrow \lim_{h\to0}\left(\dfrac{2h(2-h)}{2}-\dfrac{a(1-h)(-h)}{2}\right)=0$$
$$\Rightarrow \lim_{h\to0}\dfrac{2h(2-h)+a(1-h)(h)}{2}=0$$
$$\Rightarrow 2(2-h)+a(1-h)=0, h\to0$$
$$\Rightarrow a+4=0$$
Finally, we get $a=-4$.


text:
Q: MGF of discrete random variable - simplification of series? I want to find the moment-generating function of a discrete random variable $X$ with probability mass function $p_X(x)=\frac{2}{3^{x+1}}$ for $x \in \{1,2,3...\}$
For discrete random variables, $M_x(t) = \sum_{x=0}^{\infty} e^{tx}p_X(x)$
Thus, for my problem, $M_x(t)= \sum_{x=0}^{\infty} \frac{2e^{tx}}{3^{x+1}}$
My question is: can this series be simplified at all? My typical strategy in such situations is to use properties of Taylor series (e.g., $\sum_{n=0}^{\infty}x^n=\frac{1}{1-x}$), but I do not see any obvious candidates.

A: The given series is $$2/3* \sum_{n=0}^{\infty} {(\frac{e^t}{3}})^n$$This is a geometric series and also in the form of the example provided in the question. (Just put x = $\frac{e^t}{3}$)


text:
Q: Is there a With statement in Javascript like ther is in VB I can hold my own in VBA and now I am venturing out into Javascript.
In VBA if you are going to use the same object you can prefence it with and With statement and not need to reference the object again. For example;
With oSomeForm
   .Name = "some neat name"
   .Refresh
End With   ' oSomeForm

Is there something similar for Javascript?

A: Yes, there is. Using it is strongly discouraged for the reasons described in this YUI blog post by Douglas Crockford, and you can't use it in strict mode (which you should be using, and which is the default in modules), but it's there.
with (someForm) {
    name = "some neat name";
    // ...
}

Note that you don't use a leading . as you do in VB.

Instead of using with, consider just repeating the variable name. If it's long, or you're using with on the result of an expression, you might use a local alias. For instance, in ES2015 and later you can use a local const in a block:
{
    const o = /*...the long identifier or expression...*/;
    o.name = "some neat name";
}

MDN is a very good community-edited resource for JavaScript information


text:
Q: What is the procedure to switch app from one developer account to another developer account? Hi I am currently using a individual developer account to submit my app to the app store. My current version in the store is already at 1.7.
However now, I want to switch using my company account to submit the same app.
What is the procedure in doing so? Do I need to remove the current version from the app store? Also do I need to reset my version of the app to 1.0?

A: You can transfer the ownership of an app to another developer without removing the app from the store. The app retains its reviews and ratings during and after the transfer, and users continue to have access to future updates. There's no limit to the number of apps you can transfer, but each app needs to be transferred individually.
All transfers and deletions are performed by the team agent. To learn more about a team agent's function.
Here is step by step explanation on Apple's Documentation.


text:
Q: How to optimize cudaHostAlloc and cudaLaunchKernel times in pytorch training I am trying to profile my model with pytorch profiler. I used the below code to profile
with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], record_shapes=True) as prof:
    with record_function("model_inference"):
        output_batch = self.model(input_batch)
print(prof.key_averages().table(sort_by="cpu_time_total", row_limit=10))

The profiler output is as follows
-------------------------------------------------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------
                                                   Name    Self CPU %      Self CPU   CPU total %     CPU total  CPU time avg     Self CUDA   Self CUDA %    CUDA total  CUDA time avg    # of Calls
-------------------------------------------------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------
                                        model_inference         3.17%      83.011ms        63.97%        1.675s        1.675s       0.000us         0.00%     373.844ms     373.844ms             1
                                            aten::copy_         0.24%       6.333ms        39.93%        1.046s       1.504ms      28.758ms         7.69%      29.035ms      41.777us           695
                                          cudaHostAlloc        36.02%     943.053ms        36.02%     943.053ms      30.421ms       0.000us         0.00%       0.000us       0.000us            31
                                       cudaLaunchKernel        35.93%     940.773ms        35.93%     940.773ms      86.619us       0.000us         0.00%       0.000us       0.000us         10861
                                           aten::repeat         0.04%     979.000us        33.77%     884.170ms      30.489ms       0.000us         0.00%     204.000us       7.034us            29
                                           aten::conv2d         0.06%       1.481ms         8.71%     228.183ms     695.680us       0.000us         0.00%     145.688ms     444.171us           328
                                      aten::convolution         0.05%       1.391ms         8.66%     226.702ms     691.165us       0.000us         0.00%     145.688ms     444.171us           328
                                     aten::_convolution         0.10%       2.742ms         8.61%     225.311ms     686.924us       0.000us         0.00%     145.688ms     444.171us           328
                                aten::cudnn_convolution         0.53%      13.803ms         8.33%     218.051ms     664.790us     137.822ms        36.87%     137.822ms     420.189us           328
                                               cudaFree         7.46%     195.373ms         7.46%     195.373ms      48.843ms       0.000us         0.00%       0.000us       0.000us             4
-------------------------------------------------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------  ------------
Self CPU time total: 2.618s
Self CUDA time total: 373.844ms

I notice that a large part of the time (self CPU) is taken by cudaHostAlloc and cudaLaunchKernel. What are these cudaHostAlloc and cudaLaunchKernel? Is it possible to reduce this time? If yes how? Are there any standard operations that I'm missing which is leading to this high time consumption?
PS: I'm new to profiling as such. Kindly let me know if any other information is needed.

A: I am not an expert but I think cudaLaunchKernel is called at every operation done with cuda. So I think you cannot optimize it.
If you plot a detailed tracing https://pytorch.org/tutorials/recipes/recipes/profiler_recipe.html#using-tracing-functionality, you see that it is called everytime you do a cuda operation like here for a linear layer.

One note on you profiler output: aten::copy_ cudaHostAlloc cudaLaunchKernel and aten::repeat all take roughly 40% of the CPU total time. I think it may be related to ProfilerActivity.CUDA that records CUDA operation but it also add a lot of CPU time on your first CUDA operation that is profiled. In my case a simple torch.ones(1000, device="cuda") took a full second of CPU time because it was the first cuda operation.
It may be the problem in your case, try to remove ProfilerActivity.CUDA and maybe aten::copy_ cudaHostAlloc cudaLaunchKernel and aten::repeat will have a much smaller CPU time and will disappear from the table.


text:
Q: why does following code give different output in C , C++? The following code gives output as
1, 4, 4 in C whereas
1, 1, 4 in C++
#include<stdio.h>
int main()
{
    char ch = 'A'; //initialise
    //printing output
    printf("%d, %d, %d", sizeof(ch), sizeof('A'), sizeof(3.14f));
    return 0;
}

A: Because a character literal is of type int in C but of type char in C++.


text:
Q: Display XY coordinates (with different lengths) in ArcGIS does not work I have a list of Excel lat long coordinates in a spreadsheet that I want to import as points in ArcMap by displaying the XY Data.
lat      lon
5235746   486124
5236799   487447
5238042   489453
523686    486487
5236528   49301

However, ArcMap does not seem to recognise/display my coordinate data as points. I think because there are some 6-numbered coordinates in there as well. How should I tackle this problem?

A: In Excel reload your file and export it in CSV format. Reload the CSV file in ArcMap. CSV files do wonders.
Also always remember that we are used to say Lat-Long, however from a mathematical point of view, I always say Long-Lat to remind myself that "Long is X" and "Lat is Y".


text:
Q: Android - save value on LocalStorage before WebView.loadUrl() Before I load a URL on WebView i want to set a value inside browser LocalStorage.
Till now the only way I did managed to set this value is after the page is loaded. This is how I can set the value:
browser.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
                loadUrl("javascript: LocalStorage.set('namespace', 'key', 'value');");
        }
}

I did try to override the method onPageStarted(), but the value is not stored.
How can I set this key/value before the call browser.loadUrl()? The url/page depends on this value, so I need to set the value before I load the page.

A: What you can do is set a redirect into the javascript to the actual url and load the javascript plus redirect using webview.loadData().
 String injection = "";
 webview.loadData(injection, "text/html", null);

Be aware though that you might need to save that to a file first before it works: see How to load a javascript redirect into android webview?

A: You can use WebViewClient.onPageStarted() for this.
webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        String js = "window.localStorage.setItem('key', 'value');";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.evaluateJavascript(js, null);
        } else {
            webView.loadUrl("javascript:" + js);
        }
    }
});


text:
Q: Follow the plan vs follow through with the plan What's the difference between saying 'I will follow the plan' and 'I will follow through with the plan'? I have encountered both constructions but couldn't figure out the difference in meaning.

A: The dictionaries tell that to "follow through" is "to finish all aspects of a task"
"To follow the plan" is just doing what the plan says. Regardless of you finishing the task or not
So to "follow through with the plan" is to follow the plan until the end and finish all tasks in the plan


text:
Q: Create nested property from variable Assume I have an empty object like so:
var object = {};

How can I add a property with a nested object using variables?  E.g.:
person
name

var obj1 = $( '#obj1' ).text();
var nestedObj = $( '#nestedObj' ).text();
function (obj1, nestedObj) {
    //Trying to simulate object.person.nestedObj
    object[obj1][nestedObj] = 'someone';
}

A: You need to make sure object[obj1] is valid first:
    object[obj1] = object[obj1] || {};
    object[obj1][nestedObj] = 'someone'

This basically says "If object[obj1]" is undefined, make it an object, otherwise assign it to itself.

A: object[obj1] has to be initialized:
var obj1 = $( '#obj1' ).text();
var nestedObj = $( '#nestedObj' ).text();

if(!object[obj1]) {
    object[obj1] = {};
}

object[obj1][nestedObj] = 'someone';

A: function O(key, val) {
    var o = {};
    o[key] = val;
    return o;
}

function f(obj1, nestedObj) {
    $.extend(true, object, O(obj1, O(nestedObj, 'someone')));
}


text:
Q: Django: sitemap.xml and 'unknown timezone' Django sitemaps worked fine on a previous server, and work fine in my development environment, but break in production on a new server, with:
ValidationError: [u'Unknown timezone']
(traceback below). I was also getting a similar error when trying to access one of our models from admin.
Update:
The path build/bdist.linux-x86_64/egg/timezones in the traceback tipped me off that there was some weird path stuff going on. Turned out someone had copied a bunch of stuff from another server rather than doing proper pip installs. I removed some old libs, fixed a virtualenv default path, and pip installed django-timezones. All working nicely now. Leaving this in case it's helpful to anyone else.

The sitemap docs don't mention anything about timezone configuration or dependencies:
https://docs.djangoproject.com/en/dev/ref/contrib/sitemaps/
The server's timezone is correctly set  to America/Los_Angeles, and I've set the same in settings.py I'm not sure what else to look at here and Google's turning up nothing.
I reference 8 models in my SiteMaps definition in urls.py but only one BlogSiteMap is causing the breakage (if I comment it out the breakage stops, but then I don't have blog posts in the sitemap. It consists of:
class BlogSitemap(Sitemap):
    changefreq = "weekly"
    priority = 0.7

    def items(self):
        return Post.objects.filter(status=2).order_by('-modified')

    def lastmod(self, obj):
        return obj.modified

The blog Post model is this (edited slightly for brevity)
class Post(models.Model):
    """Post model."""

    title           = models.CharField(_('title'), max_length=200)
    slug            = models.SlugField(_('slug'), unique_for_date='publish')
    author          = models.ForeignKey(User, blank=True, null=True)
    body            = models.TextField(_('body'))
    tease           = models.TextField(_('tease'), blank=True)
    status          = models.IntegerField(_('status'), choices=STATUS_CHOICES, default=2)
    allow_comments  = models.BooleanField(_('allow comments'), default=True)
    fp_show         = models.BooleanField('Show on homepage',default=False)
    order           = models.IntegerField(blank=True, null=True)
    publish         = models.DateTimeField(_('publish'),default=datetime.now())
    created         = models.DateTimeField(_('created'), auto_now_add=True)
    modified        = models.DateTimeField(_('modified'), auto_now=True)
    categories      = models.ManyToManyField(Category, blank=True)
    tags            = TagField()
    objects         = PublicManager()

    def __unicode__(self):
        return u'%s' % self.title

    @permalink
    def get_absolute_url(self):
        return ('blog_detail', None, {
            'year': self.publish.year,
            'month': self.publish.strftime('%b').lower(),
            'day': self.publish.day,
            'slug': self.slug
        })

Using:
Django 1.3
Python 2.7
RHEL 5.7
Thanks.
Traceback (most recent call last):

 File "/home/username/virtualenvs/kdmc/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response
   response = callback(request, *callback_args, **callback_kwargs)

 File "/home/username/virtualenvs/kdmc/lib/python2.7/site-packages/django/contrib/sitemaps/views.py", line 39, in sitemap
   urls.extend(site().get_urls(page=page, site=current_site))

 File "/home/username/virtualenvs/kdmc/lib/python2.7/site-packages/django/contrib/sitemaps/__init__.py", line 75, in get_urls
   for item in self.paginator.page(page).object_list:

 File "/home/username/virtualenvs/kdmc/lib/python2.7/site-packages/django/db/models/query.py", line 107, in _result_iter
   self._fill_cache()

 File "/home/username/virtualenvs/kdmc/lib/python2.7/site-packages/django/db/models/query.py", line 772, in _fill_cache
   self._result_cache.append(self._iter.next())

 File "/home/username/virtualenvs/kdmc/lib/python2.7/site-packages/django/db/models/query.py", line 286, in iterator
   obj = model(*row[index_start:aggregate_start])

 File "/home/username/virtualenvs/kdmc/lib/python2.7/site-packages/django/db/models/base.py", line 297, in __init__
   setattr(self, field.attname, val)

 File "/home/username/virtualenvs/kdmc/lib/python2.7/site-packages/django/db/models/fields/subclassing.py", line 99, in __set__
   obj.__dict__[self.field.name] = self.field.to_python(value)

 File "build/bdist.linux-x86_64/egg/timezones/fields.py", line 43, in to_python
   return coerce_timezone_value(value)

 File "build/bdist.linux-x86_64/egg/timezones/utils.py", line 34, in coerce_timezone_value
   raise ValidationError("Unknown timezone")

ValidationError: [u'Unknown timezone']

A: See Update: section above - this turned out to be a series of conflicts arising from old installed libraries and an incorrect path in the virtualenv.


text:
Q: C++/CLI Wrapper DLL TypeLoadException too many fields I have native (unmanaged) C++ DLLs that are being wrapped by a single C++/CLI dll (linking through the .lib files). These unmanaged C++ DLLs have quite a few classes with a ton of methods and a ton const data (e.g. strings, hex values, etc) which are defined in included headers.
But for the C++/CLI wrapper DLL its only a wrapping and marshalling layer for the native dll. However its binary size is as big as the native dll.
I believe this is causing me to hit the hardcoded limit which throws the exception when it is being loaded by a C# application:
System.TypeLoadException: Internal limitation: too many fields
The C# application will never use the fields defined in the headers for the native DLLs.
It was able to alleviate this issue through enabling of string pooling (shaving off a few MB), but it seems like a hack.
Why is a simple wrapper of a DLL the same size as that DLL? Is there a way where I can mark the const data such that the C# application won't load them?

A: You are falling into a pretty common trap, the C++/CLI compiler works too well.  It is capable of compiling any C++03 compatible native C++ code into IL when #pragma managed or /clr is in effect.  Works well at runtime too, it gets just-in-time compiled by the jitter to machine code, just like regular managed programs will be.
That's the good news.  The bad news is that this code does not execute like managed code.   It doesn't get verified and it doesn't get the garbage collector love.  It also doesn't run as efficiently as regularly compiled C++ code, you are missing out on the extra time that the C++ code optimizer has available get the absolute best possible machine code.
And the one restriction that made your program bomb.  Any global variables and free functions are compiled into members of the hidden <Module> class.  Required because the CLR doesn't support globals.  Members of a managed class get a metadata token, a number that uniquely identifies them in the metadata tables.  A token is a 32-bit value with the low 16-bits used to number them.  Kaboom when you created a <Module> class with more than 65535 members.
Clearly this is all quite undesirable.  You'll need to pay more attention to what code gets compiled to IL and what code gets compiled to machine code.  Your native C++ source code should be compiled without the /clr option in effect.  Shift+click select those files and set the option.  Where necessary, use #pragma un/managed to switch the compiler back and forth within one source code file.

A:
Why is a simple wrapper of a DLL the same size as that DLL? Is there a way where I can mark the const data such that the C# application won't load them?

This is typically because you're compiling the entire project with /CLR.
If you're very careful to only include the absolute bare minimum requirements into the .cpp files which are compiled with /CLR, and only compile the .cpp files which are managed classes with /CLR, the wrapper projects tend to be far simpler and smaller.  The main issue is that any header that's used by a /CLR compiled .cpp file creates proxy types for all of the C++ types, which can explode into a huge number of fields or types in the assembly.
Using the PIMPL idiom to "hide" the native code behind and opaque pointer can also dramatically shrink the number of types exposed to the managed portion of the assembly, as this allows you to not include the main headers within the managed code.


text:
Q: Blender not starting Lubuntu 13.04 PowerPC I have installed Blender via apt-get on a PowerPC G4 Mac Mini running Lubuntu 13.04, and now it will not start over VNC.
Output from running blender in the terminal:
Color management: using fallback mode for management
Xlib:  extension "XInputExtension" missing on display "lubuntu:1".
connect failed: No such file or directory
/build/buildd/blender-2.66a/intern/ghost/intern/GHOST_WindowX11.cpp:192: X11 glXQueryVersion() failed, verify working openGL system!
initial window could not find the GLX extension, exit!

I know GLX is part of OpenGL, but I have no knowledge of how to install it.

A: I use this on my lubuntu
sudo add-apt-repository -y ppa:irie/blender
sudo apt-get update
sudo apt-get install blender

This is my screenshot when I install blender on lubuntu.


text:
Q: Magento 2 How to include custom library in controller I have created custom extension with some library classes. I have placed the libraries in lib/internal/SSOSdk folder. I need to include one of the library class in my controller. I have used the below code but it gives Class not found error.
Here is my code
namespace Company\Sso\Controller\Login;

require_once('lib/internal/SSOSdk/SSO.php');

    class Login extends \Magento\Framework\App\Action\Action
    {
        private $resultPageFactory;

        private $scopeConfig;

        public $storeManager;

        public function __construct(
            \Magento\Framework\App\Action\Context $context,
            \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
            \Magento\Store\Model\StoreManagerInterface $storeManager,
            \Magento\Framework\View\Result\PageFactory $resultPageFactory
        ) {
            $this->resultPageFactory = $resultPageFactory;
            $this->scopeConfig = $scopeConfig;
            $this->storeManager = $storeManager;
            parent::__construct($context);
        }

         public function execute()
        {
            $apiUrl = 'test.com';
            $clientId = '123';
            $clientSecret = '456';

            $params = $_GET;

            $sso = new SSO($apiUrl, $clientId, $clientSecret);
            try {
                if($params['error']){
                    $sso->notifyJs(false, $params);
                }else{
                    $sso->notifyJs(true, $params);
                }
            } catch (Exception $e) {
                $sso->notifyJs(false, $e);
            }

        }
    }

SSO.php
class SSO {

    private $_clientId, $_clientSecret, $_hostUrl;

    public function __construct($hostUrl, $clientId, $clientSecret){
        $this->_hostUrl = $hostUrl;
        $this->_clientId = $clientId;
        $this->_clientSecret =$clientSecret;
    }

    public function setHostUrl($hostUrl){
        $this->_hostUrl = $hostUrl;
    }
    .......

}

How can I do this?

A: try this

require_once(__DIR__ . '../../../../lib/internal/SSOSdk/SSO.php');

instead of

require_once('lib/internal/SSOSdk/SSO.php');

Also.use

new \SSO

instead of

new SSO

But I suggest converting your classes to psr-2 format php-fig.org/psr/psr-2 right solution.


text:
Q: YouTube API Key Security - How worried should I be? I'm getting ready to launch an Angular/Node web application which uses the YouTube V3 API. The app was released about 3 weeks ago as a "beta version" for market validation and was pretty successful in beta. It's not going to be a commercial success, just a fun app that makes peoples lives a little bit easier. I have one issue/concern, should I be hiding my YouTube V3 API key, client id, and scopes? Or can I assume that since only my domain name is whitelisted, that the potential hackers/people who try to use the API key, won't be able to make any calls or do any damage so therefore I have nothing to worry about?
These are the specific calls I'm worried about (not the real ids/keys)
Index.html Script Tag
    var OAUTH2_CLIENT_ID ='_#H#RJHWEJFHEFUIEHFUHEFHEJFU.apps.googleusercontent.com';
    var OAUTH2_SCOPES = ['https://www.googleapis.com/auth/youtube'];

In Angular, Controller.js
    .value('google_api_key', 'jfasdkjfdnstnewurweqjtndi')
    gapi.client.setApiKey(google_api_key);

A: For Simple Access to Google APIs, API key is the only credential required for the request, and it is a unique identifier of your app/project. It provides API access and is subject to quotas.
You should keep it a secret!
If you have a client-side-only app (without a server), then use OAuth 2.0 Client-side Flow
From Google's Documentation:

Best practices for securely using API keys:
When you use API keys in your applications, take care to keep them secure. Publicly exposing your credentials can result in your account being compromised, which could lead to unexpected charges on your account. To keep your API keys secure, follow these best practices:

*

*Do not embed API keys directly in code
API keys that are embedded in code can be accidentally exposed to the public—for example, if you forget to remove the keys from code that you share. Instead of embedding your API keys in your applications, store them in environment variables or in files outside of your application's source tree.

*Do not store API keys in files inside your application's source tree
If you store API keys in files, keep the files outside your application's source tree to help ensure your keys do not end up in your source code control system. This is particularly important if you use a public source code management system such as GitHub.

*Restrict your API keys to be used by only the IP addresses, referrer URLs, and mobile apps that need them
By restricting the IP addresses, referrer URLs, and mobile apps that can use each key, you can reduce the impact of a compromised API key. You can specify the hosts and apps that can use each key from the Google Developers Console by opening the Credentials page and then either creating a new API key with the settings you want, or editing the settings of an API key.

*Delete unneeded API keys
To minimize your exposure to attack, delete any API keys that you no longer need.

*Regenerate your API keys periodically
You can regenerate API keys from the Google Developers Console by opening the Credentials page and clicking Regenerate key for each key. Then, update your applications to use the newly-generated keys. Your old keys will continue to work for 24 hours after you generate replacement keys.

*Review your code before publicly releasing it
Ensure that your code does not contain API keys or any other private information before you make your code publicly available.


text:
Q: jSignature - Increase height of signature acceptance area Using jSignature on a mobile device - all works.
The problem that I am having is that on a phone (like my Galaxy S4) i want to increase the height of the signature drawing area to make it easier to sign. I have passing height & width as well as passing a CSS class ...
$('#signature').jSignature({'cssclass': 'signatureWrapper'}).focus();

While it appears to increase the size of the surrounding box, it doesn't appear to increase the height of the signature area.
Thanks for any suggestions or guidance.

A: You need to target canvas.jSignature with your CSS.
CSS File
canvas.jSignature { height: 500px; }

It looks like you'll also need to change the height="" attribute on the <canvas> element as well.
I did this on the demo page for jSignature ( http://willowsystems.github.io/jSignature/#/demo/ ) with the Chrome inspector and it worked fine.


text:
Q: How to type an inline chi in Latex \( \chi \) produces a letter that is slightly below the row, but I've seen in many papers a chi that is in the same line as the rest of the row)

A: I'm not sure why you'd want this. However, it's easy to provide it:
\documentclass{article}

\DeclareRobustCommand{\rchi}{{\mathpalette\irchi\relax}}
\newcommand{\irchi}[2]{\raisebox{\depth}{$#1\chi$}} % inner command, used by \rchi

\begin{document}

dg $\chi$ dg $\rchi$ dg

$\chi_\chi$ $\rchi_\rchi$

\end{document}

Left the normal chi, right the raised one. I added the baseline in the image just for clarity.

With \DeclareRobustCommand, \rchi can be used also in section titles (but always in math mode, so \section{... $\rchi$ ...}).


text:
Q: How to save one Doctrine entity to two database tables (required for MySQL optimisation) In my database I've a table file and a table file_content. The file table stores the metadata of the file such as name, mime and some more. The file_content stores a blob with the file content. I'm not storing the blob in the same table as the metadata for performance reasons only.
For a 'version 2' of my project I'm looking into Doctrine (2.3). To me, a "File" seems to be one entity, with properties such as name, mime, extension, content that should be used like this:
$file = new File();
$file->setName('hello.txt');
$file->setMime('text/plain');
$file->setContent('Hello world!')
$em->persist($file);
$em->flush();

Is this behaviour possible? To me it makes no sense to create two entities for something that's really just one entity. I could not find anything about it in the documentation and I read in a 2-year-old topic that it isn't possible in Doctrine 2.1: Doctrine 2.1 - Map entity to multiple tables
Someone any suggestions how to handle this correctly? I'm new to Doctrine and have been playing around with it a bit to see if it's the right choice for my project. Thanks.

A: I'm going to suggest a different approach even though it's a somewhat older question. Instead of making two entities, you should make three.
Create FileMetadata, which holds name, mimetype, etc. Create FileContent, which holds the content. Then, create a third entity File which holds a one-to-one connection with one of each of the other types, and give it a bunch of methods that simply call the matching methods on the sub entities.
So for example in File, the setName method would look like this:
  public function setName() {
    $this->getFileMetadata()->getName();
  }

And set would look like this:
  public function setName( $name ) {
    $this->getFileMetadata()->setName( $name );
  }

The constructor of the File entity should create a new FileMetadata and a new FileContent on creation and should NOT have a setFilemetadata or setFilecontent method; these two entities should be completely shielded from your application.
Now you have the File entity, which handles exactly like you want (a single entity, no additional sub-entities) which is still stored neatly in two (well, three really) different tables.

A: Do you have the ability to alter the schema of your database? If so, I'd consider consolidating this into one table.
Barring that, you may want to try a one-to-one relationship in Doctrine. Perhaps something like:
class File {
    private $id;
    private $name;
    private $mime;
    private $content;
}

class Content {
    private $id;
    private $data;
    private $fileId;
}

If you map Content->fileId with a one-to-one relationship to File->id, then you can do things like:
$file->getContent()->getData();
$file->getContent()->setData("something different");

Here's some more info on one-to-one mappings: http://docs.doctrine-project.org/en/2.0.x/reference/association-mapping.html#one-to-one-unidirectional

A: You could map both tables, resulting in File and FileContent, and add a one-to-one relationship between the two.
Then add getter/setter methods for the file content in the File class. In these you'd have to call the corresponding methods in FileContent.


text:
Q: ReCaptcha 2.0 With AJAX I have managed to get ReCaptcha 2.0 working in my website. However, it's only working when I don't use AJAX and I let the form submit "naturally".
I want to submit the form with the captcha and alert the user with a success note without refreshing the page.
I tried the following code, but it seems like the server doesn't get the user response:
HTML:
<form class="form" action="javascript:void(0)" novalidate>

        <input type="button" value="Send" class="btn-default right" id="submit">

</form>

JS:
$('#submit').click(function(e) {
    console.log('clicked submit'); // --> works

    var $errors = $('#errors'),
        $status = $('#status'),

        name = $('#name').val().replace(/<|>/g, ""), // prevent xss
        email = $('#email').val().replace(/<|>/g, ""),
        msg = $('#message').val().replace(/<|>/g, "");

    if (name == '' || email == '' || msg == '') {
        valid = false;
        errors = "All fields are required.";
    }

    // pretty sure the problem is here
    console.log('captcha response: ' + grecaptcha.getResponse()); // --> captcha response:

    if (!errors) {
        // hide the errors
        $errors.slideUp();
        // ajax to the php file to send the mail
        $.ajax({
            type: "POST",
            url: "http://orenurbach.com/assets/sendmail.php",
            data: "email=" + email + "&name=" + name + "&msg=" + msg + "&g-recaptcha-response=" + grecaptcha.getResponse()
        }).done(function(status) {
            if (status == "ok") {
                // slide down the "ok" message to the user
                $status.text('Thanks! Your message has been sent, and I will contact you soon.');
                $status.slideDown();
                // clear the form fields
                $('#name').val('');
                $('#email').val('');
                $('#message').val('');
            }
        });
    } else {
        $errors.text(errors);
        $errors.slideDown();
    }
});

PHP:
<?php
    // assemble the message from the POST fields

    // getting the captcha
    $captcha = '';
    if (isset($_POST['g-recaptcha-response']))
        $captcha = $_POST['g-recaptcha-response'];
    echo 'captcha: '.$captcha;

    if (!$captcha)
        echo 'The captcha has not been checked.';
    // handling the captcha and checking if it's ok
    $secret = 'MY_SECRET';
    $response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);

    var_dump($response);

    // if the captcha is cleared with google, send the mail and echo ok.
    if ($response['success'] != false) {
        // send the actual mail
        @mail($email_to, $subject, $finalMsg);

        // the echo goes back to the ajax, so the user can know if everything is ok
        echo 'ok';
    } else {
        echo 'not ok';
    }
?>

The result in the PHP page:
captcha: The captcha has not been checked.array(2) { ["success"]=> bool(false) ["error-codes"]=> array(1) { [0]=> string(22) "missing-input-response" } } not ok

Bottom line is, how can I get the input response manually without it automatically going with the rest of the POST data?

A: Ok, this was pretty silly.
I have done a couple of things wrong:

*

*In the PHP file, all the strings had single quotes on them, and that caused problems.

*Throughout the testing, I added multiple printings of things in the PHP file, thus the if (status == "ok") was never working. I did get the emails but did not get any conformation that I did and now I see why.

*When I wanted to check what the PHP file was omitting, I simply went to it's address in the URL and always got an error. Even when the mails were sent. Now I understand that that is not the correct way of checking the logs.

Thanks to @Samurai who helped my figure out things.

Final PHP code:
<?php
    // assemble the message from the POST fields

    // getting the captcha
    $captcha = "";
    if (isset($_POST["g-recaptcha-response"]))
        $captcha = $_POST["g-recaptcha-response"];

    if (!$captcha)
        echo "not ok";
    // handling the captcha and checking if it's ok
    $secret = "MY_SECRET";
    $response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER["REMOTE_ADDR"]), true);

    // if the captcha is cleared with google, send the mail and echo ok.
    if ($response["success"] != false) {
        // send the actual mail
        @mail($email_to, $subject, $finalMsg);

        // the echo goes back to the ajax, so the user can know if everything is ok
        echo "ok";
    } else {
        echo "not ok";
    }
?>


text:
Q: calculating determinant Let M be real vector space of order $2\times3$ matrices with the real entries. Let $T:M\longrightarrow M$ be defined by
$T\Bigg( \begin{pmatrix}
    x_{1} & x_{2} &  x_{3} \\
     x_{4} & x_{5} &  x_{6}\end{pmatrix}\Bigg)$=$\begin{pmatrix}-x_{6}& x_{4}& x_{1}\\
                             x_{3}& x_{5}& x_{2}\end{pmatrix}$
how to calculate the determinant of T?

A: We can write $T = RS$, where $R$ is the map the multiplies the $(1, 1)$ entry by $-1$ and fixes all of the other entries and $S$ is the permutation matrix for the permutation $(16243)$ of six elements.
The matrix representation of $R$ is diagonal with entries $(-1, 1, \ldots 1)$, so $\det R = (-1)(1) \cdots (1) = -1$. The above permutation is even, so $\det S = 1$ and thus
$$\det T = \det(RS) = \det R \det S = (-1)(1) = -1.$$


text:
Q: Where is Grand Admiral Thrawn during the events of Andor in 5 BBY? In my opinion, Thrawn is an under-utilized character. Where is he and what is he doing in 5 BBY?

A: As Valorum mentioned in their comment, the Thrawn novel covers events up to 2 BBY. He was chasing down pirates, smugglers and arms dealers. The book covers most of his exploits leading up to the 3rd season of Rebels where he is the primary antagonist.
While this explains where he was during this time, I believe there is a logical reason as to why he was not involved in the events of Andor, at least as of season 1.
Thrawn (Either Captain or Commander around this time) was part of the Imperial Navy. While his command lead him into dealings on planets, a large amount of his work was done in space commanding ships and later fleets. The events of Andor, specifically in the season finale, seem to involve only the ISB and Imperial Army. This is evident by the large number of Imperial soldiers on Ferrix and by the fact there was no visible blockade around the planet. Since there was no involvement of the Imperial Navy, Thrawn would have not called to assist in any of the events seen in the show.


text:
Q: Help with finding coefficient of $x^k$ in $(x^2 - \frac{1}{x})^{100}$ So $(x^2 - 1/x)^{100}$
Through the binomial formula $(x^2 - 1/x)^{100}$ is:
$$\sum_{j = 0}^{100} C(100,j) (x^{2})^{j} (1/x)^{100-j}$$
$$\sum_{j = 0}^{100} C(100,j) (x^{2})^{j} (-1)^{100-j}(x^{-1})^{100-j}$$
$$\sum_{j = 0}^{100} C(100,j) (x)^{2j} (-1)^{100-j}(x)^{-100+j}$$
$$\sum_{j = 0}^{100} C(100,j) (x)^{3j-100} (-1)^{100-j}$$
Let k = $3j-100$
Then j = $(k+100)/3$
And k should any value between 0 and 100 inclusive such that k is a whole number.
I'm not sure what's wrong in how I proceeded, I know the correct answer should be:
$(-1)^{(200-k)/3} C(100,(200-k)/3)$
But I'm not sure where I went wrong

A: $$\frac{200-k}3+\frac{100+k}3=100\implies{100\choose\frac{200-k}3}={100\choose\frac{100+k}3}$$

A: It's the coefficient of $x^{k+100}$ in $(x^3-1)^{100}$. And then it's the coefficient of $x^{(k+100)/3}$ in $(x-1)^{100}$.


text:
Q: Loop in Javascript to display DB Values I am a python developer and new to javascript and ajax . I am creating a pie chart that displays DB values.
$(document).ready(function () {
      google.charts.load('current', { 'packages': ['corechart'] });
      google.charts.setOnLoadCallback(drawChart);
      function drawChart() {
        $.ajax({
            url: '/dashboard/document/',
            type: 'POST',
            dataType: 'json',
            data:{
              csrfmiddlewaretoken: '{{ csrf_token }}'
            },
            success: function (response) {
                console.log(response.result);
                $.each(response.result, function (item) {
                  console.log(item);

I have fetched my DB values using pymongo and it is stored in console.log(response.result);Now i need to print in console.log(item); using looping . How to use ?

A:
i need to print in console.log(item); using looping . How to use ?

You can probably skip the jQuery if you are new to JS. (the language has come a long way and doesn't really need it often anymore : )
const exampleArray = ['one', 'two', 'three'];

exampleArray.forEach( function(thing) {
    console.log('thing: ', thing);
});

https://jsfiddle.net/sheriffderek/h2fcb54g/


text:
Q: How to get the selected checkbox value from the row? I want to get the selected the check box row text values from the row.I'm using jstl tags to display the list of records in page.Please see my code below...
<c:forEach items="${list}" var="product">
<input type="text" value='${product.featurename}' name="featurename" readonly="readonly"/>
<input type="text" value='${product.featureversion}' readonly="readonly"/>
<input type="text" value='${product.end_date}' readonly="readonly"/>
<input type="text" value='${product.new_end_date}' class="datepicker" />
<input type="checkbox" value='${product.new_end_date}' name="new_end_date" class="selectedId"/>
</c:forEach>

java class :
String[] newenddate = req.getParameterValues("new_end_date");

Jquery for selectAll
$('#selectall').click(function(i, v){
        $('.selectedId').prop('checked', this.checked);
    });

    var checkCount = $('.selectedId').length;
    $('.selectedId').click(function(i, v){
        $('#selectall').prop('checked',$('.selectedId:checked').length  == checkCount);
    });
});

A: $('.selectedId:checked').each(function(index, value) {
    // gets row inputs
    var $inputs = $(this).closest('tr').find('input[type="text"]');

    // do something here
});

You can change the find's selector as you need.
By the way, you missed a 	 on the last column cell.


text:
Q: How to validate user input against string elements that have been randomly generated in an ArrayList? I'm fairly new to java and am experimenting building my own text based game, at the moment im just trying to work on individual concepts and then hopefully be able to pull it all together in a final project, my problem i have come across at the moment and cant seem to find an answer is exactly what the title question states:
How can i validate user input against a String ArrayList of randomly generated elements?
To clarify, i have a working program at the moment that when run generates a random amount and random types of enemy and then populates them into the dungeon each time the dungeon object is created, the user is then presented with a question allowing them to pick which enemy they should confront first, this is where i require the validation in order that the game would continue, im trying to use a while loop which if the condition returns false would just skip and move on to if statements and their validations, i hope that makes sense and ive posted my code below, apologies in advance if there are many things wrong with my code either syntactically or structurally as stated earlier im still very new to java and at the moment if i can just learn to code then i can worry about how professional or proper something should be.
Here is my code:
package com.davegreen;

import java.util.List;
import java.util.Random;
import java.util.Scanner;

public class Main
{

    public static void main(String[] args)
    {
        // Declaring some variables and creating some objects of other classes that i need.

        Scanner scanner = new Scanner(System.in);
        Dungeon dungeon = new Dungeon();
        List<String> enemyType = dungeon.getEnemy();        // Gets all the enemy from my enemy ArrayList in the Dungeon class.
        int enemyNumberTotal = dungeon.getEnemy().size();   // Gets the amount of enemy in my enemy ArrayList.

        runGame();
        int randomAmountOfEnemy = generateRandomNumber(enemyNumberTotal);   // Generates a random amount of enemy into the dungeon from the total number in the ArrayList.

        System.out.println("\n The enemies in this dungeon are: \n");

        // Generates the random enemies that will populate the dungeon based on a method in my Dungeon class and then passes a random amount of said enemy each time also.

        List<String> randomlyPickedEnemy = dungeon.populateWithRandomEnemy(enemyType, randomAmountOfEnemy);

        System.out.println("\n\t * " + randomlyPickedEnemy);

        System.out.println("\n> Which enemy would you like to confront first?");
        String userChoice = scanner.nextLine();

        // I want to validate the user input from line 31 of the code to reflect that if the user has not selected an enemy that was in the randomly populated list
        // then we stay in the while loop and continue asking until of course the user types in a enemy that was in the randomly populated list, at which
        // point we would of course skip the while loop moving onto the if statements validation, it would be nice also to have ignore case somewhere in there.

        while(!userChoice.equals(randomlyPickedEnemy))
        {
            System.out.println("\n\t That enemy does not live in this dungeon!");
            System.out.println("\n> Which enemy would you like to confront first?");
            userChoice = scanner.nextLine();
        }

        // For the validation here i realise of course that just using the variable randomlyPickedEnemy in the sout would more than likely return ALL the enemy that
        // were randomly populated and not specifically the enemy that the user had chosen, so at this point i need a way to be able to access exactly what enemy it was
        // that the user had chosen to battle so that the sout statement makes sense but more importantly so i can then direct the code where it needs to go based on any given
        // particular enemy.

        if(userChoice.equals(randomlyPickedEnemy))
        {
            System.out.println("You have chose to battle " + randomlyPickedEnemy);
        }
    }

    public static void runGame()
    {
        System.out.println("##################################################");
        System.out.println("#####            DUNGEON CRAWLER             #####");
        System.out.println("##################################################");
    }

    // This is my method to generate a random amount of enemy for the total amount of enemy in my ArrayList.

    public static int generateRandomNumber(int howManyEnemies)
    {
        Random random = new Random();
        int rng = random.nextInt(howManyEnemies) + 1;
        System.out.println("\n There are " + rng + " enemies in this dungeon!");
        return rng;

    }
}

A: You are actually comparing a String to a List (randomlyPickedEnemy).
If I understand correctly, you want to know if this list contains the input of the user.
To do this you just have to modify your whilestatement :
while(!randomlyPickedEnemy.contains(userChoice)) {
    ...
}


text:
Q: No newline before section, preserve header info I am trying to achieve the same as this post:
Remove newline *before* \section
But the problem is that with the suggested solution the section information cannot be used in the header. Is there any way that I can remove the newline before a subsection and at the same time keep the section information for the header? I need a running header with the first and last section and subsection information.
Basically I'm trying to achieve a combination of this:
No newline before section, preserve header info
And this:
Chapters and verses of current page in header

A: I think you want something like this, the key is to use \markright (or \markboth or one of the other mark commands) to leave a mark on the page, the page heading can then pick up the first and last mark on the page and use accordingly.  In the standard classes \section uses \markright (with chapter level marks using the left mark) so I did the same here, defining a simple \section that uses a counter and leaves a mark but no optional handling or star form, and very little heading formatting

\documentclass{report}

\usepackage[paperheight=8cm,paperwidth=7cm, margin=2cm]{geometry}

\pagestyle{headings}

\renewcommand\section[1]{%
\refstepcounter{section}%
\textsection\thesection\markright{#1}~\textit{#1} %
}

\begin{document}

%\chapter{zzz} omit this as page heading is open on chapter start pages by default
\refstepcounter{chapter}

\section{Start} something about the beginning \section{This} and a bit more
\section{That} A longer section about something that has more than one paragraph.

It seems a bit odd to have a paragraph more distinguished than a section heading, so perhaps that is not needed. \section{Then} and sections will always be inline.

\section{Later} or at the start of a paragraph.

\section{Second Start} something about the beginning \section{Second This} and a bit more
\section{Second That} A longer section about something that has more than one paragraph.

It seems a bit odd to have a paragraph more distinguished than a section heading, so perhaps that is not needed. \section{Second Then} and sections will always be inline.

\section{Second Later} or at the start of a paragraph.

\section{Third} Is surprisingly different to the first two.
\end{document}


text:
Q: Getting string between two given characters
quote
I have input something like !Hello world! - 123 123 - and I need to get it into struct { char *string; int a; int b;}  Can you help me?

typedef struct {
    int a;
    int b;
    char *string;
} Smth;
//-----------(size=(already known size of input))
Smth *smth = (*Smth)malloc(sizeof(smth));
smth.string = (char*)malloc(sizeof(char) * size);
sscanf(input, "!%[^!]! - %d %d - ", smth.string, &smth.a, &smth.b); // doesn't work for me

A: before you edit your question
the call

sscanf("!%[^!]! - %d %d - ",string,&a,&b);

is not the one you want, you missed to give the string to parse as the first argument, so the string to parse is the format you wanted to use and the used format is the perhaps not initialized value of string
You wanted :
#include <stdio.h>

int main()
{
  char string[32];
  int a,b;
  const char * i = "!Hello world! - 123 123 -";

  if (sscanf(i, "!%31[^!]! - %d %d - ", string,&a,&b) == 3)
    printf("'%s' %d %d\n", string, a, b);
  else
    put("error");

  return 0;
}

does the work :
pi@raspberrypi:/tmp $ gcc -Wall f.c
pi@raspberrypi:/tmp $ ./a.out
'Hello world' 123 123
pi@raspberrypi:/tmp $

Notice I added in your original format a max length for the read string to not take the risk to write out of string and then to have an undefined behavior. If you do not want to manage yourself the array for string you can use the option %m but is not always available.

A: You are lacking the input string for sscanf. See example below.
#include <stdio.h>
#include <stdlib.h>

typedef struct
{
   int a;
   int b;
   char *string;
} Smth;

int main(void)
{
   Smth smth;
   sscanf(
      "!Hello world! - 123 123 -",
      "!%m[^!]! - %i %i -",
      &smth.string,
      &smth.a,
      &smth.b);
   printf("Str: `%s' a:%d b:%d\n", smth.string, smth.a, smth.b);
   free(smth.string);
   return 0;
}

UPDATE: Given your change in question
#include <stdio.h>
#include <stdlib.h>

typedef struct
{
   int a;
   int b;
   char* string;
} Smth;

int main(void)
{
   size_t size  = 30u;
   char input[] = "!Hello world! - 123 123 -";

   Smth* smth   = (Smth*) malloc(sizeof(Smth));
   smth->string = (char*) malloc(sizeof(char) * size);
   sscanf(input, "!%29[^!]! - %d %d - ", smth->string, &smth->a, &smth->b);

   printf("Str: %s a:%d b:%d\n", smth->string, smth->a, smth->b);

   free(smth->string);
   free(smth);

   return 0;
}


text:
Q: Sequence of critical points converging to $0$ I would like an example of a function with the following properties,

A differentiable function $f:\mathbb{R}\to\mathbb{R}$ such that $0$ is the limit of a sequence of critical points of $f$, and $f'(0)>0$.

The examples I was able to think of, always fail to be differentiable at $0$, would anyone have any idea of an example?
I believe that the function must oscillate infinitely times close to $0$ so that it is possible to create the sequence of critical points, so I am finding it difficult to think of a function that is differentiable at zero, because in its neighborhood, the function is strange.
$c$ is a critical point if $f'(c)=0$

A: $$
f(x) = \begin{cases}
x+x^2\sin \frac{1}{x},\qquad & x \ne 0,
\\
0,\qquad & x = 0
\end{cases}
$$

addd
The derivative exists at zero.
$$
f'(0) = \lim_{x \to 0}\frac{f(x)}{x} = \lim_{x \to 0} 1+ x \sin\frac{1}{x} = 1 .
$$
But the derivative is not continuous at zero.


text:
Q: How can I activate "if" condition on onclick event I seem not to be able to figure out why my "if" part of the function is not working on onclick event. I am trying to make a function to execute on onclick in HTML, it executes it but I always get "undefined" as a result...
My HTML is:
<button type="button" id="n1" class="btn btn-secondary btn-decor" onclick="pressNumber()">1</button>
                <button type="button" id="n2" class="btn btn-secondary btn-decor" onclick="pressNumber()">2</button>

and Javascript

var displayedValue = document.getElementById("calc-disp").textContent;

var fullNumber;

function pressNumber () {
    if (document.getElementById("n1")) {
        var fullNumber = displayedValue + numbers[1];
    }
    else if (document.getElementById("n2")) {
        var fullNumber = displayedValue + numbers[2];
    }
    displayValueNow();
}

// display result

function displayValueNow () {
    document.getElementById("calc-disp").innerHTML = fullNumber;
}```

thanks for any advice

A: Instead of using an if statement simply pass in the button number as an argument to the function and use that in your calculation.

const numbers = [0, 1, 2];

// Cache only the element
const displayedValue = document.getElementById('calc-disp');

function displayValueNow(fullNumber) {
  displayedValue.textContent = fullNumber;
}

function pressNumber(n) {

  // Make sure you coerce your displayed value (a string) to
  // an integer before trying to add it to the number in the array
  var fullNumber = Number(displayedValue.textContent) + numbers[n];

  // Pass in `fullNumber` as an argument to `displayValueNow`
  // so you're not using a global variable
  displayValueNow(fullNumber);
}
<button type="button" onclick="pressNumber(1)">1</button>
<button type="button" onclick="pressNumber(2)">2</button>

A: You were close, the if condition didn't work because your statement checked IF the element exists, not whether it was clicked on. To do that, pass a param to your pressNumber function from your html (here I pass the button, you could pass the id directly or the value of the number).

// declare your numbers array
var numbers = [1, 2]

// +so that it's a number not a string (try removing it)
var fullNumber = +document.getElementById("calc-disp").textContent;

// removed, we should only operate on the fullNumber variable
// var displayedValue = document.getElementById("calc-disp").textContent;

function pressNumber(button) {
// in an if, document.getElementById("n1") just checks if the element exists - since it always exists, the else branch will never be executed
  if (button.id === "n1") {
  // remove the var so it changes the outer fullNumber
    fullNumber = fullNumber + numbers[0];

  } else if (button.id === "n2") {
    fullNumber = fullNumber + numbers[1];
  }
  displayValueNow();
}

// display result

function displayValueNow() {
  document.getElementById("calc-disp").innerHTML = fullNumber;
}
<button type="button" id="n1" class="btn btn-secondary btn-decor" onclick="pressNumber(this)">1</button>
<button type="button" id="n2" class="btn btn-secondary btn-decor" onclick="pressNumber(this)">2</button>

0


text:
Q: Getting time of day from user for silly simple app I am begginer in Python and I wanted to try to make myslef a simple piece of code that would take my input of time when I came to work and tell me when I get to go home.
Problem is the input formatting and then adding those 8 hours of work into it and having an output.
I can make it work with integers but that is not good enough. I would like to see HH:MM format in I/O
I searched all around the web but what I found are mostly articles and advice about time in general (date and more importantly, the datetime.now) whereas I need it to understand I want to input time when I came to work and time when I get to leave the work, regardless of day and so on.
# When do I get to go home program
# first we need ot define a variable to use it to store the time when I came
# to work
# That is atw (arrived to work)
# gh is "go home"

from datetime import time
atw = input ("When I came to work in format of HH:MM \n")
#atw = datetime.strptime(input('enter time you arrived to work in HHMM format: '), "%H%M")
h,m = map (int, time.split(":"))
#gh = atw (hour = h, minute = m)
print (("I came to work @", atw ,"%H%M"))

gh = atw + 0800
print ("You can go home @ ", gh)

All sort of error messages, from syntax to problems with format of my input and adding of those 8 hours of work to the final number (gh variable)
Is there some awesome being that could walk me trough how do I actually make python to understand that I am adding time to variable that should be formatted as time (HH:MM) input which is coming form user?

A: Ok, let's do this step by step, because as you said, there All sort of error messages, from syntax to...
from datetime import time
atw = input ("When I came to work in format of HH:MM \n")

These first two lines work without problem, that's fine.
h,m = map (int, time.split(":"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'datetime.time' has no attribute 'split'

Oh, an error, let's read what the error message says: type object 'datetime.time' has no attribute 'split'. Well, that's correct, because we don't want to split time, but the time that we gave to input and that has the name atw, so let's use that:
h,m = map (int, atw.split(":"))
print (("I came to work @", atw ,"%H%M"))

No error, but a weird output:

('I came to work @', '08:17', '%H%M')

You probably didn't want a tuple as output (the parentheses) and wanted to format that output, as I can see from the format string "%H%M". Fortunately python (>=3.6) has a nice solution for that called f-strings:
print (f"I came to work @{atw}")

Hmmm, wait, what about the formatting, that just outputs what we inputed... So make use of h and m:
print (f"I came to work @{h:02d}:{m:02d}")

Do a google search what that :02d means and what other options there are ;)
Next line:
gh = atw + 0800
  File "<stdin>", line 1
    gh = atw + 0800
                  ^
SyntaxError: invalid token

Hmmm, you want to add 8 hours to get the endtime, but all you get is an syntax error... That's because 0800 is no valid python construct, you probably ment just 8? Let's try this...
gh = atw + 8
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

Another error, but why? You are using atw, which is a string, albeit you already split that in two ints h and m, with h representing the hours:
gh = h + 8
print ("You can go home @ ", gh)

Ahh, damn that print again. Look above and use f-strings:
print (f"You can go home @{gh}:{m}")

And now try to see if you get a solution using strptime as @mkrieger1 suggested in the comments.
And pleeeeease do a python tutorial :)


text:
Q: Load a process into RAM, but don't execute? Is there a way to load a process into RAM, but somehow tell the scheduler not to execute it? The aim being to have the system read the binary from disk, allocate the pages in RAM for the code, but not to immediately jump into the code to start executing it. The intention to be to start it at some later time.
The below approximates to this, but allows some amount of execution before the signal is delivered to pause the process:
$ /path/to/program &; kill -STOP $!

I assume there's some part of code execution that involves pulling in libraries and other "setup" before the first line of my actual program is executed. I don't mind if these steps are run or not. We can assume I have root and can make any changes to the system to support this task.
Having played with gdb, I assume this could do what I ask in some way. This would suffice, but ideally I'd have a way to do this without needing to have anything running alongside my process.
In response to comments, I suspect the load-when-needed issue would indeed frustrate this plan. I was hoping to load the code into RAM, modify the file, and then let the process execute. The code in RAM is now different to the code on disk. If the process's first job was to hash the file, it would now get the "wrong" hash, even though it's running the "correct" code.

A: This probably won't achieve what you're really after (as explained in the comments, binaries are loaded as needed), but it will stop a process as soon as it starts, and have it wait for a SIGCONT.
Place the following in a file, say stop.c:
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>

__attribute__ ((constructor)) void stoponstart() {
  kill(getpid(), SIGSTOP);
}

Build it as a shared library:
gcc stop.c -o stop.so -fPIC -shared

Then preload it whenever you want to "start and pause" a program:
LD_PRELOAD=/path/to/stop.so foo

When run from a shell, this will actually put the process in the background, and you can then really start it with fg.


text:
Q: Tortoisesvn seems stuck in non-recursive mode Just set up a new machine, running windows 10, and installed TortoiseSVN 1.9.4, Build 27285 - 64 Bit
Did plenty of reboots, needed the first one for the icons to appear. However it seems to be stuck in non-recursive mode. The icons are all there, working correctly, but when I click on a parent folder, it says there's nothing to commit. If I drill down to the child-most folder, and try to commit, it seems to figure out what files to commit. It's just a pain in the butt to have to drill down to every folder just to get the committing working, seems broken to me, or is there some setting for this?

A: Found my problem. One of the subdirectories, had an old svn repo in it. Had to do a clean-up, but also had to select break locks. Seems to have fixed the problem.


text:
Q: Kaggle Titanic with tflearn neural network I have solved the Titanic problem with logistic regression, now I want solve the problem with neural network. But my model always return 1, that means survived. for every test input. Maybe there is a problem in my model. How could I solve this?
train_data = pd.read_csv('data/train.csv')
test_data = pd.read_csv('data/test.csv')

#Some data cleaning process
#......

X_train = train_data.drop("Survived",axis=1).as_matrix()
Y_train = train_data["Survived"].as_matrix().reshape((891,1))
X_test  = test_data.drop("PassengerId",axis=1).as_matrix()

net = tflearn.input_data(shape=[None, 6])
net = tflearn.fully_connected(net, 32)
net = tflearn.fully_connected(net, 32)
net = tflearn.fully_connected(net, 1, activation='softmax')
net = tflearn.regression(net)
model = tflearn.DNN(net)
model.fit(X_train, Y_train, n_epoch=10, batch_size=16, show_metric=True)

pred = model.predict(X_test)
print pred

A: Using softmax as an activation layer in the output ensures that the sum of the outputs across all nodes in that layer is 1. Since you only have a single node, and the output has to sum to 1, it will always output 1 by definition.
You should never use softmax as your activation for a binary classification task. A better option is the logistic function, which I think tensorflow calls sigmoid.
So instead of
net = tflearn.fully_connected(net, 1, activation='softmax')

try
net = tflearn.fully_connected(net, 1, activation='sigmoid')

A: Your problem is a binary classification problem ie there are 2 possible outcomes. 0 or 1 . In the context of Titanic Problem Not Survived or Survived.
The output layer of the neural net should produce an output less than or equal to 1 or greater than or equal to 0. No other values will make sense in the context of binary classification.
Normally a cutoff is placed like 0.50. If the predicted output of the net is greater than that cutoff, it is regarded as 1 else 0.
In order for things to work like this as said before the net should produce an output in the range [0, 1]. For this the activation function of the layer ie output layer must be sigmoid. It produces output in the range [0, 1]. To know more about sigmoid and other activation functions I recommend you to follow this link.
In your code you can do it like this.
net = tflearn.fully_connected(net, 1, activation='sigmoid')


text:
Q: Using SQL Fiddle to share SQL Server I'd like to share my SQL Server code via SQL Fiddle. But I can't seem to get my schema created. I can get MySQL tables created no problem, but something won't cooperate when I switch to the SQL Server setting. I've looked across the internet for almost an hour now. can someone steer me straight?
Here's a table I'm trying to make for example:
create table employee
(
    empnum char(3) primary key,
    empname varchar(15),
    empphone char(4)
)
GO

insert into employee values('123', 'andrew', '1234')
insert into employee values('124', 'andy', '1221')
insert into employee values('125', 'andre', '1344')
GO

I keep getting:

Create script error

Thank you.

A: I see this is an old post, but had the same issue with the example code above in both MySQL and SQL Server.  However, I was able to get the following to run successfully:
create table employee
(
    empnum char(3) primary key,
    empname varchar(15),
    empphone char(4)
);

insert into employee values('123', 'andrew', '1234');
insert into employee values('124', 'andy', '1221');
insert into employee values('125', 'andre', '1344');

Hope this saves someone else a little time.
http://sqlfiddle.com/#!6/5649a

A: Thanks for your answers that SQL Fiddle is currently having issues with MS SQL Server code. I'm think I'm going to share it via dropbox link instead. Making temporary table son stack exchange sort of works, but I'm gonna have to ctrl + h every single instance of a table name...
crappy. I wish I hadn't spent an hour struggling on this. Thank you for all your help.


text:
Q: change to a php variable in blade laravel doesn't persist When I increment currentIndex whenever I click the next button, the value of currentIndex returns to its default value which is 1 here. So the update of currentIndex doesn't persist. Does anyone have any idea why? And how can I solve this problem?
    let inputBoxNum = 3
    let currentIndex
    {{ $currentIndex = 1 }}
    updateButtons()
    $('.back-btn, .next-btn').on('click', function (e) {
        console.log({{$currentIndex}}) // returns 1 even if this function was called before
        let btnClicked = e.target.className.includes('next-btn') ? 'next' : 'back'
        if (btnClicked === 'next') {
            {{$currentIndex += 1}} // it increments to 2
            console.log({{$currentIndex}}) // returns 2
            $('#create-input-box').html(`@include('reservations.create-input-box-'.$currentIndex)`)
        } else {
            $('#create-input-box').html(`@include('reservations.create-input-box-'.$currentIndex)`)
        }
        updateButtons()
    })
    function updateButtons() {
        getCurrentIndex()
        if (currentIndex <= 1) {
            $('.back-btn').hide()
            $('.next-btn').show()
        } else if (currentIndex > 1 && currentIndex < inputBoxNum) {
            $('.back-btn').show()
            $('.next-btn').show()
        } else {
            $('.back-btn').show()
            $('.next-btn').hide()
        }
    }

    function getCurrentIndex() {
        currentIndex = parseInt($('#create-input-box')[0].children[0].className.split("-")[3])
    }


text:
Q: Windows 8.1 store app https local server using Windows.Networking.Sockets.StreamSocket I'm working on a Windows8.1 Store app using JavaScript.
As per the requirement we are serving the html files with the help of a http local server which uses Windows.Networking.Sockets.StreamSocket.Listener.
Here is the example of the http server I'm using and its working fine for http requests.
If I change the source to https the local server receives request, but the InputStream will be encrypted.
Is there way to decrypt and get the InputStream? May be by using any SSL certificates.
The problem is x-ms-webview in windows 8.1 app require https source to perform script notification i.e MSWebViewScriptNotify event.
As we are not using any external website to make it https, how to make this local server to accept https requests and serve the files.


text:
Q: JavaScript detect if hardware acceleration is enabled Is it possible to detect to see if a browser has support for hardware accelerated page rendering and is it also possible to see if it has been enabled? I am aware that Firefox 4, IE9 and Chrome support it, but it may or may not be enabled due to the version of the browser, the OS, and the computer hardware itself.
Is this possible using some form of DOM sniffing?

A: Like all other browser-specific capabilities, probably the best thing you can do is to devise some sort of feature test and actually measure the performance of what matters to you.
You can do when the first page on your site is loaded and then set a cookie with the setting so you only have to do it every once-in-a-while and don't have to do it again for awhile as long as the cookie is present.
Depending upon what type of performance you care the most about, you can devise a test that's pretty specific to that.  For example if you cared a lot about image scaling, you could devise a JS test that scales an image among a bunch of different sizes in a big enough loop to get a measurable time and then decide what your timing threshold is.
Not only would this be better than a single binary choice of accelaration on or off, but it would also be able to test the specific features you care about and be able to see how fast they actually are.

A: I recently discovered a handy command-line switch for Chrome (I am using v. 16.0.912) that results in red borders being painted around HTML (CSS3) elements that are actually being hardware accelerated. You can read more details in a blog that I have published on this subject.


text:
Q: Why slider handle can not be moved? I am trying to test slider but the slider handle can not move. Could you please help me this. I have attached a Fiddle for the reference.
My JS:
var current_plan = {};
var plans = [
  {
    'name' : 'Business',
    'ram' : '1024 MB',
    'disk' : '25 GB',
    'bandwidth' : 'Unlimited',
    'cores' : 4,
    'price' : {
      'uk' : 7.5,
      'us' : 12
    },
    'comment' : 'Ideal for simple websites, secondary nameservers & small test environments.'
  },
  {
    'name' : 'Power',
    'ram' : '2048 MB',
    'disk' : '50 GB',
    'bandwidth' : 'Unlimited',
    'cores' : 4,
    'price' : {
      'uk' : 15,
      'us' : 24
    },
    'comment' : 'Ideal for wordpress, drupal & other CMS, forums and medium sized web shops.'
  },
  {
    'name' : 'High-Traffic',
    'ram' : '4096 MB',
    'disk' : '100 GB',
    'bandwidth' : 'Unlimited',
    'cores' : 4,
    'price' : {
      'uk' : 30,
      'us' : 48
    },
    'comment' : 'Ideal for cPanel and other hosting controlpanels as well as busy sites and forums.'
  },
  {
    'name' : 'Power',
    'ram' : '8192 MB',
    'disk' : '200 GB',
    'bandwidth' : 'Unlimited',
    'cores' : 4,
    'price' : {
      'uk' : 60,
      'us' : 96
    },
    'comment' : 'Ideal for complex web apps, multiple busy sites, forums or web shops.'
  },
  {
    'name' : 'High-Traffic',
    'ram' : '16384 MB',
    'disk' : '400 GB',
    'bandwidth' : 'Unlimited',
    'cores' : 4,
    'price' : {
      'uk' : 120,
      'us' : 192
    },
    'comment' : 'Ideal for complex web apps, multiple busy sites, forums or web shops.'
  }
];
function calc_price() {
    var os_price = {
    'uk': {
        os: {
            windows: 5,
            cpanel: 7.5,
            ubuntu: 0,
            centos: 0
            },
        },
    'us': {
        os: {
            windows: 7.5,
            cpanel: 10,
            ubuntu: 0,
            centos: 0
            },
        }
    };

    var total_price = current_plan.price[country_code] + os_price[country_code].os[$("input[name=os_template]:checked").val()];
    $('.price-val').text(total_price.toFixed(2));
    var signUpUrl = ["https://control.vps.net/cart/ssd-vps"];
    signUpUrl.push(parseInt(current_plan.ram, 10));
    signUpUrl.push($("input[name=locations_template]:checked").val());
    signUpUrl.push($("input[name=os_template]:checked").val());
    signUpUrl.push("ssdvps-" + Math.floor(Math.random()*(99999-10000+1)+10000) + ".vps.net");
    $('#signup-button').attr('href', signUpUrl.join("/")+"/");
};

$(document).ready(function(){
  selected_signup_slices = parseInt($('input[name=preselected-package]').val(), 10);
  assigned_signup_slices = selected_signup_slices > 0 ? selected_signup_slices : 1;
  $('input[name=preselected-package]').val(assigned_signup_slices);
  var hslide_handle = function(e,ui){
      var x = ui.value;
      jQuery(this).find('input').val(x);
      current_plan = plans[x-1];

      $('.ram-field').text(current_plan.ram);
      $('.disk-field').text(current_plan.disk);
      $('.traffic-field').text(current_plan.bandwidth);
      $('.cores-field').text(current_plan.cores);
      $('.type-field').text(current_plan.name);
      $('.os-field').text(current_plan.os);
      $('.node-comment').text(current_plan.comment);

      $('.jsSliderNav span').removeClass('active');
      $('.jsSliderNav span:eq('+(x-1)+')').addClass('active');

      //$('#signup-button2').attr('href',"https://control.uat.vps.net/cloud-hosting-signup/"+current_plan.name.toLowerCase());

     //$('.price-val').text(total_price.toFixed(2));
        calc_price();
     //$('.price-val').text(current_plan.price[country_code].toFixed(2));
    };

  var hostapps_slider = $('#cloud-apps-slider').slider({
    min: 1,
    max: 5,
    animate: true,
    range: "min",
    slide: hslide_handle,
    change: hslide_handle
  });
  hostapps_slider.slider('value',assigned_signup_slices);
  $('.jsSliderNav span').click(function(){
    hostapps_slider.slider('value',$(this).index()+1);
  });
   $('.currency').html(currency_code);
    $("input[name=os_template]").on("change", calc_price);
    $("input[name=locations_template]").on("change", calc_price);
    calc_price();
});

My HTML:

                                        VPS1GB
                                        VPS2GB
                                        VPS4GB
                                        VPS8GB
                                        VPS16GB

                            RAM: 2 GB

                            DISK SPACE: 50 GB

                            BANDWIDTH: Unlimited

                            CORES: 4

Many thanks!

A: Abdel is correct, your original code throws an error. You can access the error by opening up the javascript console in your browser (for chrome it's at options -> more tools -> javascript console). If you define country_code by inserting var country_code = 'uk'; on line 84 the slider works fine.