text:
Q: TWO ISP internet connections on CENTOS6. Can't ping on client I have two internet connections, from two different ISPs and I need failover host for my local network between the two ISPs. I am using CentOS6.
eth0 – ISP 1
eth1 – ISP 2
eth2 – local network interface
Configs:
eth0
DEVICE=eth0
TYPE=Ethernet
ONBOOT=yes
NM_CONTROLLED=no
BOOTPROTO=none
HWADDR=00:15:5D:AA:AD:A6
IPADDR=12.12.12.226
DNS1=202.119.32.5
DNS2=202.119.32.9
NAME="System eth0"
NETMASK=255.255.255.248
USERCTL=no

eth1
DEVICE=eth1
TYPE=Ethernet
ONBOOT=yes
NM_CONTROLLED=no
BOOTPROTO=none
HWADDR=00:15:5D:AA:AD:A7
IPADDR=11.11.11.115
DNS1=198.169.104.130
NAME="System eth1"
NETMASK=255.255.255.240
USERCTL=no

eth2
DEVICE=eth2
TYPE=Ethernet
ONBOOT=yes
NM_CONTROLLED=no
BOOTPROTO=none
HWADDR=00:15:5D:AA:AD:A8
IPADDR=192.168.110.181
NAME="System eth2"
NETMASK=255.255.255.0
USERCTL=no

route-eth0
12.12.12.224/29 dev eth0 table vega
###
12.12.12.224/29 dev eth0 src 12.12.12.226
###
12.12.12.224/29 dev eth0 src 12.12.12.226 table kyivstar
default via 12.12.12.225 table kyivstar

route-eth1. scope of two ISP in it interface route.
11.11.11.112/28 dev eth1 table kyivstar
###
11.11.11.112/28 dev eth1 src 11.11.11.115
###
11.11.11.112/28 dev eth1 src 11.11.11.115 table vega
default via 11.11.11.113 table vega
#need, because after network servicerestart, default scope are fallen
default scope global nexthop via 12.12.12.225 dev eth0 weight 4 nexthop via 11.11.11.113 dev eth1 weight 1

route-eth2 (local network):
192.168.110.0/24 dev eth2 table kyivstar
192.168.110.0/24 dev eth2 table vega

rule-eth0:
from 12.12.12.226 lookup kyivstar

rule-eth1:
from 11.11.11.115 lookup vega

My rt_tables:
#
# reserved values
#
255     local
254     main
253     default
0       unspec
#
# local
#
#1      inr.ruhep

1       kyivstar
2       vega

Next, my iptables script:
#!/bin/bash

IPTABLES="/sbin/iptables"

$IPTABLES -F
$IPTABLES -t nat -F
$IPTABLES -t mangle -F

$IPTABLES -X
$IPTABLES -t nat -X
$IPTABLES -t mangle -X

/sbin/modprobe ip_tables
/sbin/modprobe ip_conntrack
/sbin/modprobe iptable_filter
/sbin/modprobe iptable_mangle
/sbin/modprobe iptable_nat
/sbin/modprobe ipt_LOG
/sbin/modprobe ipt_limit
/sbin/modprobe ipt_state
/sbin/modprobe ipt_owner
/sbin/modprobe ipt_REJECT
/sbin/modprobe ipt_MASQUERADE
/sbin/modprobe ip_conntrack_ftp
/sbin/modprobe ip_conntrack_irc
/sbin/modprobe ip_nat_ftp
/sbin/modprobe ip_nat_irc
/sbin/modprobe ip_gre
/sbin/modprobe ip_nat_pptp

$IPTABLES -A FORWARD -i eth2 -j ACCEPT
$IPTABLES -t nat -A POSTROUTING -o eth0 -j MASQUERADE
$IPTABLES -t nat -A POSTROUTING -o eth1 -j MASQUERADE

Finally my failover script:
#!/bin/bash

# Conventionally 0 indicates success in this script.

# Time between checks in seconds
SLEEPTIME=10

#IP Address or domain name to ping. The script relies on the domain being
#pingable and always available
TESTIP=8.8.8.8

#Ping timeout in seconds
TIMEOUT=2

# External interfaces
EXTIF1=eth0
EXTIF2=eth1

#IP address of external interfaces. This is not the gateway address.
IP1=`ifconfig $EXTIF1 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'`
IP2=`ifconfig $EXTIF2 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'`

#Gateway IP addresses. This is the first (hop) gateway, could be your router IP
#address if it has been configured as the gateway
GW1=`sipcalc $EXTIF1 | grep -w 'Usable range' | awk '{ print $4 }'`
GW2=`sipcalc $EXTIF2 | grep -w 'Usable range' | awk '{ print $4 }'`

# Relative weights of routes. Keep this to a low integer value. I am using 4
# for TATA connection because it is 4 times faster
W1=4
W2=1

# Broadband providers name; use your own names here.
NAME1=kyivstar
NAME2=vega

#No of repeats of success or failure before changing status of connection
SUCCESSREPEATCOUNT=4
FAILUREREPEATCOUNT=1

# Do not change anything below this line

# Last link status indicates the macro status of the link we determined. This is down initially to force routing change upfront. Don't change these values.
LLS1=1
LLS2=1

# Last ping status. Don't change these values.
LPS1=1
LPS2=1

# Current ping status. Don't change these values.
CPS1=1
CPS2=1

# Change link status indicates that the link needs to be changed. Don't change these values.

CLS1=1
CLS2=1

# Count of repeated up status or down status. Don't change these values.
COUNT1=0
COUNT2=0

# Log file
CHECKGATEWAYLOG=/termolife/gwping_status

while : ; do
        ping -W $TIMEOUT -I $IP1 -c 1 $TESTIP > /dev/null  2>&1
        RETVAL=$?

        if [ $RETVAL -ne 0 ]; then
                echo $(date) "______" $NAME1 Down >> $CHECKGATEWAYLOG
                CPS1=1
        else
                CPS1=0
        fi

        if [ $LPS1 -ne $CPS1 ]; then
                echo $(date) "______" Ping status changed for $NAME1 from $LPS1 to $CPS1 >> $CHECKGATEWAYLOG
                COUNT1=1
        else
                if [ $LPS1 -ne $LLS1 ]; then
                        COUNT1=`expr $COUNT1 + 1`
                fi
        fi

        if [[ $COUNT1 -ge $SUCCESSREPEATCOUNT || ($LLS1 -eq 0 && $COUNT1 -ge $FAILUREREPEATCOUNT) ]]; then
                echo $(date) "______" Uptime status will be changed for $NAME1 from $LLS1 >> $CHECKGATEWAYLOG
                CLS1=0
                COUNT1=0
                if [ $LLS1 -eq 1 ]; then
                        LLS1=0
                else
                        LLS1=1
                fi
        else
                CLS1=1
        fi

        LPS1=$CPS1

        ping -W $TIMEOUT -I $IP2 -c 1 $TESTIP > /dev/null  2>&1
        RETVAL=$?

        if [ $RETVAL -ne 0 ]; then
                echo $(date) "______" $NAME2 Down >> $CHECKGATEWAYLOG
                CPS2=1
        else
                CPS2=0
        fi

        if [ $LPS2 -ne $CPS2 ]; then
                echo $(date) "______" Ping status changed for $NAME2 from $LPS2 to $CPS2 >> $CHECKGATEWAYLOG
                COUNT2=1
        else
                if [ $LPS2 -ne $LLS2 ]; then
                        COUNT2=`expr $COUNT2 + 1`
                fi
        fi

        if [[ $COUNT2 -ge $SUCCESSREPEATCOUNT || ($LLS2 -eq 0 && $COUNT2 -ge $FAILUREREPEATCOUNT) ]]; then
                echo $(date) "______" Uptime status will be changed for $NAME2 from $LLS2 >> $CHECKGATEWAYLOG
                CLS2=0
                COUNT2=0
                if [ $LLS2 -eq 1 ]; then
                        LLS2=0
                else
                        LLS2=1
                fi
        else
                CLS2=1
        fi

        LPS2=$CPS2

        if [[ $CLS1 -eq 0 || $CLS2 -eq 0 ]]; then
                if [[ $LLS1 -eq 1 && $LLS2 -eq 0 ]]; then
                       ip route flush cache
                        echo $(date) "______" Switching to $NAME2 >> $CHECKGATEWAYLOG
                        ip route replace default scope global via $GW2 dev $EXTIF2
                        ip route show | awk '{print}' | grep 'eth0\|eth1' >> $CHECKGATEWAYLOG
                elif [[ $LLS1 -eq 0 && $LLS2 -eq 1 ]]; then
                       ip route flush cache
                        echo $(date) "______" Switching to $NAME1 >> $CHECKGATEWAYLOG
                        ip route replace default scope global via $GW1 dev $EXTIF1
                        ip route show | awk '{print}' | grep 'eth0\|eth1' >> $CHECKGATEWAYLOG
                elif [[ $LLS1 -eq 0 && $LLS2 -eq 0 ]]; then
                       ip route flush cache
                        echo $(date) "______" Restoring default load balancing >> $CHECKGATEWAYLOG
                        ip route replace default scope global nexthop via $GW1 dev $EXTIF1 weight $W1 nexthop via $GW2 dev $EXTIF2 weight $W2
                        ip route show | awk '{print}' | grep 'eth0\|eth1' >> $CHECKGATEWAYLOG
                fi
        fi
        sleep $SLEEPTIME
done

All ok, when ISP kyivstar fallen – my default route is changed on ISP vega. But, on client (windows 7), when i check ping (ping gmail.com -t) and turn off ISP kyivstart, i see that packets lost. But, when i check ping on other host (ping facebook.com), i see – all packets are delivered.
When i check "tracert" on windows client, i see that packets go on gateway ISP kyivstar, but not on ISP vega. In table of routing on host(server), i see, that default gateway was changed on ISP vega. And if, i check ping on host (server) – all packets go to gateway ISP vega.
In google, i see, that problem in cache of routing. Ok.
I put in sysctl.conf:
sysctl -w net.ipv4.route.secret_interval=0

But, it can't help me. How to solve this problem ? Thanks for your attention.


text:
Q: How to limit by multiple categories(dynamically taken) in one SQL statement? Here is current SQL:
http://www.copypastecode.com/22205/
It takes 70 new rows from table ads.
But it doesn't take proper amount(for example 5) of rows for each mr.region_id from joined table map_regions.
For example if I will add 50 ads in one region, it will take all 50 of them and leave 20 slots for the rest regions.
Please help me to upgrade current SQL, so it would take 5 rows from table ads for each mr.region_id in map_regions table.

A: Try
SELECT a.id,a.country,a.region,a.rajons,a.town AS town_id,a.pagasts,i.t0_1, mt.town, mp.pagasts, c.link
FROM ads a
INNER JOIN categories c ON a.category = c.cat_id
RIGHT JOIN images i ON a.id = i.ad_id
LEFT JOIN (select * from map_regions where region_id = a.region LIMIT 5) as mr
LEFT JOIN map_towns mt ON a.town = mt.town_id
LEFT JOIN map_pagasts mp ON a.pagasts = mp.pagasts_id
WHERE a.expire >= ' . $current->get() . '
ORDER by a.id DESC
LIMIT 70

redpajama_set_name: RedPajamaStackExchange


text:
Q: JavaFX lib can not be build any more since JavaFX 17 I have a JavaFX lib which I use for my projects. When I set the maven dependencies to JavaFX 16 the lib can be build via "clean install" without any errors.
When I switch the maven dependency to 17 I get several error like:
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] C:\kisters\workspaces\2021-09-workspace\water-widgets.ui.javafx.lib\src\main\java\de\kisters\ui\water\widgets\propertysheet\editor\PSButton.java:[4,27] error: package javafx.scene.control does not exist
[ERROR] C:\kisters\workspaces\2021-09-workspace\water-widgets.ui.javafx.lib\src\main\java\de\kisters\ui\water\widgets\propertysheet\editor\PSButton.java:[5,26] error: package javafx.scene.layout does not exist
[ERROR] C:\kisters\workspaces\2021-09-workspace\water-widgets.ui.javafx.lib\src\main\java\de\kisters\ui\water\widgets\propertysheet\editor\PSButton.java:[6,26] error: package javafx.scene.layout does not exist
[ERROR] C:\kisters\workspaces\2021-09-workspace\water-widgets.ui.javafx.lib\src\main\java\de\kisters\ui\water\widgets\propertysheet\APropertySheetEditor.java:[5,28] error: package javafx.beans.property does not exist

I searched the net an found this issue openjdk.
It seems that during the compile process empty modules are used. Does anyone know how to solve this for my maven build?


text:
Q: PHP - Using $_POST after a link I have a form with a textbox with name="name".
In my code, I use a direct image hosted on another website in the format:
$grav_url = "http://yourwebsitehere.com/avatarimage.php?username=YourUsername";
I want the YourUsername part to be replaced with the input of the textbox.
For this to work, i'm trying the following code:
$grav_url = "http://yourwebsitehere.com/avatarimage.php?username="+ $_POST['name'];
What am I doing wrong? PHP noob here

A: in php . is used for concatenate string not +
here try this
$grav_url = "http://yourwebsitehere.com/avatarimage.php?username=".$_POST['name'];


text:
Q: Replicating SKAction.playSoundFileNamed() with volume? I've been using playSoundFileNamed() to play a machine-gun type of sound - repeats very quickly and often has the sound overlaps. I'd like to add a volume control to it, and I can't figure out how - Since it requires a variable amount of sound effects playing over each other I have to create the audio player on the spot, and I can't find a way to preload the sound data for it that way, making it lag like crazy. SKAction.playSoundFileNamed() works perfectly, but... it doesn't have a volume option. I haven't been able to figure out a way to replicate it with volume that doesn't lag.

A: Prefered method is to use SKAudioNode to achieve the effects you want,
but to answer the question at hand
let sound = SKAction.playSoundFileNamed("machinegun")
let action = SKAction.changeVolume(by: -1, duration: 1)
let group = SKAction.group([sound,action])

node.run(group)

https://developer.apple.com/documentation/spritekit/skaction/1417664-playsoundfilenamed


text:
Q: How to show multiple customised google maps on a single page? I need to show coordinates of multiple items on separate maps on a single page.
To accomplish this I need to do something similar to the code below. The question is how to pass the list of map names and coordinates to JavaScript?
values I can pass are following three values
    ${location.lat}
    ${location.long}
    ${location.mapName}

JSP
I loop through the list to show the name of each location, I am also trying to set the id of each map different to the other.
<c:forEach var="location" items="${locations}">

${location.name}

</c:forEach>

A: First off all, since Location is a java object you can't have an attribute called long. Also,
 insede the forEach will generate objects with duplicated ids on DOM.
For the test, I created a Location object like this:
public class Location {

    private double lat;
    private double lng;
    private String mapName;

    private String name;

    // getters and setters

}

In a simple way, just iterate over locations to cread the location to the maps, like this:
<c:forEach var="location" items="${locations}">

${location.name}

</c:forEach>

And iterate to generate the map objects, markers and whatever, like this:
<c:forEach var="location" items="${locations}">
    var latLng_${location.mapName} = new gm.LatLng(${location.lat}, ${location.lng});
    var options_${location.mapName} = {
        zoom: 14,
        center: latLng_${location.mapName},
        mapTypeId: gm.MapTypeId.TERRAIN
    };

    var ${location.mapName} = new gm.Map(document.getElementById("${location.mapName}"), options_${location.mapName});

    var marker_${location.mapName} = new gm.Marker({
        title: "${location.name}",
        position: latLng_${location.mapName},
        map: ${location.mapName}
    });
</c:forEach>

You can enclose this in a function if you want to. In a test I generated 4 maps, like in this image:

This is the entire JSP:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>

<c:forEach var="location" items="${locations}">

${location.name}

</c:forEach>

A: The key to achieving what you want is to realize that you need multiple contexts/optionsets declared, one for each map.  My personal approach would be to define an initialization function that takes your values as parameters like so:

<c:forEach var="location" items="${locations}">

${location.name}

</c:forEach>

A: Try this solution :3 ... I hope this help.

<c:forEach var="location" items="${locations}">

${location.name}

</c:forEach>


text:
Q: Random effects and cluster-robust standard errors I have read that when one adopts Random Effects (RE) there is no need to include cluster-robust standard errors because of the structure and functioning of the RE model itself.
Could anyone please elucidate on this - or indicate good references to better understand the rationale?
Thank you so much.


text:
Q: How to effectively concatenate multiple String variables each from the list of objects? I would like to go through a list of objects and concatenate several Strings for each variable:
final StringBuilder xBuilder = new StringBuilder();
final StringBuilder yBuilder = new StringBuilder();
final StringBuilder zBuilder = new StringBuilder();

someObjects.forEach(obj -> {
  A a = obj.getA();
  xBuilder.append(obj.getX() + ",");
  yBuilder.append(obj.getY() + ",");
  zBuilder.append(a.getZ() + ",");
});

Is there any more effective way than creating several StringBuilders for each variable?

A: Well, you do want 3 separate Strings here, so looks just fine to create 3 StringBuilder(s)..  You could alternatively use a StringJoiner though:
StringJoiner xJoiner = new StringJoiner(",");
someObjects.forEach(obj -> {
    xJoiner.join(obj.getX();
});

A:
Is there any more effective way than creating several StringBuilders for each variable?

There is no more effective way than creating a something for each of the variables.
Don't use forEach here: there is no advantage over a plain old loop (see here for a question about the differences):
final StringBuilder xBuilder = new StringBuilder();
final StringBuilder yBuilder = new StringBuilder();
final StringBuilder zBuilder = new StringBuilder();

for (SomeObject obj : someObjects) {
  A a = obj.getA();

  // Use two appends, rather than concatentating then appending.
  xBuilder.append(obj.getX()).append(",");

  yBuilder.append(obj.getY()).append(",");
  zBuilder.append(a.getZ()).append(",");

}

A: Collectors.joining() method will use StringJoiner internally to append Strings with passed delimiter like here ','.
someObjects.stream().collect(Collectors.joining(","));

A: As you're concatenating 3 different properties of the object, you need to use 3 different StringBuilder instances (or StringJoiner). You could iterate the list of objects 3 times, one for each property, or if you only want to iterate once (despite traversing a list is extremely cheap), you could use either your own approach or a traditional foreach.
Or you could also use the code I'm showing below, which is semantically equivalent to the other answers, except that it allows to decouple the concatenation process from the iteration (if you need this at all):
StringBuilder xBuilder = new StringBuilder(); // no need to use final since
StringBuilder yBuilder = new StringBuilder(); // these instances are
StringBuilder zBuilder = new StringBuilder(); // effectively final

Consumer<SomeObject> action = ((Consumer<SomeObject>) obj ->
    xBuilder.append(obj.getX() + ","))
        .andThen(obj -> yBuilder.append(obj.getY() + ","))
        .andThen(obj -> zBuilder.append(obj.getA().getZ() + ","));

Then, you can pass around action (i.e. to some method that doesn't have visibility over the builders) and simply do:
someObjects.forEach(action);


text:
Q: proving the inequality $ (\frac{n}{e})^n \leq n! \leq en ( \frac{n}{e})^n$ by induction I want to prove $ (\frac{n}{e})^n \leq n! \leq en ( \frac{n}{e})^n$ by induction. For this prove I want to use the inequality $(\frac{n+1}{n})^n < e <(\frac{n+1}{n})^{n+1}$.
for $n=1$ the inequality is obvious. I Assume it is true for a fixed $n\in \mathbb{N}$ and want to show that
$
(\frac{n+1}{e})^{n+1} \leq (n+1)! \leq e(n+1) ( \frac{n+1}{e})^{n+1}
$
However I have problems with using both the induction hypothesis and the inequalities $(\frac{n+1}{n})^n < e <(\frac{n+1}{n})^{n+1}$ to obtain my answer.

A: Using the mentioned inequality we have:
$$\left(\frac{n+1}{n}\right)^n < e \implies \frac{(n+1)^n}{e^{n+1}} < \frac{n^n}{e^n} \implies \left(\frac{n+1}{e}\right)^{n+1} < \left(\frac{n}{e}\right)^n(n+1) \le n!(n+1) = (n+1)!$$
This proves the left side of the inequality. Similarly:
$$e < \left(\frac{n+1}{n}\right)^{n+1} \implies n\left(\frac{n}{e}\right)^n < \left(\frac{n+1}{e}\right)^{n+1}$$
Using this and the induction hypothesis we have:
$$e(n+1)\left(\frac{n+1}{e}\right)^{n+1} > (n+1)en\left(\frac{n}{e}\right)^n \ge (n+1)n! = (n+1)!$$
Hence the inequality is proven

A: I had originally written this up for another question but it seems fitting here as well. Maybe this can help someone.
Depending on how you introduced $e$, you might be able to use the fact that there are two sequences $(a_n)_{n \in \mathbb{N}}$, $(b_n)_{n \in \mathbb{N}}$ with
$$\begin{align}
a_n ~~~&:=~~~ \left ( 1 + \frac{1}{n} \right ) ^n \\ ~ \\
b_n ~~~&:=~~~ \left ( 1 - \frac{1}{n} \right ) ^{-n}
\end{align}$$
and
$$\underset{n \rightarrow \infty}{\lim} a_n ~~~=~~~ \underset{n \rightarrow \infty}{\lim} b_n ~~~=~~~ e \\ ~ \\$$
While both sequences converge to the same limit, $a_n$ approaches from the bottom and $b_n$ approaches from the top:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams.update({'figure.autolayout': True})

pts = np.arange(0, 20, 1)
a_n = lambda n: (1+1/n)**n
b_n = lambda n: (1-1/n)**(-n)

plt.errorbar(x = pts, xerr = None, y = a_n(pts), yerr = None, fmt = "bx", markersize = "5", markeredgewidth = "2", label = "$a_n$")
plt.errorbar(x = pts, xerr = None, y = b_n(pts), yerr = None, fmt = "rx", markersize = "5", markeredgewidth = "2", label = "$b_n$")
plt.plot(pts, [np.exp(1)]*len(pts), color = "black", linewidth = 2, label = "$e$")
plt.xlim(1.5, 14.5)
plt.ylim(2.0, 3.5)
plt.legend(loc = "best")
plt.setp(plt.gca().get_legend().get_texts(), fontsize = "22")
plt.show()

So we're going to use the following inequality:
$$\forall n \in \mathbb{N} ~ : ~~~~~ \left ( 1 + \frac{1}{n} \right ) ^n ~~~~<~~~~ e ~~~~<~~~~ \left ( 1 - \frac{1}{n} \right ) ^{-n} \tag*{$\circledast$} \\ ~ \\$$

Thesis
$$\forall n \in \mathbb{N}, ~ n \geq 2 ~ : ~~~~~ e \cdot \left ( \frac{n}{e} \right )^n ~~~~<~~~~ n! ~~~~<~~~~ n \cdot e \cdot \left ( \frac{n}{e} \right )^n \\ ~ \\$$

Proof By Induction
Base Case
We begin with $n = 2$ and get
$$\begin{align}
& ~ && e \cdot \left ( \frac{2}{e} \right )^2 ~~~~&&<~~~~ 2! ~~~~&&<~~~~ 2 \cdot e \cdot \left ( \frac{2}{e} \right )^2 \\ ~ \\
& \Leftrightarrow && e \cdot \frac{4}{e^2} ~~~~&&<~~~~ 1 \cdot 2 ~~~~&&<~~~~ 2 \cdot e \cdot \frac{4}{e^2} \\ ~ \\
& \Leftrightarrow && \frac{4}{e} ~~~~&&<~~~~ 2 ~~~~&&<~~~~ \frac{8}{e} \\ ~ \\
&\Leftrightarrow && 2 ~~~~&&<~~~~ e ~~~~&&<~~~~ 4 ~~~~ \\
\end{align}
$$
Which is a true statement.
Inductive Hypothesis
Therefore the statement holds for some $n$. $\tag*{$\text{I.H.}$}$
Inductive Step
$$\begin{align}
& ~ && e \cdot \left ( \frac{n+1}{e} \right )^{n+1} \\ ~ \\
& = && (n+1) \cdot \frac{1}{e} \cdot e \cdot \left ( \frac{n+1}{e} \right )^n\\ ~ \\
& = && (n+1) \cdot \left ( \frac{n}{e} \right )^n \cdot \left ( \frac{n+1}{n} \right )^n\\ ~ \\
& = && (n+1) \cdot \left ( \frac{n}{e} \right )^n \cdot \left ( 1 + \frac{1}{n} \right )^n\\ ~ \\
& \overset{\circledast}{<} && (n+1) \cdot \left ( \frac{n}{e} \right )^n \cdot e\\ ~ \\
& \overset{\text{I.H.}}{<} && (n+1) \cdot n!\\ ~ \\
& = && (n+1)!\\ ~ \\
& = && (n+1) \cdot n!\\ ~ \\
& \overset{\text{I.H.}}{<} && (n+1) \cdot n \cdot e \cdot \left ( \frac{n}{e} \right )^n\\ ~ \\
& = && (n+1) \cdot e \cdot \left ( \frac{n}{e} \right )^{n+1} \cdot e \\ ~ \\
& = && (n+1) \cdot e \cdot \left ( \frac{n+1}{e} \right )^{n+1} \cdot \left ( \frac{n}{n+1} \right )^{n+1} \cdot e \\ ~ \\
& = && (n+1) \cdot e \cdot \left ( \frac{n+1}{e} \right )^{n+1} \cdot \left ( 1 - \frac{1}{n+1} \right )^{n+1} \cdot e \\ ~ \\
& \overset{\circledast}{<} && (n+1) \cdot e \cdot \left ( \frac{n+1}{e} \right )^{n+1} \cdot \left ( 1 - \frac{1}{n+1} \right )^{n+1} \cdot \left ( 1 - \frac{1}{n+1} \right )^{-(n+1)} \\ ~ \\
& = && (n+1) \cdot e \cdot \left ( \frac{n+1}{e} \right )^{n+1} \\ ~ \\
\end{align}
$$
Conclusion
Therefore the statement holds $\forall n \in \mathbb{N}, ~ n \geq 2$.
$$\tag*{$\square$}$$


text:
Q: error[E0597]: borrowed value does not live long enough in While loop I am really new to Rust, I am having trouble solving this error, but it only happens if I comment out the while statement , basicly I am asking values from the console and storing it in a HashMap:
use std::collections::HashMap;
use std::io;

fn main() {
    let mut customers = HashMap::new();
    let mut next_customer = true;
    while next_customer {
        let mut input_string = String::new();
        let mut temp_vec = Vec::with_capacity(3);
        let mut vec = Vec::with_capacity(2);
        println!("Insert new customer f.e = customer id,name,address:");
        io::stdin().read_line(&mut input_string);
        input_string = input_string.trim().to_string();
        for s in input_string.split(",") {
            temp_vec.push(s);
        }
        vec.push(temp_vec[1]);
        vec.push(temp_vec[2]);
        let mut key_value = temp_vec[0].parse::<i32>().unwrap();
        customers.insert(key_value, vec);
        next_customer = false;
    }
    println!("DONE");
}

The code results in the error
error[E0597]: `input_string` does not live long enough
  --> src/main.rs:14:18
   |
14 |         for s in input_string.split(",") {
   |                  ^^^^^^^^^^^^ borrowed value does not live long enough
...
20 |         customers.insert(key_value, vec);
   |         --------- borrow later used here
21 |         next_customer = false;
22 |     }
   |     - `input_string` dropped here while still borrowed

A: As others have said the problem lies with the lifetime and/or type of the values getting put into the customers map.
customers.insert(key_value, vec);
   |         --------- borrow later used here

Often this happens when the compiler has decided to give an object a type that you didn't expect. To find out what it's doing you can force the type, and see how it complains. Changing the code to:
    let mut customers: HashMap<(),()> = HashMap::new();

Gives us two relevant errors:
20 |         customers.insert(key_value, vec);
   |                          ^^^^^^^^^ expected `()`, found `i32`
...
20 |         customers.insert(key_value, vec);
   |                                     ^^^ expected `()`, found struct `std::vec::Vec`
   |
   = note: expected unit type `()`
                 found struct `std::vec::Vec<&str>`

So the type that the compiler wants to give our customers object is HashMap<i32, Vec<&str>>
The problem is that the &str lifetime has got to be inside the block as we don't store the Strings anywhere, and they can't have 'static lifetime since they're user input.
This means we probably want a HashMap<i32,Vec<String>>.
Changing the code to use one of those gives us an error about vec not having the right type: It's getting deduced as a Vec<&str>, but we want a Vec<String>.
We have two options.

*

*Convert the vec to the right type just before we insert it into the map using customers.insert(key_value, vec.iter().map(|s| s.to_string()).collect()). (Though you may want to extract it to a variable for clarity).

*Explicitly change the type of vec to Vec<String>
Option 1 "just works". While option 2 leads us down a path of making similar changes closer and closer to the read_line call.
Once you've decided on the fix in option 1, you can remove the manual type annotations that were added to work out the fix, if you find them overly noisy.

A: The issue is that you are passing around reference to underlying &str values that will get dropped.  One way is to take the input string, trim and split it, then clone it going into the other vector.
let temp_vec: Vec<String> = input_string.trim().split(",").map(|t| t.to_string()).collect();
vec.push(temp_vec[1].clone());
vec.push(temp_vec[2].clone());


text:
Q: Не приходят данные через AJAX есть скрипт который меняет значение рейтинга в базе данных.
Отдельно скрипт работает верно, если указать прямо в нем нужные данные, но в связке с скриптом на JavaSсript не работает, я так понимаю что данные просто не передаются.


text:
Q: How to collect results into array from annotation? Is this possible to collect results from different Case directives and store them in an array field?
Several intances for test:
banana = Fruit.objects.create(name='banana', type='tropicals', country_of_import='Africa')
orange = Fruit.objects.create(name='orange', type='citrus', country_of_import='Spain')
apple = Fruit.objects.create(name='apple', type='apples', country_of_import='Russia')

Here is the Manager that needs to collect all results from cases. ToArray as a possible function that does this work. There is a function with a similar name ArrayAgg according to the docs:

Returns a list of values, including nulls, concatenated into an array.

It works fine with one expression, but not with several:
class CustomManager(Manager):

    def get_queryset(self):
        query = super().get_queryset().annotate(
            additional_info=ToArray(
                Case(
                    When(
                        type='tropicals',
                        then=Value('This fruit is tropical...')
                    ),
                    output_field=CharField()
                ),
                Case(
                    When(
                        country_of_import='Spain',
                        then=Value('This fruits was grown in Spain'),
                    ),
                    output_field=CharField()
                )
            )
        )
        return query

And in the end the result would be:
banana.additional_info = ['This fruit is tropical.']
orange.additional_info = ['This fruits was grown in Spain.']

Is this possible to handle with existing function or do I need to write my own?

A: Actually, there is no obvious way to implement this. The most simple solution would be to use CombinedExpression class like this:
from django.contrib.postgres.aggregates import ArrayAgg
from django.db.models import Manager, Case, When, Value, CharField

from django.db.models.expressions import CombinedExpression

class FruitManager(Manager):
    def get_queryset(self):
        query = super().get_queryset()

        query = query.annotate(
            result=(
                CombinedExpression(
                    ArrayAgg(Case(
                        When(
                            type='tropicals',
                            then=Value('This fruit is tropical...'),

                        ),
                        output_field=CharField()
                    )),
                    '||'
                    ,
                    ArrayAgg(Case(
                        When(
                            country_of_import='Africa',
                            then=Value('This fruit is citrus...'),

                        ),
                        output_field=CharField(),
                        default=Value('default value')),
                    ),
                )
            )
        )
        return query

That will be compiled to the following SQL:
SELECT "core_fruit"."id",
       (
               ARRAY_AGG(CASE
                             WHEN "core_fruit"."type" = 'tropicals'
                                 THEN 'This fruit is tropical...'
                             ELSE NULL END) ||
               ARRAY_AGG(
                       CASE
                           WHEN "core_fruit"."country_of_import" = 'Africa'
                               THEN 'This fruit is citrus...'
                           ELSE 'default value' END
                   )
           ) AS "result"
FROM "core_fruit"
GROUP BY "core_fruit"."id";

But there is one thing worth to note, CombinedExpression isn't documented because intended only for internal usage.


text:
Q: Execute a VSTS query and get all its details using API I created a VSTS query under a folder shared. But when I try to list all queries under my domain nothing in that folder is showing. That folder name is showing in that JSON response. But real queries under that folder is not showing.
This is the way I tried to list all queries
https://dev.azure.com/{org}/{projectid}/_apis/wit/queries?api-version=4.1

But its just listing the top folders. I need to list all queries under that project
Next and major issue is once I have an API id and on executing its only giving me the workitem ID and url. I am not getting any details such as its task or bug or that specific information
This is the way I tried
https://dev.azure.com/{org}/{proj}/_apis/wit/wiql/{wiqlid}?api-version=5.0&$expand=all

Please help me how to solve these two troubles.

A: Can you try depth parameter?

In the folder of queries, return child queries and folders to this depth.

If you do this you shloud get queries in children collection.
https://dev.azure.com/thecodemanual/DevOps Manual/_apis/wit/queries?$expand=all&$depth=2&api-version=5.1

If you queries are in subfolder this may help you.
When I run wiql I got this:
https://dev.azure.com/thecodemanual/DevOps Manual/DevOps Manual Team/_apis/wit/wiql/91dad662-7104-4882-b28f-945c152fc4ee?api-version=5.1

{
    "queryType": "flat",
    "queryResultType": "workItem",
    "asOf": "2020-05-15T10:12:01.163Z",
    "columns": [
        {
            "referenceName": "System.Id",
            "name": "ID",
            "url": "https://dev.azure.com/thecodemanual/_apis/wit/fields/System.Id"
        },
        {
            "referenceName": "System.WorkItemType",
            "name": "Work Item Type",
            "url": "https://dev.azure.com/thecodemanual/_apis/wit/fields/System.WorkItemType"
        },
        {
            "referenceName": "System.Title",
            "name": "Title",
            "url": "https://dev.azure.com/thecodemanual/_apis/wit/fields/System.Title"
        },
        {
            "referenceName": "System.State",
            "name": "State",
            "url": "https://dev.azure.com/thecodemanual/_apis/wit/fields/System.State"
        },
        {
            "referenceName": "System.AreaPath",
            "name": "Area Path",
            "url": "https://dev.azure.com/thecodemanual/_apis/wit/fields/System.AreaPath"
        },
        {
            "referenceName": "System.IterationPath",
            "name": "Iteration Path",
            "url": "https://dev.azure.com/thecodemanual/_apis/wit/fields/System.IterationPath"
        },
        {
            "referenceName": "System.Tags",
            "name": "Tags",
            "url": "https://dev.azure.com/thecodemanual/_apis/wit/fields/System.Tags"
        }
    ],
    "sortColumns": [
        {
            "field": {
                "referenceName": "System.ChangedDate",
                "name": "Changed Date",
                "url": "https://dev.azure.com/thecodemanual/_apis/wit/fields/System.ChangedDate"
            },
            "descending": true
        }
    ],
    "workItems": []
}

And this is a wiql query run behind:
select [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State], [System.Tags]
from Workitems
where [System.TeamProject] = @project and [System.WorkItemType] <> '' and [System.State] <> ''

Is this what you want to get?
EDIT
You are nissing team here
https://dev.azure.com/{org}/{proj}/_apis/wit/wiql/{wiqlid}?api-version=5.0&$expand=all

Please add team after proj
https://dev.azure.com/{org}/{proj}/{team}/_apis/wit/wiql/{wiqlid}?api-version=5.0&$expand=all

{team}


text:
Q: Corrupt zip file downloaded in angular Angular client code:
         $http.post('/zip', {
            id: _id
        })
        .success(function (data, status, headers, config) {
            var blob = new Blob([data], {type: "application/zip"});
            var contentDisp = headers('content-disposition');
            if (contentDisp && /^attachment/i.test(contentDisp)) {
                var fileName = contentDisp.toLowerCase()
                    .split('filename=')[1]
                    .split(';')[0]
                    .replace(/"/g, '');
                //The below command works but generates a corrupt zip file.
                FileSaver.saveAs(blob, fileName);
            }
        })
        .error(function () {
            console.log("Could not download");
        });

NodeJS Server Code:
        app.route('/zip/')
        .post(function(req, res) {

          var output = fs.createWriteStream(join(outdir, outzipfile));
          //Using s3zip to archive.
          s3Zip
           .archive({ s3: s3Client, bucket: bucket}, folder, s3_files)
           .pipe(output);

          output.on('close', function() {
             //This sends back a zip file.
             res.download(outPutDirectory + outputBcemFile);
          });

          output.on('error', function(err) {
             console.log(err);
             return res.status(500).json({error: "Internal Server Error"});
          });

        });

Although FileSaver.saveAs works and downloads the zip file, it seems to be corrupted. Is the type "application/zip" correct? I have also tried "octet/stream" and it downloads a corrupt zip file too. Any help would be highly invaluable! Thanks.

A: This is a bug mentioned in Git in below link :
https://github.com/eligrey/FileSaver.js/issues/156
To solve you need to add : responseType: 'arraybuffer' to your $http Request headers and it will work.


text:
Q: How to tell if a USB is plugged by parsing PID and VID First of all I wanna thank you for making time to read my post.
I need a Visual basic or a VBSCript code that can detect if a specific USB is plugged.
I have therse infos:
VID_0DF7
PID_0620
My code do not want to work :( I dont know how to make it to read only a specific VID and Pid :( Please dont thumb my post down only because I do not know how to do something.
I found many examples on the internet but actualy for telling what is the PID and the VID for All plugged devices...so...i do not need them...
My code:
strComputer = "."

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colDevices = objWMIService.ExecQuery _
    ("Select * From Win32_USBControllerDevice")

For Each objDevice in colDevices
    strDeviceName = objDevice.Dependent
    strQuotes = Chr(34)
    strDeviceName = Replace(strDeviceName, strQuotes, "")
    arrDeviceNames = Split(strDeviceName, "=")
    strDeviceName = arrDeviceNames(1)
    Set colUSBDevices = objWMIService.ExecQuery _
        ("Select * From Win32_PnPEntity Where DeviceID = '" & strDeviceName & "'")
    For Each objUSBDevice in colUSBDevices
        Wscript.Echo objUSBDevice.Description
    Next
Next

Thank you!

A: Something like this should work:
Set wmi = GetObject("winmgmts://./root/cimv2")

vid = "VID_0DF7"
pid = "PID_0620"

For Each d In wmi.ExecQuery("SELECT * FROM Win32_USBControllerDevice")
  If InStr(d.Dependent, vid & "&" & pid) > 0 Then
    WScript.Echo wmi.Get(d.Dependent).Description
  End If
Next

If you want a notification when there's no device matching your criteria, you cannot implement an Else branch inside the loop. A nested Else would fire for each device that doesn't match the criteria, whereas you want a notification only if none of the devices match the criteria. Use a boolean value that you change to True when you find a matching device:
found = False
For Each d In wmi.ExecQuery("SELECT * FROM Win32_USBControllerDevice")
  If InStr(d.Dependent, vid & "&" & pid) > 0 Then
    WScript.Echo wmi.Get(d.Dependent).Description
    found = True
  End If
Next

If Not found Then WScript.Echo "USB not found."


text:
Q: How to get the systems Battery Percentage in Swift 5? I'm trying to include a battery feature to my widget, but I can't seem to get the mobile's battery percentage...
I tried:
import UIKit

struct BatteryControl {
    static func getBatteryPercent() -> Int {
        UIDevice.current.isBatteryMonitoringEnabled = true
        print("BATTERY : \(UIDevice.current.batteryLevel)")
        return Int(UIDevice.current.batteryLevel * 100)
    }
}

It just keeps showing that the battery is -1.0
EDIT
SOLUTION: Simulator always showing the batter as -1.0, but whem testing it on a real deivce, it showed the correct value.

A: The battery monitoring must be enabled in the method didFinishLaunchingWithOptions of the AppDelegate
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        UIDevice.current.isBatteryMonitoringEnabled = true
        return true
    }


text:
Q: UIWebView get HTML Source I am trying to get the HTML source of a UIWebView without re-downloading it again (a.k.a. do another download, such as [NSData dataWithContentsOfURL:(NSURL*)URL] or launching an NSURLRequest. Browsing the UIWebView header and documentation, there seems to be no way of accessing the current loaded NSData of the source. Am I missing something ?

A: UIWebView can execute javascript code, so this can work it out.
NSString *html = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.outerHTML"];

A: The inverse should do what you want. That is, load the URL into an NSData object and then load the UIWebView from that object using – loadData:MIMEType:textEncodingName:baseURL:


text:
Q: Partial with login and page logic I have a navigation bar that I want to be a partial. The contents of the nav bar will vary slightly, like if the user is logged in or if you're on a certain page you might get an extra link.
How do I best deal with providing the data to the partial? Should I pass this in ViewData for every controller?
A list of options would help me the most, because likely I will have to utilize a few different techniques.

A: Make a model for it. Create a class NavModel which in its constructor gathers all the data it represents (friendly user name, current page, etc.) and publishes them as public properties. Then just bind the model to the view as usual. Oh, and avoid instantiating nav model directly in a view, instead create a controller action (called Nav) which instantiates the NavModel and  returns the nav partial view. Mark that action as ChildActionOnlyAttribute so that it can't be requested by the client. Then use @Html.RenderAction in the view that needs to render the nav partial (usually a layout view).

A: I had the same problem sometime ago, when i have to show some menu to admin and some menu to super admin and some to others...  What i did in that case. I made a an action returning partial view and rendered it on master page. The view was strongly typed. ( A class whose property representing roles of user.) so using that strongly typed class i wrote if and else if logic in my razor view..and that solved my problem....Hope this would help you.


text:
Q: DataGridAutoFilter C# Существует библиотека DataGridAutoFilter для winforms, которая вешает фильтр на столбец в datagridview. Я обновляю datagridview так :
        public void update_shift()
    {
        cn.Open();
        BindingSource bsshift = new BindingSource();
        DataSet dsshift = new DataSet();
        DataTable dtshift = new DataTable();

        dsshift.Tables.Add(dtshift);

        SqlDataAdapter dashift = new SqlDataAdapter();
        dashift = new SqlDataAdapter("select shift.truck, shift.tripNumber, case when exists(select * from shift sh1 WHERE cast(sh1.capacityKg as int) < (select sum(cast(kg as int)) from orders join action on orders.order_number = action.id_order where action.shiftcode = sh1.shiftcode) and sh1.shiftcode = shift.shiftcode) THEN 1 ELSE 0 end as ErrUpload, shift.comment, case when exists (SELECT * FROM action WHERE shiftcode = shift.shiftcode and id_order is not null) THEN 1 ELSE 0 end as planned, shift.datework,driver, statusName, trailer,subcontractor.contactName, shift.shiftcode, shift.capacityKg, shift.capacityPal, (select sum(cast(kg as int)) from orders join action on orders.order_number = action.id_order where action.shiftcode = shift.shiftcode)  as uploadKg,(select sum(cast(pal as int)) from orders join action on orders.order_number = action.id_order where action.shiftcode = shift.shiftcode)  as uploadPal, (select top 1 address.cityName from address join action on address.addressCode = action.finish where action.shiftcode = shift.shiftcode) as firstCity from shift  left join dbo.subcontractor ON shift.subcontractor = dbo.subcontractor.contact_externalId left join shiftStatus ON shift.status = shiftStatus.id_status WHERE shift.datework ='2016-06-17'  ORDER by shift.truck, shift.tripNumber ASC", cn);
        dashift.Fill(dtshift);
        bsshift.DataSource = dtshift;
        int index2 = dataGridView2.FirstDisplayedScrollingRowIndex;
        dataGridView2.DataSource = bsshift;
        cn.Close();

    }

И фильтр со столбцов сбивается, становится все с нуля. То есть, выбрали на фильтре фамилию Петров, правой кнопкой мыши вызвал еще одно окно с данными "Петрова", изменил ему, к примеру возраст. По закрытию формы 2(с данными) у меня стоит запуск функции в первой форме update_shift(), что бы на первой форме в строке сразу обновились данные, в этом случае по фамилии петров, но после обновления слетает фильтр со столбца и приходится снова его ставить.
Если делать вот так
        private void button1_Click(object sender, EventArgs e)
    {
        this.dataTable1TableAdapter.Fill(this.newDataSet1.DataTable1);
    }

То не слетает, объясните пожалуйста, в чем разница, и как мне решить эту проблему? Лепить кучу комбо боксов над datagridview не красиво.

A: Необходимо сохранить фильтры перед обновлением DataGridView, так как фильтрация происходит не на уровне DataGridView, а на уровне DataSet. А при назначении DataGridView нового DataSet со старым теряются и фильтры.
string filter = "";

// Ошибка если фильтров нет
try
{
   filter = (dataGridView1.DataSource as DataTable).DefaultView.RowFilter;
}
catch { }

dataGridView1.DataSource = bsshift;

if (filter.Length > 0)
{
   (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = filter;
}


text:
Q: \vec{p_{\bar p}} renders strangely When I do:
\vec{p_{\bar p}}

I get:

instead of

with the \vec shifted over a bit. Why does this happen?
(Also, \vec{\mbox{p_{\bar p}}} renders identically, even though \mbox{p_{\bar p}} looks fine, which clashes with my previous mental model of \mbox – I thought that things outside the box don't really affect things inside the box; guess I'm wrong.)

A: This seems connected to the bug already examined in the question Why do arguments to nested \tilde or \breve commands reappear when amsmath is used?
Indeed, if amsmath is not loaded, your code works fine.
The solution is to avoid nesting:
$\vec{p}_{\bar{p}}$

which is, in my opinion, more mathematically sound.


text:
Q: jquery mobile javascript verify json key My mobile app reads an external json object. How can I check in javascript that a key node exists in the dynamically generated json structure? I tried the hasOwnProperty or containsKey methods, but without luck.
Example json data:
{  "element1":
  {  "element2": { "Number":  "0" },
     "element3": { "Number":  "1" },
     "element4": { "Number":  "2" }
  }
}

As these elements are generated dynamically, I want to check if the key element3 exists in this structure. No luck with data.element1.hasOwnProperty("element3").

A: Yes, hasOwnProperty() method does not work for a Json object. It works for a Java Script Object. So You just need to convert this Json object into a Java Script Object using eval() method and check inside that object.
When you convert above Json structure, it will create an Object (element1) inside another Object (say JSObject). element1 will contain properties element2, element3 and element4. So your code should go like this.
var MyObject={  "element1":
  {  "element2": { "Number":  "0" },
     "element3": { "Number":  "1" },
     "element4": { "Number":  "2" }
  }
}

var JSObject=eval('(' + MyObject+ ')');

var IsExistElement3 = JSObject.element1.hasOwnProperty("element3");


text:
Q: How do i know if the ADODB is connected to my database using vb.net (class, module and form) I hope the title is enough to understand my problem, it already installed whats need to run the ADODBC, my problem is how do i know if the connection is connected to the database mariadb
Module GlobalVariables
    Public sGlobalConnectionString As String

    Sub Main()
        Dim clsFunction As New clsFunction
        Dim sParameter As String
        Dim sDataserver As String
        Dim sDatabaseName As String
        Dim sDatabaseConnection As String

        sDataserver = "localhost"
        sDatabaseName = "employee"
        sDatabaseConnection = "Driver={MariaDB ODBC 3.1 Driver}; SERVER=" & sDataserver & "; UID=root;PWD=*****; Database=" & sDatabaseName & "; PORT=3307; OPTION=3"
        sGlobalConnectionString = sDatabaseConnection
    End Sub
End Module

this is my class
Public Class Query
    Private Sub Class_ConOpen()
        Dim con = New ADODB.Connection
        con.ConnectionString = sGlobalConnectionString
        con.Open
        con.CommandTimeout = 0
    End Sub
    Private Sub Class_ConClose()
        Dim con = New ADODB.Connection
        If Not con Is Nothing Then
            con.Close
            con = Nothing
        End If
    End Sub
End Class

this is my form, is this right? going to used try catch?
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
        Try
           ?????
        Catch ex As Exception
           ????
        End Try
    End Sub

A: You can try the State property of con object.
con.State property will tell you the state of the connection.

A: The only way to find out if your application is connected to the database is to execute command, such as SELECT servername;.
Even if the state of connection is Open there's no 100% that you're connected to the database. In other word, if command will execute without errors, connection is OK.


text:
Q: Find the minimum value of n such that the given limit is 0. Suppose that $\phi_1$ and $\phi_2$ are linearly independent solutions of the differential equation $$2x^2y''-(x+x^2)y'+(x^2-2)y=0,$$ and $\phi_1(0)=0$. Then the smallest positive integer $n$ such that $$\lim_{x\to 0}x^n\frac{\phi_2(x)}{\phi_1(x)}=0\ \text{is}$$
Attempt: I have started by calculating Wronskian through Abel's formula according to which $$W(\phi_1, \phi_2)(x)=W(\phi_1, \phi_2)(0)e^{\int\frac{-(x+x^2)\, dx}{2x^2}} = W(\phi_1, \phi_2)(0) \sqrt{x}e^{-\frac{x}{2}}.$$ Further, since $\phi_1$ and $\phi_2$ are linearly independent, their Wronskian must be non-zero, but $W(\phi_1, \phi_2)(0)=0$. I am confused. Please tell how to proceed.

A: Since $\phi_1(x)$ is a solution, one has
$$ 2x^2\phi_1''-(x+x^2)\phi_1'+(x^2-2)\phi_1=0. \tag{1}$$
Dividing (1) by $x$ gives
$$ 2x\phi_1''(x)-(1+x)\phi_1'(x)+(x^2-2)\frac{\phi_1(x)}{x}=0. $$
Using $\phi_1(0)=0$ and $\lim_{x\to0}\frac{\phi_1(x)}{x}=\phi_1'(0)$ and letting $x\to0$, one obtains
$$ -3\phi_1'(0)=0,\text{ or }\phi'_1(0)=0. $$
Thus $\phi_1(x)=ax^2+O(x^3)$.
Define $k(x)=\frac{\phi_2(x)}{\phi_1(x)}$ and then $\phi_2(x)=k(x)\phi_1(x)$.  Since $\phi_2(x)$ is a solution, one has
$$ 2 x^2 \left(\phi _1(x) k''(x)+2 k'(x) \phi _1'(x)+k(x) \phi
   _1''(x)\right)+\left(x^2-2\right) k(x) \phi _1(x)=x (x+1) \left(\phi _1(x) k'(x)+k(x)
   \phi _1'(x)\right). $$
Using (1) gives
$$ \phi _1(x) \left((x+1) k'(x)-2 x k''(x)\right)-4 x k'(x) \phi _1'(x)=0. $$
So
$$ \frac{k''(x)}{k'(x)}=\frac{(1+x)\phi_1(x)-4x\phi_1'(x)}{2x\phi_1(x)}=\frac12(1+\frac1x-4\frac{\phi_1'(x)}{\phi_1(x)}) $$
which gives
$$ \ln(k'(x))=\frac12(x+\ln x-4\ln\phi_1(x))+c. $$
So
$$ k'(x)=\frac{ce^{x/2}\sqrt x}{\phi_1^2(x)}\approx C_2x^{-7/2} $$
which gives
$$ k(x)\approx C_1+ C_2x^{-5/2}. $$
Thus
$$ \lim_{x\to0}x^nk(x)=\lim_{x\to0}C_2x^{n-5/2}=0 $$
implies that the smallest integer is $n=3$.


text:
Q: How can I display the alphanumeric ID on the front end of my Windows form and stop accepting more entries after a limit is reached? I have a Student table in my SQL Server database which is as follows:
CREATE TABLE [dbo].[Student]
(
    [Id]   INT NOT NULL,
    [Name] NVARCHAR (50) NOT NULL,
    [MyId] AS 'S' + RIGHT('00'+ CONVERT(VARCHAR(5), Id), 2) PERSISTED,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

I have created a front-end page through which a user can add entries into this table.

When the user clicks on the Create button above, it takes him to the following window:

I want the MyId value to be displayed in the circled text-box instead of the Id value. In the case of the window above, I want S11 to be displayed instead of 11 but I do not know how to accomplish that without hard-coding the zeroes. The code I have written so far is as follows:
var query_1 = "SELECT TOP 1 Id + 1 " +
              "FROM dbo.Student mo " +
              "WHERE NOT EXISTS(SELECT NULL FROM dbo.Student mi " +
              "                 WHERE mi.Id = mo.Id + 1)" +
              "ORDER BY Id";

using (connection = new SqlConnection(connectionString))
using (SqlCommand sa = new SqlCommand(query_1, connection))
{
    connection.Open();

    SqlDataReader da = sa.ExecuteReader();

    while (da.Read())
    {
        txtID.Text = da.GetValue(0).ToString();
    }

    connection.Close();
}

The entries I have created so far in the Student table are as follows:

How can I ensure that the latest/desired MyId value is displayed in the ID text-box? Additionally, how do I make sure the user is not allowed to make further entries in the table after S99?


text:
Q: R shiny: highlight a point in two different graphs I would like to highlight a point in two graphs. I want to select a point in one graph,highlight it and highlight this point in the other graph.
I have used a reactive object where I called the "nearPoints" function, but when I highlight a point it disappears automatically and it changes the other graph. Could you help me please ?
Here is the code:
#Load  data:
data_073 <- read_csv("Study_ACI073.csv")
data_074 <- read.csv("Study_ACI074.csv")
data_071 <- read.csv("Study_ACI071.csv")
data_077 <- read.csv("Study_ACI077.csv")

data_073$Group <- factor(data_073$Group, levels = c("tTA-Vehicle","Tg4510-Vehicle","Tg4510-ACI-12518\r\n100mg/kg-bid","Tg4510-ACI-15588\r\n30mg/kg-bid","Tg4510-ACI-15588\r\n100mg/kg-bid"))
data_073$Color <- factor(data_073$Color, levels = c("grey","#F8766D","#7CAE00","lightblue","darkblue"))

data_074$Group <- factor(data_074$Group, levels = c("tTA-Vehicle","Tg4510-Vehicle","Tg4510-ACI-12518\n30mg/kg-bid","Tg4510-ACI-12518\n100mg/kg-bid"))
data_074$Color <- factor(data_074$Color, levels=c("grey","#F8766D","yellowgreen","forestgreen"))

data_071$Group <- factor(data_071$Group, levels = c("Vehicle","ACI-12518-30mg/kg"))
data_071$Color <- factor(data_071$Color, levels = c("indianred1","forestgreen"))

data_077$Group <- factor(data_077$Group, levels = c("tTA-Vehicle","Tg4510-Vehicle","Tg4510-ACI-16664\n100mg/kg-bid"))
data_077$Color <- factor(data_077$Color, levels = c("grey","#F8766D","#7CAE00"))

# Define all the desired input on the left and the output ( plot and table)
ui <- fluidPage(

  # Application title
  titlePanel("R_shiny"),

  # Sidebar with conditional Panel depending if we want a correlation or a data plot. First we choose the type of plot.
  # Depending on the choice, several options are available: for data plot, we have : type of transformations, choices for the variable,plot by cohort ans which groups of treatment.

  # For correlation plot, we need to choose the X-axis variable, the Y-axis variable, the number of groups and the name of the labels for the axes.
  sidebarPanel(

    selectInput("data_set", label = "Select the data set", choices = c("Study ACI071", "Study ACI073","Study ACI074", "Study ACI077")),

    selectInput("Var1", label="Choose the X-axis", choices = "FrCtx.AT8.Class3.OD",selected="FrCtx.AT8.Class3.OD"),
    selectInput("Var2", label="Choose the Y-axis", choices = "FrCtx.AT8.Class4.OD",selected = "FrCtx.AT8.Class4.OD" ),
    textInput("lab_x","Label for X-axis",value=" "),
    textInput("lab_y","Label for Y-axis",value=" "),
    checkboxGroupInput("Groups","Groups:",choices = NULL),
    radioButtons("transformation", "Transformations:", c("None"="no", "Square root"="sqrt", "Logarithm"="log")),
    checkboxInput("cohort", "Plot by cohort", FALSE)

  ),

  mainPanel(
    plotOutput("plot1",click="plot_click"),
    plotOutput("plot2"),
    tableOutput("info"),
    tableOutput("selected"),
    br(),
    tableOutput("summary"),
    br(),
    br(),
    downloadLink("downloadPlot1", "Download Correlation Plot"),
    br(),
    downloadLink("downloadPlot2", "Download Data Plot")
  )

)

server <- function(input, output,session){

  datasetInput <- reactive({
    if(req(input$data_set) == "Study ACI071"){
      a <- data_071
    } else if (req(input$data_set) == "Study ACI073"){
      a <- data_073
    } else if(req(input$data_set) == "Study ACI074"){
      a <- data_074
    } else{
      a <- data_077
    }
  })

  observe({
    dataset <- datasetInput()
    freezeReactiveValue(input,"Groups")
    updateCheckboxGroupInput(session, "Groups", choices = levels(as.factor(dataset$Group)), selected = levels(as.factor(dataset$Group)))
    freezeReactiveValue(input,"Var1")
    updateSelectInput(session, "Var1", choices = names(select_if(dataset,is.numeric)),selected = "FrCtx.AT8.Class3.OD")
    freezeReactiveValue(input,"Var2")
    updateSelectInput(session, "Var2", choices = names(select_if(dataset,is.numeric)), selected = "FrCtx.AT8.Class4.OD")
  })

  dataset_plot <- reactive({
    dataset <- datasetInput()
    dat <- dataset[c(input$Var1, input$Var2,"Group","Color","Mouse.ID")]
    colnames(dat) <- c("Var1","Var2","Group","Color","Id")
    dat <- dat[dat$Group %in% input$Groups,]
    dat <- na.omit(dat)
    return(dat)
  })

  data_color <- reactive({
    dataset <- datasetInput()
    dat <- dataset[c(input$Var1, input$Var2,"Group","Color","Mouse.ID")]
    colnames(dat) <- c("Var1","Var2","Group","Color","Id")
    order_color <- levels(as.factor(dat$Color))
    names(order_color) <- levels(as.factor(dat$Group))
    dat <- dat[dat$Group %in% input$Groups,]
    dat <- na.omit(dat)
    order_color <- order_color[names(order_color) %in% input$Groups]
    return(order_color)
  })

  data_point <- reactive({
    input$plot_click
    dataset <- datasetInput()
    dat <- dataset[c(input$Var1, input$Var2,"Group","Color","Mouse.ID")]
    colnames(dat) <- c("Var1","Var2","Group","Color","Id")
    dat <- dat[dat$Group %in% input$Groups,]
    dat <- na.omit(dat)
    colnames(dat) <- c(input$Var1,input$Var2, "Group","Color","Mouse ID")
    dat_1 <- nearPoints(dat, coordinfo=input$plot_click, xvar=input$Var1, yvar = input$Var2)
    dat_1 <- dat_1[,c(1,2,3,5)]
    dat_1 <- dat_1[,c(4,3,1,2)]
    colnames(dat_1) <- c("Mouse Id", "Group","xx","yy")
    return(dat_1)
  })

  my_plot1 <- function(){
    input$plot_click
    order_color <- data_color()
    dat <- dataset_plot()
    dat_points <- data_point()
    ggplot(dat,aes(y=Var2, x=Var1,color = Group)) + geom_point(size= 3.5) + scale_y_continuous(input$lab_y) + scale_x_continuous(input$lab_x) + theme(axis.title=element_text(size=15))+
        theme_bw()+ scale_color_manual(values = order_color, name = "Group", labels = names(order_color)) +
        theme(legend.position = "bottom") +
        labs(title = paste("Correlation plot of: ",input$lab_y, "on the Y-axis and ", input$lab_x, "on the X-axis")) +
        geom_point(data = data_point(), aes(x=xx,y=yy),size = 5)

  }

  my_plot2_no <- function(){
    dat <- dataset_plot()
    order_color <- data_color()

    if(input$cohort == FALSE){

      p1 <- ggplot(dat,aes(x=Group,y=Var1,color=Group)) + geom_sina(size=3.5) + stat_summary(fun.data=mean_sdl,fun.args=list(mult=1),geom="errorbar",width=0.3,size=1.2) +
        stat_summary(fun=base::mean,geom="crossbar",width=0.8) + scale_y_continuous(input$lab_x)+ scale_x_discrete(" ",labels = names(order_color)) +
        theme_bw() + scale_color_manual(values = order_color) +
        theme(legend.position = "none") +
        labs(title = paste("Plot of: ", input$lab_x))

      p2 <- ggplot(dat,aes(x=Group,y=Var2,color=Group)) + geom_sina(size=3.5) + stat_summary(fun.data=mean_sdl,fun.args=list(mult=1),geom="errorbar",width=0.3,size=1.2) +
        stat_summary(fun=base::mean,geom="crossbar",width=0.8) + scale_y_continuous(input$lab_y)+ scale_x_discrete("", labels = names(order_color)) +
        theme_bw() +  scale_color_manual(values = order_color) +
        theme(legend.position = "none") +
        labs(title = paste("Plot of: ", input$lab_y))

      plot_grid(p1 ,p2 )
    }else{

      p1 <- ggplot(dat,aes(x=Group,y=Var1,colour= Group)) + geom_sina(size=3.5) + stat_summary(fun.data=mean_sdl,fun.args=list(mult=1),geom="errorbar",width=0.3,size=1.2) +
        stat_summary(fun=base::mean,geom="crossbar",width=0.8) + scale_y_continuous(input$lab_x) + scale_x_discrete("") +
        theme_bw()+ scale_color_manual(values = order_color, labels = names(order_color), name = "Group") +theme(legend.position = "bottom",axis.text.x=element_blank(),axis.title=element_text(size=15)) +
        labs(title = paste("Plot of: ", input$lab_x)) + facet_wrap(~Cohort, ncol=3)

      p2 <- ggplot(dat,aes(x=Group,y=Var2,colour= Group)) + geom_sina(size=3.5) + stat_summary(fun.data=mean_sdl,fun.args=list(mult=1),geom="errorbar",width=0.3,size=1.2) +
        stat_summary(fun=base::mean,geom="crossbar",width=0.8) + scale_y_continuous(input$lab_y) + scale_x_discrete("") +
        theme_bw()+ scale_color_manual(values = order_color, labels = names(order_color), name = "Group")+ theme(legend.position = "bottom",axis.text.x=element_blank(),axis.title=element_text(size=15)) +
        facet_wrap(~Cohort, ncol=3)

      plot_grid(p1,p2)
    }
  }

  my_plot2_sqrt <- function(){
    dat <- dataset_plot()
    order_color <- data_color()

    if(input$cohort == FALSE){

      p1 <- ggplot(dat,aes(x=Group,y=sqrt(Var1),color=Group)) + geom_sina(size=3.5) + stat_summary(fun.data=mean_sdl,fun.args=list(mult=1),geom="errorbar",width=0.3,size=1.2) +
        stat_summary(fun=base::mean,geom="crossbar",width=0.8) + scale_y_continuous(paste("Square root of",input$lab_x)) + scale_x_discrete(" ",labels = names(order_color)) +
        theme_bw() + scale_color_manual(values = order_color) +
        theme(legend.position = "none") +
        labs(title = paste("Plot of: ", input$lab_x))

      p2 <- ggplot(dat,aes(x=Group,y=sqrt(Var2),color=Group)) + geom_sina(size=3.5) + stat_summary(fun.data=mean_sdl,fun.args=list(mult=1),geom="errorbar",width=0.3,size=1.2) +
        stat_summary(fun=base::mean,geom="crossbar",width=0.8)  + scale_y_continuous(paste("Square root of",input$lab_y)) + scale_x_discrete("", labels = names(order_color)) +
        theme_bw() +  scale_color_manual(values = order_color) +
        theme(legend.position = "none") +
        labs(title = paste("Plot of: ", input$lab_y))

      plot_grid(p1 ,p2 )
    }else{

      p1 <- ggplot(dat,aes(x=Group,y=sqrt(Var1),colour= Group)) + geom_sina(size=3.5) + stat_summary(fun.data=mean_sdl,fun.args=list(mult=1),geom="errorbar",width=0.3,size=1.2) +
        stat_summary(fun=base::mean,geom="crossbar",width=0.8) + scale_y_continuous(paste("Square root of",input$lab_x)) + scale_x_discrete("") +
        theme_bw()+ scale_color_manual(values = order_color, labels = names(order_color), name = "Group") +theme(legend.position = "bottom",axis.text.x=element_blank(),axis.title=element_text(size=15)) +
        labs(title = paste("Plot of: ", input$lab_x)) + facet_wrap(~Cohort, ncol=3)

      p2 <- ggplot(dat,aes(x=Group,y=sqrt(Var2),colour= Group)) + geom_sina(size=3.5) + stat_summary(fun.data=mean_sdl,fun.args=list(mult=1),geom="errorbar",width=0.3,size=1.2) +
        stat_summary(fun=base::mean,geom="crossbar",width=0.8) + scale_y_continuous(paste("Square root of",input$lab_y)) + scale_x_discrete("") +
        theme_bw()+ scale_color_manual(values = order_color, labels = names(order_color), name = "Group")+ theme(legend.position = "bottom",axis.text.x=element_blank(),axis.title=element_text(size=15)) +
        facet_wrap(~Cohort, ncol=3)

      plot_grid(p1,p2)
    }
  }

  my_plot2_log <- function(){
    dat1 <- dataset_plot()
    order_color <- data_color()

    if(input$cohort == FALSE){

      p1 <- ggplot(dat,aes(x=Group,y=log(Var1),color=Group)) + geom_sina(size=3.5) + stat_summary(fun.data=mean_sdl,fun.args=list(mult=1),geom="errorbar",width=0.3,size=1.2) +
        stat_summary(fun=base::mean,geom="crossbar",width=0.8) + scale_y_continuous(paste("Log of",input$lab_x)) + scale_x_discrete(" ",labels = names(order_color)) +
        theme_bw() + scale_color_manual(values = order_color) +
        theme(legend.position = "none") +
        labs(title = paste("Plot of: ", input$lab_x))

      p2 <- ggplot(dat,aes(x=Group,y=log(Var2),color=Group)) + geom_sina(size=3.5) + stat_summary(fun.data=mean_sdl,fun.args=list(mult=1),geom="errorbar",width=0.3,size=1.2) +
        stat_summary(fun=base::mean,geom="crossbar",width=0.8)  + scale_y_continuous(paste("Log of",input$lab_y)) + scale_x_discrete("", labels = names(order_color)) +
        theme_bw() +  scale_color_manual(values = order_color) +
        theme(legend.position = "none") +
        labs(title = paste("Plot of: ", input$lab_y))

      plot_grid(p1 ,p2 )
    }else{

      p1 <- ggplot(dat,aes(x=Group,y=log(Var1),colour= Group)) + geom_sina(size=3.5) + stat_summary(fun.data=mean_sdl,fun.args=list(mult=1),geom="errorbar",width=0.3,size=1.2) +
        stat_summary(fun=base::mean,geom="crossbar",width=0.8) + scale_y_continuous(paste("Log of",input$lab_x)) + scale_x_discrete("") +
        theme_bw()+ scale_color_manual(values = order_color, labels = names(order_color), name = "Group") +theme(legend.position = "bottom",axis.text.x=element_blank(),axis.title=element_text(size=15)) +
        labs(title = paste("Plot of: ", input$lab_x)) + facet_wrap(~Cohort, ncol=3)

      p2 <- ggplot(dat,aes(x=Group,y=log(Var2),colour= Group)) + geom_sina(size=3.5) + stat_summary(fun.data=mean_sdl,fun.args=list(mult=1),geom="errorbar",width=0.3,size=1.2) +
        stat_summary(fun=base::mean,geom="crossbar",width=0.8) + scale_y_continuous(paste("Log of",input$lab_y)) + scale_x_discrete("") +
        theme_bw()+ scale_color_manual(values = order_color, labels = names(order_color), name = "Group")+ theme(legend.position = "bottom",axis.text.x=element_blank(),axis.title=element_text(size=15)) +
        facet_wrap(~Cohort, ncol=3)

      plot_grid(p1,p2)
    }
  }

  output$plot1 <- renderPlot(my_plot1())

  output$plot2 <- renderPlot({
    if(input$transformation == "no"){
      my_plot2_no()
    } else if(input$transformation == "sqrt"){
      my_plot2_sqrt()
    } else{
      my_plot2_log()
    }
  })

  output$downloadPlot1 <- downloadHandler(
    filename =function(){
      paste("plot-",paste(input$lab_x,"-", input$lab_y),".png")
    },
    content=function(file){
      ggsave(file,my_plot1())
    }
  )

  output$downloadPlot2 <- downloadHandler(
    filename =function(){
      paste("plot-",input$lab_x,".png")
    },
    content=function(file){
      ggsave(file,output$plot2)
    }
  )

  output$info <- renderTable({
    req(input$plot_click,cancelOutput = TRUE)
    dat <- data_point()
    colnames(dat) <- c("Mouse Id", "Group", input$lab_x, input$lab_y)
    print(dat)
  })

  output$summary <- renderTable({
    dat <- dataset_plot()
    cor <- c()
    pvalue <- c()
    con_int_lower <- c()
    con_int_upper <- c()
    names <- c()
    for(j in 1:length(input$Groups)){
      dat__ <- dat[dat$Group == input$Groups[j],]
      colnames(dat__) <- c("Var1","Var2","Group")
      dat__stat <- cor.test(dat__$Var1,dat__$Var2)
      cor[j] <- dat__stat$estimate
      pvalue[j] <- dat__stat$p.value
      con_int_lower[j] <- dat__stat$conf.int[1]
      con_int_upper[j] <- dat__stat$conf.int[2]
      names[j] <- input$Groups[j]
    }
    dat_stat <- cor.test(dat$Var1, dat$Var2)
    cor <- c(cor,dat_stat$estimate)
    pvalue <- c(pvalue, dat_stat$p.value)
    con_int_lower <- c(con_int_lower, dat_stat$conf.int[1])
    con_int_upper <- c(con_int_upper, dat_stat$conf.int[2])
    names <- c(names,"Overall")
    data_fin <- data.frame(names,cor,pvalue,con_int_lower,con_int_upper)
    data_fin$cor <- format(round(data_fin$cor,3),nsmall=3)
    data_fin$pvalue <- format(round(data_fin$pvalue,3),nsmall=3)
    data_fin$con_int_lower <- format(round(data_fin$con_int_lower,3),nsmall=3)
    data_fin$con_int_upper <- format(round(data_fin$con_int_upper,3),nsmall=3)
    colnames(data_fin) <- c("Group","Spearman's rho", "P-value", "CL lower", "CL upper")
    print(data_fin)
  })

  }

shinyApp(ui = ui, server = server)


text:
Q: Cutting off tetrahedral corners off a cube... Problem:

Solution:

The part I don't get is circled in red - why is the side length of the tetrahedron equal to square root 2? If the tetrahedra meet at the midpoints of the cube, then surely the side length of the tetrahedron is equal to 1?
Apologies if I am being obtuse - could someone clarify? Many thanks.


text:
Q: Recuperar chave e valor de campo específico no Firebase Por favor, gostaria de recuperar apenas a chave e o email da lista, ignorando os demais "campos". Queria ter uma lista, sem carregar todos os valores de todos os nós, como tenho feito ultimamente.
Como conseguir isso com javascript ?

A: Não existe esta opção. O que você pode fazer é mapear somente estes campos com um Json só para este fim, e passar a gravar os registros tanto na estrutura completa quanto na que estou propondo. Desta forma terá duas estruturas disponíveis para leitura/gravação.


text:
Q: Create list with unique id in Java and manipulate it I want to create a programm that creates a list that looks like this
ID: 1
Name: Example
Surname: Example
email: example

//New list

ID: 2
Name: Example
Surname: Example
email: example

and then when i want to change something (like Name: ) i'd like to change it by id, so it can only be changed inside the list with ID: 2

A: You should use a HashMap.
Create a class (let's class it YourClass) that contains ID, name, surname and email instance variables.
Then create a HashMap where the key is the identifier and the value is YourClass:
Map<Integer,YourClass> map = new HashMap<>();
map.put(objectOfYourClassWithID1.getID(),objectOfYourClassWithID1);
map.put(objectOfYourClassWithID2.getID(),objectOfYourClassWithID2);
if (map.containsKey(2)) {
    map.get(2).setSomeProperty(newValue); // this will only change the object whose ID is 2
}

A: you can create class like this
public class Record{
    private int id;
    private String name;
    private String Surname;
    private String email;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getSurname() {
        return Surname;
    }

    public void setSurname(String surname) {
        Surname = surname;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

and then use it like this:
    Record record1 = new Record();
    record1.setId(1);
    record1.setName("example");
    record1.setSurname("example");
    record1.setEmail("example");

    Record record2 = new Record();
    record2.setId(2);
    record2.setName("example");
    record2.setSurname("example");
    record2.setEmail("example");

    Map<Integer,Record> recordMap = new HashMap<Integer, Record>();
    recordMap.put(record1.getId(),record1);
    recordMap.put(record2.getId(),record2);]

    recordMap.get(2).getName();//example
    recordMap.get(2).setName("ebi");
    recordMap.get(2).getName();//ebi

A: import java.util.ArrayList;
import java.util.List;

public class Person {

private int id;
private String name;
private String Surname;
private String email;

public Person(int id, String name, String surname, String email) {
    super();
    this.id = id;
    this.name = name;
    Surname = surname;
    this.email = email;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

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

public String getSurname() {
    return Surname;
}

public void setSurname(String surname) {
    Surname = surname;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public static void main(String[] args) {

    List<Person> list = new ArrayList<Person>();
    list.add(new Person(1, "example", "example", "example"));
    list.add(new Person(2, "example", "example", "example"));
  }

 }


text:
Q: Select nested data using crosstalk and filter_select I have a nested data.frame that looks similar to this example. I want to use crosstalk filter_select to return the nested plot from the 'selected' Species. How do I access the 'selected' shared data in crosstalk?
    library(tidyverse)
    library(crosstalk)

    irisplot= iris %>%
      group_by(Species) %>%
      nest %>%
      mutate(plot = map2(Species, data,  function (.x,.y){
      ggplot(data = .y, aes(x =  Sepal.Length, y = Sepal.Width)) +
      geom_smooth() +
      ggtitle(label = .x) }))

    shared_df1 <- SharedData$new(irisplot, ~Species, group = "Choose")

    bscols(
    filter_select("species",
    "Species:",shared_df1,~Species,multiple=FALSE),

    shared_df1$data$plot ## does not work. What should this be?

    )


text:
Q: X11 change screen orientation Debian I want to change screen orientation between portrait and landscape, through Debian command line, shell script or C code. Windowing system is X11. I have searched the Web but without success.
xrandr -o left

Response:

X Error of failed request:  BadMatch (invalid parameter attributes)
  Major opcode of failed request:  140 (RANDR)
  Minor opcode of failed request:  2 (RRSetScreenConfig)
  Serial number of failed request:  14
  Current serial number in output stream:  14

If I want do anything with xrandr it shows "xrandr: Failed to get size of gamma for output default" only.
LCD is connected on LVDS connector. My xorg.conf is
Section "ServerFlags"
    Option "BlankTime"  "0"
    Option "StandbyTime"  "0"
    Option "SuspendTime"  "0"
    Option "OffTime"  "0"
EndSection

Section "Device"
    Identifier      "fbdev display"
    Driver          "fbdev"
    #Option "Rotate" "CCW"
    Option "Rotate" "RandRRotation" "On"
EndSection

Is it possible to rotate my display?

A: Not all X11 drivers supports Xrandr API. Some drivers do not support changing this at runtime at all, while others have non-standard ways to perform this. An example would be a binary closed source driver with its own utility.

A: There are many graphical front-ends to xrandr, that simplify its use.  These front-ends may not always be available, especially when using more minimalist window managers.
For those situations, it's handy to know some options that can be used to avoid the overhead of installing multiple libraries and unwanted cruft.
Some useful options
$ xrandr -q # With one monitor connected

Screen 0: minimum 320 x 200, current 3286 x 1080, maximum 16384 x 16384
LVDS connected 1366x768+0+0 (normal left inverted right x axis y axis) 344mm x 194mm
   1366x768       60.0*+
   1280x720       59.9
   1152x768       59.8
   1024x768       59.9
   800x600        59.9
   848x480        59.7
   720x480        59.7
   640x480        59.4
VGA-0 disconnected (normal left inverted right x axis y axis)

After attaching a second monitor we also get this listed:

HDMI-0 connected 1920x1080+1366+0 (normal left inverted right x axis y axis) 16mm x 9mm
   1920x1080i     30.0 +   25.0     30.0
   1920x1080      24.0*    24.0
   1280x720       60.0     50.0     59.9
   1024x768       75.1     70.1     60.0
   1440x480i      30.0
   832x624        74.6
   800x600        72.2     75.0     60.3     56.2
   720x576        50.0
   720x576i       25.0
   720x480        60.0     59.9
   720x480i       30.0     30.0
   640x480        75.0     72.8     66.7     60.0     59.9

Some useful options

*

*--auto      Enable connected monitor with preferred mode

*--mode mode Set the resolution, using a value reported with xrandr -q

*--rate rate     Set the refresh rate

*--left-of --right-of --above --below --same-as
            Set the position of a monitor relative to another

*--off           Turn output to monitor off

Some toys
Use normal to restore normality.  Each command is relative to normal, so 4 rotates right wont fully rotate, each will duplicate the first command... try it!

*

*--reflect <normal|x|y|xy>

*--rotate <normal|left|right|inverted>


text:
Q: Authenticating and using a Google Spreadsheet as a database for a web app There seem to be many questions in around this topic but none seem to answer my question. I have a simple website with a signup form, and when users enter their email I want to push this as a new row in a Google Spreadsheet I have already setup. I don't want the user to authenticate or even know about this spreadsheet. How do I authenticate so I can start using the Google API? Code/pseudocode would be greatly appreciated! Here are some examples that do not answer my question:
Using Google Spreadsheet as DB for apps
Google spreadsheet as db for web applications

A: Here's a link to a library for accessing Google Spreadsheets:
https://github.com/EastCloud/node-spreadsheets
Note: Ive not actually used this lib

A: You will need to use PHP and the Zend GData Library.
When you post your form to your PHP script, you'll need to collect all of the variables into an associative array that you then pass to the insertRow method of Zend_Gdata_Spreadsheets.
It's important to note that your spreadsheet must contain column headers for my example to work. E.g. First Name / Last Name and it's important to note that when you target these column headers in a script, they will need to be all lowercase and stripped of spaces because this is how the spreadsheet expects them.
Here is a basic example of the PHP script:
<?php
        $errors = array(); // use this to create an associative array to json encode and send back any errors
        $rowData = array(); // this will be the associative array that gets passed to the insertRow method

        $firstName = $_POST['firstName'];

        if(isset($firstName)){
            $rowData['firstname'] = $firstName; // note the key 'firstname' must equal the column header in your spreadsheet which you are inserting the value into. the column header name key should be all lowercase and not contain spaces regardless of if you have it in the spreadsheet
        }else{
            $errors['firstname'] = '1';
        }

        $lastName = $_POST['lastName'];

        if(isset($lastName)){
            $rowData['lastname'] = $lastName; // note the key 'lastname' must equal the column header in your spreadsheet which you are inserting the value into. the column header name key should be all lowercase and not contain spaces regardless of if you have it in the spreadsheet
        }else{
            $errors['lastname'] = '1';
        }

        set_include_path($_SERVER['DOCUMENT_ROOT'] . '/library/');

        $spreadsheetKey = 'your-spreadsheet-key';
        $worksheetId = 'your-worksheet-id'; // if you only have one worksheet this will be 'od6'

        require_once 'Zend/Loader/Autoloader.php';
        $autoloader = Zend_Loader_Autoloader::getInstance();
        $autoloader->setFallbackAutoloader(true);

        $user = "your-user-name-at-gmail-dot-com";
        $pass = "your-password";

        $service = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
        $client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
        $spreadsheetService = new Zend_Gdata_Spreadsheets($client);

        $query = new Zend_Gdata_Spreadsheets_DocumentQuery();
        $query->setSpreadsheetKey($spreadsheetKey);
        $feed = $spreadsheetService->getWorksheetFeed($query);

        global $spreadsheetService,$spreadsheetKey,$worksheetId,$rowData;
        $insertedListEntry=$spreadsheetService->insertRow($rowData,$spreadsheetKey,$worksheetId);
        $returnObject['success'] = 'true';
        echo(json_encode($returnObject));
?>

Let me know if this works for you.


text:
Q: Close the already opened Custom menu handler when click on Cefsharp webbrowser container I am developing WPF application using cefsharp chromium web browser as a browser control. In my App, when right click on the Cefsharp browser I would like to show some controls and I am able to show the controls. When I right click, open the custom menu and click on container then I am not able to close the custom menu.
My Code is
 _cefchrbrowser.Address = _address;
 _cefchrbrowser.MenuHandler = new CustomMenuHandler();

My Class is
public class CustomMenuHandler : IContextMenuHandler
{
    public void OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model)
    {
        model.Remove(CefMenuCommand.ViewSource);
        model.Remove(CefMenuCommand.Print);
        model.Remove(CefMenuCommand.Undo);
        model.Remove(CefMenuCommand.Redo);
    }

    public bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
    {
        return false;
    }

    public void OnContextMenuDismissed(IWebBrowser browserControl, IBrowser browser, IFrame frame)
    {

    }

    public bool RunContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model, IRunContextMenuCallback callback)
    {
        return false;
    }
}

Without selecting any custom menu item when I click on browser, I am not able to close the menu.


text:
Q: Change class via JQuery not working on Websocket message I've been stuck on a small problem for a while now. I have spring websockets via stomp client set up and I receive the message and try to call a simple removeClass() / addClass() / css() operation on a specific element.
Here's the relevant code:
// Function called on page load
function connectToConfirm() {
    var sck = new SockJS('/endpoint');
    sClient = Stomp.over(sck);
    sClient.connect({}, function(frame) {
        console.log('Connected: ' + frame);
        sClient.subscribe('/test', function(readyConfirmation) {
            setReady(JSON.parse(readyConfirmation.body));
        });
    });
}

function setReady(content) {
    $('#readyIndicator-'+content.id)
        .addClass('fa-check')
        .removeClass('fa-times')
        .css('color', 'green');
    console.log("ID: " +content.id);
    // Displays the correct id and shows the function gets called
    console.log("Object exists?: " +$('#readyIndicator-'+content.id).length);
    // Displays "1", therefore an element by that id exists.

}

HTML with Thymeleaf. ${group} object gets added via a HandlerInterceptorAdapter implementation and the values are displayed correctly:

    Username

I have a button that sends a message to the server and it gets returned properly, e.g.:
>>> SEND
destination:/app/myMapping/foo
content-length:20

.. and I get the reply:
<<< MESSAGE
destination:/test
content-type:application/json;charset=UTF-8
subscription:sub-1
message-id:ffbazdj4-82
content-length:84

{"id":"123", .. , ..}

So yeah, the function gets called but the class does not get updated, even though the element exists. I'm really lost why this could ever happen. To make matters worse, I have a similar implementation in another project that works just fine. The only difference I really see is that the object gets added directly to the model in the controller instead of in the postHandle() method.


text:
Q: How to create pie chart with only 1 series data and have background be a circle Ok, using highcharts and I need to create a pie chart with only 1 data and the rest of the circle is a gray line that does not do anything.  Is there anyways to do this?  Currently, with the following code I have I have to set a data point so that it contains a percentage, but not able to disable the gray section in this pic:

But I need the gray section to not be able to be selected, and would help if it looked more like the design in the sense that the gray part is thinner.  Design here:

My current options for this pie chart is as follows:
    {
   "chart":{
      "renderTo":"amenity-0",
      "plotBackgroundColor":null,
      "plotBorderWidth":0,
      "plotShadow":false,
      "height":220,
      "marginBottom":40,
      "spacingBottom":30
   },
   "title":{
      "text":"Amenity 1",
      "align":"center",
      "verticalAlign":"bottom",
      "y":15
   },
   "credits":{
      "enabled":false
   },
   "tooltip":{
      "headerFormat":"",
      "pointFormat":"{point.name}: {point.percentage:.1f}%"
   },
   "plotOptions":{
      "pie":{
         "dataLabels":{
            "enabled":true,
            "distance":-50,
            "style":{
               "fontWeight":"bold",
               "color":"white"
            }
         },
         "startAngle":0,
         "endAngle":360,
         "center":[
            "50%",
            "50%"
         ],
         "size":"100%"
      }
   },
   "series":[
      {
         "type":"pie",
         "name":"Amenity 1",
         "innerSize":"60%",
         "data":[
            {
               "name":"Amenity 1",
               "y":69,
               "color":"#C1AFBD",
               "dataLabels":{
                  "enabled":false
               }
            },
            {
               "name":"Gray Section",
               "y":31,
               "color":"#E9EDF0",
               "dataLabels":{
                  "enabled":false
               }
            }
         ]
      }
   ]
}

I have tried using the pointFormatter function instead of pointFormat and returning false if the point.name === 'Gray Section', but this did not remove the tooltip.  It just created a blank tooltip.  In any case, I would like for the gray section to be thinner like in the design and not to be part of the data if possible.
Is this possible?  Any ideas on how to achieve this exactly?  Thanks guys/gals.

A: Regarding the tooltip, you could use some sort of condition for the general tooltip.formatter to disable the tooltip for a given point, like setting noTooltip for the given point. For example (JSFiddle):
tooltip: {
    formatter: function() {
        if(!this.point.noTooltip) {
            return '●' +
                this.series.name + '
' +
                'Value: ' + this.point.y + '
';
        }

        return false;
    },
    hideDelay: 0
},
series: [{
    data: [{
        y: 70
    }, {
        y: 30,
        noTooltip: true
    }]
}]

Regarding the thinner gray section you could use a variablepie instead and set different z values to make the actual value stand out more. For example (JSFiddle):
chart: {
    type: 'variablepie'
},
series: [{
    innerSize: '40%',
    zMin: 0,
    zMax: 100,
    data: [{
        y: 70,
        z: 10,
    }, {
        y: 30,
        z: 0.1,
        color: 'lightgray'
    }]
}]

It requires the following module imported:


text:
Q: Composing Music for Dholak Instrument in Jfugue I compose music in java with JFUGUE. Jfugue contains some Indian instruments like Sitar and Shanai etc., but I need to compose for Dholak or Tabla (percussion instruments), which are not enlisted in the list of 127 instruments in Jfugue. Is there any way or method to add or replace my needed instrument in Jfugue?

A: JFugue uses the same instruments that are defined by the MIDI standard. You may be able to find a Dholak or Tabla instrument as a SoundFont, which you can load into Java if you are using the Gervill synthesizer (or versions of Java that include the Gervill implementation, which are JDK 7 and later).
See also: Can we create our own composition using Soundfont and JFugue?


text:
Q: Partial derivative of function $\mid xy \mid + \sin{xy}$ I need to consulte one problem, just to control my result and see if I'm/ I'm not right:
I want to find
$$\frac{\partial f}{\partial x}(0,0), $$ where $f(x,y) = \mid xy \mid +\sin{xy}$ for $x,y \in \Re$
Because of the absolute value which hasn't got two-sided derivation in 0, I have to try to find it from definition of partial derivative in (0,0), which is defined as this limit
$$\lim_{t \to 0} \frac{\mid (t+x)0\mid + \sin{(x+t)0} -0}{t} = \lim_{t \to 0} \frac{0}{t} = 0$$.
So because the limit exists, the partial derivation exists and it is equal to 0.
Am I right, or is there some problem that I don't see?
Thank you very much!

A: You have a little mistake: you should write
$$\frac{\partial f}{\partial x}(0,0)=\lim_{t\to0}\frac{f(t,0)-f(0,0)}{t}=\lim_{t\to0}\frac{0}{t}=0$$


text:
Q: How to resolve this error in react native? ERROR: http could not be found within the project or in these directories: node_modules [enter image description here](https://i.stack.imgur.com/MY5Rn.png)
 BUNDLE  ./index.js

error: Error: Unable to resolve module http from /home/divum/Param/param-wallet-mobile/node_modules/https-browserify/index.js: http could not be found within the project or in these directories:
  node_modules
  ../../node_modules

If you are sure the module exists, try these steps:
 1. Clear watchman watches: watchman watch-del-all
 2. Delete node_modules and run yarn install
 3. Reset Metro's cache: yarn start --reset-cache
 4. Remove the cache: rm -rf /tmp/metro-*
> 1 | var http = require('http')
    |                     ^
  2 | var url = require('url')
  3 |
  4 | var https = module.exports
    at ModuleResolver.resolveDependency (/home/divum/Param/param-wallet-mobile/node_modules/metro/src/node-haste/DependencyGraph/ModuleResolution.js:129:15)
    at DependencyGraph.resolveDependency (/home/divum/Param/param-wallet-mobile/node_modules/metro/src/node-haste/DependencyGraph.js:288:43)
    at Object.resolve (/home/divum/Param/param-wallet-mobile/node_modules/metro/src/lib/transformHelpers.js:129:24)
    at resolve (/home/divum/Param/param-wallet-mobile/node_modules/metro/src/DeltaBundler/traverseDependencies.js:396:33)
    at /home/divum/Param/param-wallet-mobile/node_modules/metro/src/DeltaBundler/traverseDependencies.js:412:26
    at Array.reduce (<anonymous>)
    at resolveDependencies (/home/divum/Param/param-wallet-mobile/node_modules/metro/src/DeltaBundler/traverseDependencies.js:411:33)
    at processModule (/home/divum/Param/param-wallet-mobile/node_modules/metro/src/DeltaBundler/traverseDependencies.js:140:31)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)

I tried these steps :

*

*Clear watchman watches: watchman watch-del-all

*Delete node_modules and run yarn install

*Reset Metro's cache: yarn start --reset-cache

*Remove the cache: rm -rf /tmp/metro-*

I also tried cleaning my gradle ( ./gradlew clean) & cleared the cache and restarted again (npx react-native start --reset-cache , npx react-native run-android)
Please help me out , this error keeps on poping up to me. I can't even run my project because of this issue.


text:
Q: Why do we get (undesired) arrow head at start of arrow? I tried drawing an arrow between two nodes, and wanted to use the east anchor and found a strange behaviour: If you add that anchor it seems you get an additional arrow head pointing in some strange direction, but I couldn't find any explanation on why you should get this. Can anyone elaborate why we do get this additional arrow head and how one would go about removing it?
I tried demonstrating this effect with a minimal example: The arrow between a and b has a head at a (which I was referring to above). I expected that this arrow should have no arrow head there and should look exactly like the arrow between c and d.
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{shapes.geometric}
\begin{document}
\begin{tikzpicture}
\node[circle, draw] (a) at (0,0) {a};
\node[circle, draw] (b) at (1,0) {b};
\draw[->] (a.east) edge (b);
\node[circle, draw] (c) at (0,-1) {c};
\node[circle, draw] (d) at (1,-1) {d};
\draw[->] (c) edge (d);
\end{tikzpicture}
\end{document}

Here the corresponding screenshot:

A:
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{shapes.geometric}
\begin{document}
\begin{tikzpicture}
\node[circle, draw] (a) at (0,0) {a};
\node[circle, draw] (b) at (1,0) {b};
\draw[->] (a.east) to (b);
\node[circle, draw] (c) at (0,-1) {c};
\node[circle, draw] (d) at (1,-1) {d};
\draw[->] (c) to (d);
\end{tikzpicture}
\end{document}


text:
Q: Can I create custom pivot table name using another M:M entity? I'm still thinking is there a ways how can I create a custom pivot table name? Because I created a documents and users table has a many to many relationship with document_user which is my pivot table and this table was created for received document that user created. And I'm planning to create a another pivot table for document and user this table was for sent documents so I can have history. See my code below.
create_document_user_table
public function up()
 {
    Schema::create('document_user',function (Blueprint $table)
    {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->integer('document_id')->unsigned();

        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->foreign('document_id')->references('id')->on('documents')->onDelete('cascade');

        $table->unsignedInteger('sender_id')->nullable();
        $table->foreign('sender_id')->references('id')->on('users')->onDelete('cascade');

        $table->dateTime('dateReceived')->default(DB::raw('CURRENT_TIMESTAMP'));
        $table->timestamp('dateModified')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
    });
 }

documents_table
public function up()
{
    Schema::create('documents', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->text('content');
        $table->integer('category_id')->unsigned();
        $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
        $table->timestamps();
    });
}

users_table
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('first_name');
        $table->string('last_name');
        $table->string('middle_name');
        $table->string('email');
        $table->string('username');
        $table->string('address');
        $table->string('password');
        $table->string('remember_token');

        $table->integer('role_permission_id')->unsigned();

        $table->foreign('role_permission_id')->references('id')->on('roles_permissions_dt')->onDelete('cascade');
        $table->timestamps();
    });
}

This works well inserting records to my pivot table. What I'm planning to achieve is every-time I inserted a records for documents this will inserted too in my custom pivot table not only in my document_user pivot table. Any help would appreciated! Thanks for your info or tips.
UPDATE
@Mina thanks for the tips that you given but actually this is my insert or save for my pivot table. How can I inserted this in my revisions table?
DocumentController
public function postDocuments(Request $request)
{

    $this->validate($request,
    [
        'title' => 'required|regex:/(^[A-Za-z0-9 ]+$)+/|max:255',
        'content' => 'required',
        'category_id' => 'required',
        'recipient_id' => 'required',
    ]);

    $document = new Document();
                                //Request in the form
    $document->title = $request->title;
    $document->content = $request->content;
    $document->category_id = $request->category_id;

    $document->save();
    $user = Auth::user();

    foreach($request->recipient_id as $recipientId)
    {
        $document->recipients()->sync([ $recipientId => ['sender_id' => $user->id]],false );
    }

    return redirect()->back();
}

A: You do not need another pivot table. You need a table like that:
public function up()
{
    Schema::create('revisions', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('document_id')->unsigned();
        //Rest of table structure

        $table->foreign('document_id')->references('id')->on('document_user')->onDelete('cascade');
        $table->timestamps();
    });
}

When you need to create a new Revision:
$document = new Document;
//add $document attributes
$user->documents()->save($document);

$document->recipients->each(function($recipient){
      $id = $recipient->pivot->id;
      Revision::create(['document_id'=>$id]);
})

A: You can call your pivot tables as you like.

As mentioned previously, to determine the table name of the
  relationship's joining table, Eloquent will join the two related model
  names in alphabetical order. However, you are free to override this
  convention. You may do so by passing a second argument to the
  belongsToMany method:
return $this->belongsToMany('App\Role', 'user_roles');

(Eloquent: Relationships #Many To Many)
In your case you would need to define the relations like this:
class User extends Model
{
    // other stuff

    createdDocuments()
    {
        return $this->belongsToMany('App\Document', 'document_user_created');
    }

    sentDocuments() // or receivedDocuments()
    {
        return $this->belongsToMany('App\Document', 'document_user_sent');
    }

    // other stuff
}

class Document extends Model
{
    // other stuff

    createdByUsers()
    {
        return $this->belongsToMany('App\User', 'document_user_created');
    }

    sentToUsers() // or sentFromUsers() or whatever it does mean
    {
        return $this->belongsToMany('App\User', 'document_user_sent');
    }

    // other stuff
}


text:
Q: What permissions does my application have, starting up on boot? (HKLM\...\Run) My application is starting up on boot, because it's registered in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run.
I can't change that right now, but I'm clearly running into permission problems, that prevent me from creating files in some folders.
My application runs fine when started manually by the user (without admin permissions). But it can't create files when it is started automatically on boot.
So my question is: What permissions exactly does an application have, when it is started automatically? Is this documented somewhere?
I just read somewhere that it might run as a Non- or Least-Privileged User. Still, I'm wondering what permissions they might have, since I don't find this well documented.
I'm running VS2017, C# .NET 4.0, Windows 10 1803, if that's important.

A: An application registered under

*

*HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

*HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

Both cause a program to run when a user logs in. The program runs with the permissions of the user that is logging in.

A: I had a similar problem. I fixed it by checking the path used to write the target file. First, I use only the target file name. In this way, the system uses the directory path from where you launch the app. (I don't know where that is.) Then, I used the full app .exe file name, including file path, minus the .exe's file name, thus getting the app's .exe file path. In this way, I can be sure where the app writes the target file. (The app's .exe directory.)
For example, c:\myfolder\myapp.exe - myapp.exe = c:\myfolder\.
Using:
SQLScript1.Script.SaveToFile(ExtractFilePath(Application.ExeName)+ FormatDateTime('yyyy_mm_dd_hh_nn', now)+'.dat');

Previously, I had done it the following way:
SQLScript1.Script.SaveToFile( FormatDateTime('yyyy_mm_dd_hh_nn', now)+'.dat');

...and it fails only at startup. If I run the app by double-clicking the exe file, it works fine.