text:
Q: OpenVPN low performance. Do I have MTU problems? Dumps inside I have problems with an OpenVPN tunnel which does not reach line speed. The gateway is a Debian Jessy virtual server hosted at OVH. The client is either my freebsd 10.2 homeserver (Intel I3 Ivy Bridge) or my RaspberryPI2. I deactivated encryption and authentication. I have a 100mbit/s symmetrical FTTH connection but the tunnel only reaches a speed of 20-40mbit/s. Direct connection (without tunnel) always yields the 100mbit/s I expect. I tested the performance with iperf3. I first tried with my freebsd homeserver. I tried all the recommended settings about mssfix, fragment etc. Nothing helped.
Then I thought maybe it is my freebsd machine. So I installed a fresh raspbian Jessy on my RPI2 and did some more in depth testing:
First of all I removed all the MTU settings from the OpenVPN configs and let the path MTU handle things (hopefully). Since I have no firewall active on both machines it should work. These are my vpn configs:
server 10.8.0.0 255.255.255.0
port 1194
proto udp
dev tun
sndbuf 0
rcvbuf 0

user nobody
group nogroup
persist-key
persist-tun
ifconfig-pool-persist ipp.txt
keepalive 10 120
push "redirect-gateway def1"
status openvpn-status.log
verb 3

ca /etc/openvpn/easy-rsa/keys/ca.crt
cert /etc/openvpn/easy-rsa/keys/vpn.theissen.io.crt
key /etc/openvpn/easy-rsa/keys/vpn.theissen.io.key
dh /etc/openvpn/easy-rsa/keys/dh4096.pem
tls-auth /etc/openvpn/easy-rsa/keys/ta.key 0
cipher none
auth none
comp-lzo no

client
proto udp
dev tun12
remote xxx.io 1194
resolv-retry infinite
sndbuf 0
rcvbuf 0

nobind
user nobody
group nogroup
persist-key
persist-tun
verb 3

pkcs12 /etc/openvpn/vpn.theissen.io/alex.p12
tls-auth /etc/openvpn/vpn.theissen.io/ta.key 1
ns-cert-type server
cipher none
auth none
comp-lzo no

First of all the test without the tunnel to show that the connection to the server is indeed almost 100mbit/s:
iperf3 -c vpn.theissen.io
Connecting to host vpn.theissen.io, port 5201
[  4] local 192.168.1.253 port 34512 connected to 149.202.58.183 port 5201
[ ID] Interval           Transfer     Bandwidth       Retr  Cwnd
[  4]   0.00-1.00   sec  10.8 MBytes  90.5 Mbits/sec    0    335 KBytes
[  4]   1.00-2.00   sec  11.4 MBytes  95.7 Mbits/sec    0    335 KBytes
[  4]   2.00-3.00   sec  11.1 MBytes  93.0 Mbits/sec    0    352 KBytes
[  4]   3.00-4.00   sec  11.2 MBytes  94.0 Mbits/sec    0    369 KBytes
[  4]   4.00-5.00   sec  11.5 MBytes  95.9 Mbits/sec    0    390 KBytes
[  4]   5.00-6.00   sec  11.0 MBytes  92.5 Mbits/sec    0    390 KBytes
[  4]   6.00-7.00   sec  11.4 MBytes  95.2 Mbits/sec    0    390 KBytes
[  4]   7.00-8.00   sec  11.2 MBytes  94.3 Mbits/sec    0    390 KBytes
[  4]   8.00-9.00   sec  11.1 MBytes  93.3 Mbits/sec    0    390 KBytes
[  4]   9.00-10.00  sec  11.3 MBytes  95.1 Mbits/sec    0    390 KBytes
- - - - - - - - - - - - - - - - - - - - - - - - -
[ ID] Interval           Transfer     Bandwidth       Retr
[  4]   0.00-10.00  sec   112 MBytes  93.9 Mbits/sec    0             sender
[  4]   0.00-10.00  sec   112 MBytes  93.5 Mbits/sec                  receiver

iperf Done.

The packets of this connection I dumped with tcpdump on the server. You can download them here (you have to extract to open them with wireshark): dumpraw.cap.xz
So this is how a "OK" dump looks like. Maximum frame size I spotted is 1514.

Now I ran the test over the tunnel:
iperf3 -c 10.8.0.1
Connecting to host 10.8.0.1, port 5201
[  4] local 10.8.0.14 port 36388 connected to 10.8.0.1 port 5201
[ ID] Interval           Transfer     Bandwidth       Retr  Cwnd
[  4]   0.00-1.00   sec  5.96 MBytes  50.0 Mbits/sec  127    133 KBytes
[  4]   1.00-2.00   sec  5.19 MBytes  43.5 Mbits/sec    6    120 KBytes
[  4]   2.00-3.00   sec  5.80 MBytes  48.7 Mbits/sec    0    151 KBytes
[  4]   3.00-4.00   sec  4.27 MBytes  35.9 Mbits/sec   23   96.5 KBytes
[  4]   4.00-5.00   sec  4.89 MBytes  41.0 Mbits/sec    0    129 KBytes
[  4]   5.00-6.00   sec  6.11 MBytes  51.2 Mbits/sec   26    111 KBytes
[  4]   6.00-7.00   sec  5.50 MBytes  46.1 Mbits/sec    0    143 KBytes
[  4]   7.00-8.00   sec  5.25 MBytes  44.1 Mbits/sec   15    126 KBytes
[  4]   8.00-9.00   sec  5.80 MBytes  48.7 Mbits/sec    0    158 KBytes
[  4]   9.00-10.00  sec  3.97 MBytes  33.3 Mbits/sec   22    105 KBytes
- - - - - - - - - - - - - - - - - - - - - - - - -
[ ID] Interval           Transfer     Bandwidth       Retr
[  4]   0.00-10.00  sec  52.7 MBytes  44.2 Mbits/sec  219             sender
[  4]   0.00-10.00  sec  52.3 MBytes  43.8 Mbits/sec                  receiver

iperf Done.

Whoops. Not so nice anymore. Especially this "Retr" column does not look so good. I assumed this is the tcp retransmit and there should be then something in the dump. We will see that it is not the case :/. CPU is not the bottleneck here because I deactivated enrcyption and authentication. CPU is at 20% at the server and 50% on the PI during the test.
This is how the OpenVPN traffic of the test looks like:

To me this looks okay. But I do not know what to look for. Please have a look at the dump with wireshark: dump_physical.cap.xz
The traffic on the tunnel interface looks good to me, too. It seems that he correctly lowered the frame size (to 1444 as it seems):

Here is the dump: dump_tunnel.cap.xz
To me this looks all fine but I really have no idea what to look for exactly. I really tested everything out with the OpenVPN settings. Maybe someone can tell me if the traffic looks okay.
What I expect as an answer
At least an explanation what is happening here and why it seems to be independent of the VPN software I use. Everything what I found on the internet was about MTU problems but that should be easily fixed by reducing the tunnel MTU or the other parameters of OpenVPN. For me this changes little. When you look at the dump you see that it reduces the tcp segment size and packets are not fragmented. There must be something else. I really like to know what.
Update
I tested this with strongswan and even with softether. It's actually the same problem (comparable speed, no cpu bottleneck). I am really puzzled what is the problem here. I also tried another gateway (RaspberryPi2 on  friends 100/100 home connection).
Update 2
I noticed that iperf3 reports tcp retransmits (retr) but there are no retransmits in the dump (Wireshark should highlight them). What is going on?
I even tried OpenVPN on my local Network (RaspberryPi2 to FreebsdServer). Even there I have a lot of retransmits (on LAN?!):
Connecting to host 192.168.222.11, port 5201
[  4] local 192.168.222.10 port 46196 connected to 192.168.222.11 port 5201
[ ID] Interval           Transfer     Bandwidth       Retr  Cwnd
[  4]   0.00-1.00   sec  9.19 MBytes  77.0 Mbits/sec    8    141 KBytes
[  4]   1.00-2.00   sec  8.71 MBytes  73.1 Mbits/sec    3    130 KBytes
[  4]   2.00-3.00   sec  8.59 MBytes  72.0 Mbits/sec    3    120 KBytes
[  4]   3.00-4.00   sec  8.65 MBytes  72.5 Mbits/sec    4    108 KBytes
[  4]   4.00-5.00   sec  8.65 MBytes  72.5 Mbits/sec    4   95.6 KBytes
[  4]   5.00-6.00   sec  8.52 MBytes  71.5 Mbits/sec    2   80.5 KBytes
[  4]   6.00-7.00   sec  8.83 MBytes  74.1 Mbits/sec    0    141 KBytes
[  4]   7.00-8.00   sec  8.59 MBytes  72.0 Mbits/sec    7    106 KBytes
[  4]   8.00-9.00   sec  8.71 MBytes  73.1 Mbits/sec    3   94.2 KBytes
[  4]   9.00-10.00  sec  8.59 MBytes  72.0 Mbits/sec    3   79.2 KBytes
- - - - - - - - - - - - - - - - - - - - - - - - -
[ ID] Interval           Transfer     Bandwidth       Retr
[  4]   0.00-10.00  sec  87.0 MBytes  73.0 Mbits/sec   37             sender
[  4]   0.00-10.00  sec  86.8 MBytes  72.8 Mbits/sec                  receiver

In reverse mode I have a really weird congestion window (wtf?):
Accepted connection from 192.168.222.10, port 46197
[  5] local 192.168.222.11 port 5201 connected to 192.168.222.10 port 46198
[ ID] Interval           Transfer     Bandwidth       Retr  Cwnd
[  5]   0.00-1.00   sec  8.90 MBytes  74.7 Mbits/sec    3   1.48 GBytes
[  5]   1.00-2.00   sec  8.45 MBytes  70.9 Mbits/sec    2   1.59 GBytes
[  5]   2.00-3.00   sec  8.66 MBytes  72.7 Mbits/sec  518    214 MBytes
[  5]   3.00-4.00   sec  7.96 MBytes  66.8 Mbits/sec   37    703 MBytes
[  5]   4.00-5.00   sec  8.09 MBytes  67.9 Mbits/sec    0    719 MBytes
[  5]   5.00-6.00   sec  8.04 MBytes  67.5 Mbits/sec    0    734 MBytes
[  5]   6.00-7.00   sec  8.07 MBytes  67.7 Mbits/sec    1    703 MBytes
[  5]   7.00-8.00   sec  8.07 MBytes  67.7 Mbits/sec    1    703 MBytes
[  5]   8.00-9.00   sec  7.99 MBytes  67.1 Mbits/sec    2    693 MBytes
[  5]   9.00-10.00  sec  8.06 MBytes  67.6 Mbits/sec    1    693 MBytes
[  5]  10.00-10.09  sec   684 KBytes  64.5 Mbits/sec    0    695 MBytes
- - - - - - - - - - - - - - - - - - - - - - - - -
[ ID] Interval           Transfer     Bandwidth       Retr
[  5]   0.00-10.09  sec  83.0 MBytes  69.0 Mbits/sec  565             sender
[  5]   0.00-10.09  sec  0.00 Bytes  0.00 bits/sec                  receiver

Update 3
Using iperf with udp results in ovh temporary blocking that port (they send me an email informing me about an attack) and massive packet loss:
-----------------------------------------------------------
Server listening on 1194
-----------------------------------------------------------
Accepted connection from 185.22.143.160, port 15906
[  5] local 149.202.58.183 port 1194 connected to 185.22.143.160 port 4355
[ ID] Interval           Transfer     Bandwidth       Jitter    Lost/Total Datagrams
[  5]   0.00-1.00   sec  2.89 MBytes  24.2 Mbits/sec  0.727 ms  1017/1387 (73%)
iperf3: OUT OF ORDER - incoming packet = 1409 and received packet = 1470 AND SP = 5
iperf3: OUT OF ORDER - incoming packet = 1410 and received packet = 1471 AND SP = 5
iperf3: OUT OF ORDER - incoming packet = 1411 and received packet = 1472 AND SP = 5
iperf3: OUT OF ORDER - incoming packet = 1445 and received packet = 1473 AND SP = 5
iperf3: OUT OF ORDER - incoming packet = 1463 and received packet = 1473 AND SP = 5
[  5]   1.00-2.00   sec  3.29 MBytes  27.6 Mbits/sec  0.716 ms  1110/1526 (73%)
[  5]   2.00-3.00   sec  3.30 MBytes  27.7 Mbits/sec  0.732 ms  1103/1526 (72%)
[  5]   3.00-4.00   sec  3.27 MBytes  27.4 Mbits/sec  0.717 ms  1108/1526 (73%)
[  5]   4.00-5.00   sec  1.56 MBytes  13.1 Mbits/sec  0.837 ms  546/746 (73%)
[  5]   5.00-6.00   sec  0.00 Bytes  0.00 bits/sec  0.837 ms  0/0 (-nan%)
[  5]   6.00-7.00   sec  0.00 Bytes  0.00 bits/sec  0.837 ms  0/0 (-nan%)
[  5]   7.00-8.00   sec  0.00 Bytes  0.00 bits/sec  0.837 ms  0/0 (-nan%)
[  5]   8.00-9.00   sec  0.00 Bytes  0.00 bits/sec  0.837 ms  0/0 (-nan%)
[  5]   9.00-10.00  sec  0.00 Bytes  0.00 bits/sec  0.837 ms  0/0 (-nan%)
[  5]  10.00-10.06  sec  0.00 Bytes  0.00 bits/sec  0.837 ms  0/0 (-nan%)
- - - - - - - - - - - - - - - - - - - - - - - - -
[ ID] Interval           Transfer     Bandwidth       Jitter    Lost/Total Datagrams
[  5]   0.00-10.06  sec   118 MBytes  98.5 Mbits/sec  0.837 ms  4884/6711 (73%)
[SUM]  0.0-10.1 sec  4884 datagrams received out-of-order

A: For starters your 'normal' outside tunnel iperf run should be UDP/1194 as the flow on which you have the problem and not TCP/5201. Try with -b 100M first but keep in mind this will produce max size datagrams which is not representative of your VPN traffic (datagram size should be sorta random). Tune with -l option for datagram size and check the results.
If the results are not good (I'd say  >15 or 20% loss) you may suspect an overloaded Internet router which is dropping your (probably marked best-effort) packets.
Also, it could be interesting to see what performance you get if you switch your VPN tunnel either to an EF Class UDP port (I'd say 5061 because of RTP, but not really sure that all internet routers have correctly configured QoS) or any TCP port.
To me, there's nothing wrong with your setup and your diagnostics don't show anything strange. Also, try another version of OpenVPN or other VPN software.


text:
Q: Proving a sequence by induction Trying to prove by induction in a non-math course and I feel like I'm getting the steps but I'm just stuck on the math.
$$G_1 = 1$$
$$G_2 = 1$$
$$G_n = 2G_{n−1} + 3G_{n−2}, \quad n \geq 3$$
Using mathematical induction, prove that for every $n ≥ 1$, $G_n ≤ 3^n$.
I used $G_1$ as my base case, since it's given.
My induction hypothesis is to assume $G_n \leq 3^n$ for some arbitrary $n$.
Thus I should prove $G_{n+1}\leq  3^{n+1}$.
Using the given formula I simplified down to $2G_n + 3G_{n-1} ≤ 3^n3$.
I feel like I'm pretty much there, but I just don't see how to solidify the proof from here. Any hints would be greatly appreciated!

A: You should use "complete induction": assuming the thesis for all $m<n$, for $n>2$, prove it for $n$.
The cases $G_1$ and $G_2$ should be provided separately:
$$
G_1=1\le 3^1,\qquad $G_2=1\le 3^2
$$
are OK.
Now assume the thesis holds for all $m<n$, with $n>2$. Then
$$
G_n=2G_{n-1}+3G_{n-2}\le 2\cdot 3^{n-1}+3\cdot 3^{n-2}
$$
because, by inductive hypothesis, $G_{n-1}\le 3^{n-1}$ and $G_{n-2}\le 3^{n-2}$. Now you should be able to finish up.
Note that $n>2$ is needed for the argument, so the cases $n=1$ and $n=2$ must be provided separately in order to start the induction.

A: $$G_1 = 1$$
$$G_2 = 1$$
$$G_n = 2G_{n−1} + 3G_{n−2}, n \geq 3$$
"My induction hypothesis is to assume $G_n \leq 3^n$ for some arbitrary $n$.
Thus I should prove $G_{n+1}\leq  3^{n+1}$.
Using the given formula I simplified down to $2G_n + 3G_{n-1} ≤ 3^n * 3$."
Now, notice this means $$G_{n+1} = 2G_{n} + 3G_{n−1}\leq3^n*3=3^{n+1}$$ You have your desired result.

A: Suppose
$g_n
=ag_{n-1}+bg_{n-2}
$
where
$a, b > 0$.
We want to find a
condition on $r$ such that
$g_{n-1} \le r^{n-1}$
and
$g_{n-2} \le r^{n-2}$
implies that
$g_{n} \le r^{n}$.
If
$g_{n-1} \le r^{n-1}$
and
$g_{n-2} \le r^{n-2}$,
then
$g_n
=ag_{n-1}+bg_{n-2}
\le ar^{n-1}+br^{n-2}
= r^n(a/r+b/r^{2})
$.
So it is sufficient if
$(a/r+b/r^{2})
\le 1$
or
$ar+b \le r^2$.
Manipulating this,
$r^2-ar+a^2/4 \ge b+a^2/4$
or
$(r-a/2)^2 \ge b+a^2/4$
or
$r
\ge a/2 +\sqrt{b+a^2/4}
$.
(This should look familiar.)
In your case,
with $a=2$ and $b=3$,
this gives
$r
\ge 1+\sqrt{3+1}
=3
$.
This leads to the
characteristic equation
of a linear recurrence.
Look it up.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Docker:Error Response from daemon timeout I started working on Docker containerization. For that, first of all I installed Oracle Virtual Box on my laptop that has Window 10 home.
Then setup one Ubuntu on virtual machine and install the docker as well.
So now docker is working fine but I am facing one issue.
when I am running following command than its giving me error.
sudo docker run hello-world

error screen shot:

I also read few articles which say it could be due to some internet settings and I tried everything but could not fix.

A: The error you are having has nothing to do with Docker, but with the configuration of your virtual machine.
The error you are having is because Docker is trying to download the image hello-world, but it has not access to the internet.
To solve you issue you need to look for ways to connect your VirtualBox to the internet, there are many links on StackOverflow to help you out, have a look: https://stackoverflow.com/search?q=virtual+box+no+internet+access


text:
Q: mongodb 3.2.18 use slice in pipeline Unrecognized pipeline stage name: '$slice' In the document of mongodb, "$slice" was introduced in version 3.2. However, after upgrading my mongodb to 3.2, I still get this error. And I also check the db.version() and mongo --version, both of them are 3.2.18.
EDIT from the comments aggregate pipeline
db.test.aggregate(
    [
        {
            $match : {"keya" : val}, {$slice : ["$mylist", 2] }
        }
    ]
)

A: The problem here is that $slice cannot be used as a top level operator in aggregation pipeline but only as a part of $project. Please not that in MongoDB docs it is a part of Aggregation Pipeline Operators and not Aggregation Pipeline Stages.
Try following code:
db.test.aggregate([
    {$match : {"keya" : vala}},
    { $project: { keya: 1, myList: { $slice: [ "$myList", 2 ] } } }
])


text:
Q: Не работает OnDrag, но работает OnMouseDown Есть код:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class DragAndDropGame : MonoBehaviour, IBeginDragHandler, IDragHandler
{

    Camera MainCamera;

    void Awake()
    {
        MainCamera = Camera.allCameras[0];
        Debug.Log(MainCamera);
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        Debug.Log("OnBeginDrag");
    }

    public void OnDrag(PointerEventData eventData)
    {
        Vector3 newPos = MainCamera.ScreenToWorldPoint(eventData.position);
        newPos.z = 0;
        transform.position = newPos;
    }

    void OnMouseDown()
    {
        Debug.Log("OnMouseDown");
    }
}

OnMouseDown отрабатывает, а реализации IBeginDragHandler, IDragHandler - нет. В чем может быть дело?

A: IBeginDragHandler, IDragHandler находятся в пространстве имён UnityEngine.EventSystems и используют для работы EventSystem. Если точнее, то эта система кидает рейкасты, собирает с точек попадания свои интерфейсы и производит вызов.
Метод же OnMouseDown принадлежит MonoBehaviour и реализуется просто через прокидывание рейкаста из всех камер.
Можете посмотреть, в UnityEngine.EventSystems так же присутствуют интерфейс IPointerDownHandler, который является аналогом OnMouseDown.
В вашем случае, если OnMouseDown работает, а интерфейсы нет, то на сцене отсутствует объект класс EventSystem. Нажмите ПКМ в иерархии и создайте его из меню UI->EventSystem


text:
Q: Check condition and send out parameter value from procedure in MySQL I'm creating a procedure where it needs to check the value of a column IsLoggedIn and send the outparameter with -1 if "IsLoggedIn" is 1 else it needs to send the user information.
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_bh_loginverify1`(IN `user_email` VARCHAR(100), OUT `p_islogged` INT)
    NO SQL
BEGIN

IF (EXISTS(select * FROM user_details WHERE user_email = user_email))
    THEN
        SET p_islogged = 1; SELECT 0;
END IF;

(select UD.user_id, UD.user_name, UD.password, UD.password_salt, UD.user_email, R.role_id as role, R.role_name as role_name from user_details UD
 JOIN roles R on R.role_id = UD.role
 where (UD.user_email = user_email OR UD.user_name = user_email));
END$$
DELIMITER ;

A: First of all, always name your procedure input parameters something different from the columns of your table. For example you do this:
IF (EXISTS(select * FROM user_details WHERE user_email = user_email))

How is MySQL supposed to know that user_email is the column in the table, but user_email is the procedure parameter of that name? It doesn't -- it assumes both are references to the column. It compares the column user_email to itself, which will return every row where the column is not NULL, because it's always true that user_email = user_email. In other words, that the column is equal to itself (unless it's NULL).
You shoudl name the procedure parameter something distinct from the column name:
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_bh_loginverify1`(IN `p_user_email` VARCHAR(100), OUT `p_islogged` INT)

You used NO SQL which means: "indicates that the routine contains no SQL statements." But that's not true, because you do have SQL statement in this procedure.
You should use:
READS SQL DATA

You said you want to return -1 in the OUT parameter, but you set 1. So you should set -1.
Next you mentioned "else it sends user information" which suggests you want that result set to be returned only conditionally. But your code returns that user information outside the IF/END IF block, so it happens regardless of the condition. You should use an ELSE block to do this.
Notice the use of p_user_email in the queries below, to make it distinct from user_email.
BEGIN

    IF (EXISTS(select * FROM user_details WHERE user_email = p_user_email))
        THEN
            SET p_islogged = -1;
    ELSE
        SELECT UD.user_id, UD.user_name, UD.password, UD.password_salt, UD.user_email,
            R.role_id as role, R.role_name as role_name
        FROM user_details UD
        JOIN roles R ON R.role_id = UD.role
        WHERE UD.user_email = p_user_email OR UD.user_name = p_user_email;
    END IF;

END

I don't think you need SELECT 0; at all. MySQL stored procedures can return no result set, or one result set, or multiple result sets.


text:
Q: Add css class to first child through javascript ES6 Here is my html which is generated from a Rails form that loops through a PersonalityQuestions table.

I want to be seen as successful

I don't want to be seen as taking up too much space

I want to be seen as authentic and special

I want to use javascript (sadly no jQuery) to add the class of active to the first child of my

The result should be

I've read every Stackoverflow post and can't find the answer.
This is the best answer I came up with
document.getElementsByClassName('carouselinner').firstChild.classList.add('active');
but I get an error:
Uncaught TypeError: Cannot read property 'classList' of undefined at <anonymous>:1:61
Can anyone tell me what I'm doing wrong?

A: You basically have two issues in your attempt:
Firstly, getElementsByClassName() returns an array-like object of all child elements which have all of the given class names. So it is ambiguous from which index you are looking for the firstChild. You have provide the specific index.
Secondly, for an issue (returning #text or #comment nodes) with node.firstChild

To avoid the issue with node.firstChild returning #text or #comment nodes, ParentNode.firstElementChild can be used to return only the first element node. However, node.firstElementChild requires a shim for Internet Explorer 9 and earlier.

So your code should be:
document.getElementsByClassName('carousel-inner')[0].firstElementChild.classList.add('active');

But the preferred approach will be using :first-child selector in querySelector() with classList.add():

document.querySelector('.carousel-inner :first-child').classList.add('active');
.active {color: red}

I want to be seen as successful

I don't want to be seen as taking up too much space

I want to be seen as authentic and special


text:
Q: Hibernate Transaction in iteration occurs errors I'm new to hibernate.
I want to use transaction in iterator, so i did like this (without business logic):
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
for {
    try {
        Something something = session.get(Something.class, id);
        something.setX(X);
        session.save(something)
        tx.commit(); <-- error occurs after iterated once.
    catch { tx.rollback(); }
}
Something something2 = session.get(Something.class, id2);
something2.setX(X);
session.save(something2);
tx.commit():
session.close();

But the hibernate occurs Transaction not successfully started error
So i changed code like this.
Session session = sessionFactory.openSession();
Transaction tx;
for {
    try {
        tx = session.beginTransaction();
        Something something = session.get(Something.class, id);
        something.setX(X);
        session.save(something)
        tx.commit();
    catch { tx.rollback(); }
}
session.beginTransaction();
Something something2 = session.get(Something.class, id2);
something2.setX(X);
session.save(something2);
tx.commit():
session.close();

This code works at the first time. But when i relaunch this program, it occurs lock wait timeout exceeded.
Although I have set innodb_lock_wait_timeout as 120 the result is same.
What wrong with that !?


text:
Q: Generating a random number from the array Suppose there is an array :
int arr[] = {0,1,2}

Is there a way I can generate a random number out of 0,1,2 (i.e from the array) ?

A: try this
    import java.util.Random;

    Random random = new Random();
    System.out.println(arr[random.nextInt(arr.length)]);

A: Sure. You should generate a number between 0 and arr.length-1, round it to a int number and then take the arr[your_random_number] element.
int random_index = (int) round(Math.random() * (arr.length - 1));

then your element would be arr[random_index]

A: If you want unique element each time from the array then try this:
Integer arr[] = {0,1,2}
Collections.shuffle(Arrays.asList(arr));
for(int unique: ar)
   System.out.println(unique);

Shuffle method of Collections  will randomly shuffle the given array .

A: This will pick a number randomly out of the array.
public static void main(String[] args)
{
    int arr[] = {0,1,2};
    System.out.println(arr[(int)(Math.random()*arr.length)]);
}


text:
Q: how to pass static variables of class as argument in c# I am trying access properties of particular inbulit class in c# but i am not getting how to pass a class static variable and pass as an argument to a method.
Here is the class I want to pass as argument:
public class PageSize
{
    //
    public static readonly Rectangle A0;
    //
    public static readonly Rectangle A1;
}

Now I have method where i want to pass the variables of the above class as argument like this:
public void NewExportToPDFforLetter(StringWriter sw, string FileName, PageSize s )
{
    //s = new PageSize();
    StringReader sr = new StringReader(sw.ToString());
    Document pdfDoc = new Document(s.A0, 30f, 30f, 30f, 30f);
}

I am getting error at s.A0. Any help will be appreciated.

A:
Now I have method where i want to pass the variables of the above class as argument like this: public void NewExportToPDFforLetter(StringWriter sw, string FileName, PageSize s )

And why would you want to do that? PageSize is already accesible inside NewExportToPDFforLetter without the need to pass it as an argument:
public void NewExportToPDFforLetter(
    StringWriter sw,
    string FileName)
{
      var a0 = PageSize.A0; //accesible as long as `Page` is accesible:
                            //public class, internal in same assembly, etc.

      //...
}

If PageSize is not accesible from wherever NewExportToPDFforLetter is implemented, then you wouldn't be able to pass it as an argument to begin with, so the option  you are considering is simply unecessary.

A: If you want to keep the properties static, you can access them directly using PageSize.A0 and PageSize.A1.
If you want to access them from an instance, you will have to remove the static declaration of the properties.

A: Since static class variables are not part of an instance, you should not use the instance.property syntax but classname.property.
Thus change
Document pdfDoc = new Document(s.A0, 30f, 30f, 30f, 30f);

to
Document pdfDoc = new Document(PageSize.A0, 30f, 30f, 30f, 30f);

However, it's not visible, but probably you do not want to use static. In that case instead of the above change, you have to remove the statics by changing
public static readonly Rectangle A0;
//
public static readonly Rectangle A1;

to
public readonly Rectangle A0;
//
public readonly Rectangle A1;

A: You need to access A0 with PageSize.A0 instead of s.A0

A: This is the way you can do this
var size= PageSize.A4;
NewExportToPDFforLetter(stringWriter, "Application Approval Letter", HttpContext.Current.Response,(Rectangle)size);

public void NewExportToPDFforLetter(StringWriter sw, string FileName, HttpResponse Response, Rectangle s )
{
    Document pdfDoc = new Document(s, 30f, 30f, 30f, 30f);
}


text:
Q: PHP Variable does not appear instantiated in View. Trying to use PHP MVC
Code in demo.ctrl.php
$TPL['username'] = "BOB";
$TPL['title'] = "Template Demo";
include demo.view.php;

Code in the demo.view.php
<html>
<head>
<title><?=$TPL['title']?></title>
</head>
<body>
<h1> Welcome <?=$TPL['username'];?></h1>
</body>
</html>

HTML Output:
Welcome
Notice: Undefined variable: TPL in C:\root\php_demo\demo.view.php on line 6
If I click on ctrl.demo.php
I get these errors:

Notice: Use of undefined constant demo - assumed 'demo' in
  C:\root\php_demo\demo.ctrl.php
  on line 5
Notice: Use of undefined constant view - assumed 'view' in
  C:\root\php_demo\demo.ctrl.php
  on line 5
Notice: Use of undefined constant php - assumed 'php' in
  C:\root\php_demo\demo.ctrl.php
  on line 5
Warning: include(demoviewphp): failed to open stream: No such file or
  directory in
  C:\root\php_demo\demo.ctrl.php
  on line 5
Warning: include(): Failed opening 'demoviewphp' for inclusion
  (include_path='.;C:\php\pear') in
  C:\root\php_demo\demo.ctrl.php
  on line 5

Both files are in the same folder.

A: include() needs a string:
include "demo.view.php";

With your current code PHP tries to build a string by concatenating . what it assums to be constant variables that are not defined so it concatenates . them as strings.  Yielding demoviewphp.


text:
Q: Can't get AVAudioPlayer to Play I've followed every resource that I can find, and I don't know why this isn't working. I'm trying to play it on the simulator. Also, I have verified that my urlString is accurate and that it plays when pasted into a browser. What am I missing?
.h file
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface MyViewController : UIViewController <AVAudioPlayerDelegate>

@end

.m file
@interface SessionsListViewController ()
@property (strong, nonatomic) AVAudioPlayer *audioPlayer;
@end

- (void) viewDidLoad
{
    NSString *urlString = [NSString stringWithFormat:@"%@%@", AUDIO_URL, @"test.mp3"];
    NSURL *url = [NSURL URLWithString:urlString];
    NSError *err = nil;
    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&err];

    [self.audioPlayer prepareToPlay];
    [self.audioPlayer setDelegate:self];
     self.audioPlayer.volume = 1.0;
    [self.audioPlayer play];

}


text:
Q: Using Vuex as well as an Event Bus in Vue I've had this question buried in my mental Rolodex for quite some time now. I'm running a very complex Vue application that deals with quite a number of components that must communicate so for that I use a very structured setup of Vuex utilizing its module system. However, for a particular group of components, say a comments folder, i.e:
Comments Directory:

*

*Comments.vue  // overall comments component

*Comment.vue // component for each comment

*NewComment.vue // component to create new comments

*bus.js // reserved event bus for only these three components

Is it fine to utilize a reserved Event Bus placed in this directory only for these 3 components to communicate to one other, or is that deemed as "malpractice" since I already have a large vuex system going ?

A: I suggest using Vuex for all of your application. Doing so keeps your state in a single place. Using an event bus detracts from this, in that now you have two places containing state. Worse still, an event bus is less maintainable and often breaks the "one way data flow" promoted by Vue and Vuex (and other Flux implementations).
Vuex can be used for both application state and application data. Data being the usual stuff like customer details, etc. State being the "this sidebar hamburger menu is open" or "this modal is open" or "user selected this item in a list".
This then leads on to your "I just feel as Vuex should be used for app wide communications, not for communications between 2-3 neighbouring components". It's the same thing when you think about it.
If a parent component wishes to communicate with a child component, it passes props down. If the child wishes to communicate in a decoupled manner it emits events. That is perfectly fine for that scenario.
Try doing that with multiple nested components! A -> B -> C -> D
Imagine if D needed to update some state in B. How do you do that, emit events all the way up, and couple your components? Yuck, that is not the way to go. D should dispatch a Vuex action which in turn updates B via the store binding. What about when A needs to updated something in C? Now your B component needs special case extra props just to allow A to communicate with C when B should be able to exist on it's own without A as a parent. Yuck again! Dispatch an action.
Communicating between sibling components or even components in totally different parts of the page is exactly one of the things Vuex is designed for: application state.
Removing your event bus and accepting this approach will make your code easier and more maintainable.

A: if your application is very complex and big than go with vuex which is better for the state management, if not than you can stick with props,event bus and all this.


text:
Q: Reading stdin causes UnicodeDecodeError I have a program reading stdin using by sys.stdin.read(). The stdin is an email given by postfix .forward. Sometimes UnicodeDecodeError occurs (See blow).
How should I read email content with python from stdin?
raw_email = sys.stdin.read()

  File "/app/Python-3.4.2/lib/python3.4/codecs.py", line 313, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf6 in position 1230: invalid start byte


text:
Q: How to find the shortest path with multiple nodes and multiple relationships in Neo4j I am not an expert in Cypher but I'm in a project where I have several nodes with the following properties:
['COGAB11', 'COGAB7', 'COGAB30', 'COGAB32', 'COGAB94', 'COGAB70',
'COGAB01', 'COGAB04', 'COGAB91', 'COG1AB77', 'COGAB46', 'COGAB40',
'COGAB31', 'COGAB14']

and between them there are several relationships:
[rel:coexpression|cooccurence|database|experimental|
fusion|neighborhood|score|textmining]

which also have a property like score which is a numerical integer value of 0-1000 and I would like to find the shortest path between all these nodes and get the relationships with a score greater than and equal to 500 between them. Therefore, I would like to return the graph with these relationships and path. However, I have only found a query of the shortest path but between two nodes and not between multiple nodes and multiple relationships. Additionally, I'm not sure if I should use APOC for this.
MATCH (start:Loc{name:'A'}), (end:Loc{name:'F'})
CALL algo.shortestPath.stream(start, end, 'cost')
YIELD nodeId, cost
RETURN algo.asNode(nodeId).name AS name, cost

A: If you mean that you want each relationship to have a score >= 500, then this should return the shortest path:
MATCH (start:Loc {name: 'A'}), (end:Loc {name: 'F'}),
  p = SHORTESTPATH((start)-[:coexpression|cooccurence|database|experimental|fusion|neighborhood|score|textmining]-(end))
WHERE ALL(r IN RELATIONSHIPS(p) WHERE r.score >= 500)
RETURN p


text:
Q: Apps Scripts .getStartTime() doesn't work so i have a script that gets information from google calendar.
var cal = CalendarApp.getCalendarById(calendarId);
var events = cal.getEventSeriesById(eventId);
var details = [[events.getTitle(), events.getDescription(), events.getStartTime(), events.getEndTime()]];

but whenever i try to run it, i get the error TypeError: Cannot find function getStartTime in object CalendarEventSeries.
why doesn't it work?, .getStartTime is a function listed on google's own website
https://developers.google.com/apps-script/reference/calendar/calendar-event#getStartTime()

A: getStartTime is defined on the CalendarEvent class and not CalendarEventSeries. That's why you are getting the error.
Please check the documentation -
CalendarEvent : https://developers.google.com/apps-script/reference/calendar/calendar-event
CalendarEventSeries : https://developers.google.com/apps-script/reference/calendar/calendar-event-series


text:
Q: How to Get Current Project Name from TeamFoundationRequestContext I'm writing a plugin for a TFS process.
I need to get the Project Name from the TeamFoundationRequestContext whenever a work item is in the process of saving.
Normally I can get the work item ID because the record has already been saved. However, when the work Item is being saved the first time, I do not have a way to get the work item ID.
My question is how can I get the Project Name from the TeamFoundationRequestContext when the work item saves for the first time.

A: Here is a class that captures the work item changed event and checks to see if it is a newly created work item.
From within the event if it is a newly created work item you can then do what you need with the Project name that is associated with that work item.
using Microsoft.TeamFoundation.Framework.Server;
using System;
using Microsoft.TeamFoundation.Common;
using Microsoft.TeamFoundation.WorkItemTracking.Server;

namespace TfsProcess.CaptureProjectNameOnNewWorkItem
{
    public class CaptureProjectNameOnNewWorkItem : ISubscriber
    {

        public string Name
        {
            get
            {
                return "CaptureProjectNameOnNewWorkItem";
            }
        }

        public SubscriberPriority Priority
        {
            get
            {
                return SubscriberPriority.Normal;
            }
        }

        public EventNotificationStatus ProcessEvent(
            TeamFoundationRequestContext requestContext,
            NotificationType notificationType,
            object notificationEventArgs,
            out int statusCode,
            out string statusMessage,
            out ExceptionPropertyCollection properties)
        {
            statusCode = 0;
            properties = null;
            statusMessage = String.Empty;

            try
            {
                ProcessNotification(notificationType, notificationEventArgs, requestContext);
            }
            catch (Exception exception)
            {
                TeamFoundationApplicationCore.LogException("Error processing event", exception);
            }
            return EventNotificationStatus.ActionPermitted;

        }

        private static void ProcessNotification(NotificationType notificationType, object notificationEventArgs, TeamFoundationRequestContext requestContext)
        {
            if (notificationType == NotificationType.Notification && notificationEventArgs is Microsoft.TeamFoundation.WorkItemTracking.Server.WorkItemChangedEvent)
            {
                var ev = notificationEventArgs as WorkItemChangedEvent;
                if (ev.ChangeType == ChangeTypes.New)
                {
                    //Do somethin with the project name of the newly created work item
                    // projectName = ev.PortfolioProject;

                }

            }
        }

        public Type[] SubscribedTypes()
        {
            return new Type[1] { typeof(WorkItemChangedEvent) };
        }
    }
}

Update:
You could create a plugin implementing the ITeamFoundationRequestFilter interface, which gets executed BEFORE or AFTER Team Foundation Server receives and processes requests. This allows you to validate work items and cancel the creation of the work item if it is not valid based on some logic for instance.
Here is a link to blog with a implementation of this that will cancel the creation of the work item if it is being created by a certain user.
Getting information from a TFS Request
How to implement ITeamFoundationRequestFilter
In order to get the Work Item ID you will intercept the xml soap response and parse it for the work item value.
Using the filter plugin you can filter for any of the methods responsible for updating, creating and querying work items.
The blog goes into more explanation and implementation.

A: The WorkItemChangedEvent event has a PortfolioProject property, so you should be able to get it like this:
var ev = (WorkItemChangedEvent)notificationEventArgs;
var projectName = ev.PortfolioProject


text:
Q: Google Cloud Debugger thread "can't continue" I'm trying to activate the google cloud debugger agent in my micronaut based java app in GKE. But as you may have guessed, it does not work and I can't see my app in the debugger tool in the cloud console.
The container entry point is: [java, -agentpath:/cdbg_java_agent.so=--logtostderr=1, -Dcom.google.cdbg.module=mymodule, -Dcom.google.cdbg.version=123, -cp, /app/resources:/app/classes:/app/libs/*, com.example.Application].
I see these logs from the container:
I1015 07:52:41.962275     6 jvmti_globals.cc:330] Build time: Sep  5 2019 11:40:41
I1015 07:52:41.962328     6 jvmti_agent.cc:159] Java debuglet initialization started
I1015 07:52:41.962790     6 jvmti_agent.cc:193] Java debuglet initialization completed
I1015 07:52:42.099573     6 jvmti_agent.cc:204] Java VM started
I1015 07:52:42.111140     6 jvmti_agent.cc:214] JvmtiAgent::JvmtiOnVMInit initialization time: 11578 microseconds
I1015 07:52:42.111268    14 jvmti_agent_thread.cc:99] Agent thread started: CloudDebugger_main_worker_thread
E1015 07:52:42.111346    14 jvmti_agent.cc:339] Internals could not be initialized
E1015 07:52:42.111358    14 worker.cc:123] Agent initialization failed: debugger thread can't continue.
I1015 07:52:42.111362    14 jvmti_agent_thread.cc:103] Agent thread exited: CloudDebugger_main_worker_thread

It would be interesting to know why "Internals could not be initialized". Is there a way to increase the logging level?
How else can I find out why the debugger thread dies?


text:
Q: How to prevent deadlock and how to set isolation level in entity framework? I have many deadlock in my application (asp.net mvc , entity framework code first)
so I found some blog posts regarding deadlocks. In one blog post here is suggested to use
 SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

dbcontext.database.executesqlcommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;")

I execute this sql command on sql server and then checked the transaction isolation level which was read uncommitted.
but when i run it through code using ef and linq and setting a breakpoints after the line that run "set transaction" and going back to sql to check trnasaction level it still is read committed and again i have so many deadblock.
Another solution that i found is here which suggest to use scope to set isolation level
using (var scope = new TransactionScope(TransactionScopeOption.Required, new
      TransactionOptions { IsolationLevel= IsolationLevel.Snapshot }))
    {

    // do something with EF here
    scope.Complete();
    }

but is it possible to use scope when using per request context?
The first question is why transaction level is still read committed after setting it to read uncommitted through dbcontext?
the second question is that in this blog post it has mentioned that setting isolation level is per context does this mean that after disposing of dbcontext isolation level goes back to read committed?
and last i'm using ef code first v6 and have used unity to make dbcontext per request what other options i have so i avoid so many deadblock that are happening?

A: First, check where your deadlocks are coming from. That will help you find your problem areas - the areas you need to fix.
Sometimes ORMs have issues with complex logic. One option is to provide Entity Framework with a stored procedure for reading and writing to your more data-intensive tables.
In your controller or repository layer, you can execute a stored procedure like this:
Context.Database.SqlQuery<MyEntityType>("Exec mySpName \@p0, \@p1", param1, param2);

You can also use Database.ExecuteSqlCommand for procedures that do not return data.
Stored procedures normally have performance gains from execution plan caching.
Using Read Uncommitted is not a magic bullet, but if you really don't care about dirty reads potentially returning bad data, then you can guarantee that your stored procedure will not take read locks by setting the serialization or using the NoLock hint.


text:
Q: Communication between two hosts with closed ports I'm struggling with implementing a LAN communication between two devices. I dont want to open any ports on each side. The communication will be to exchange some data.
With two devices in same LAN network, creating a communication is not a problem when one side opens port.
The problem arises when I wish to provide minimum open ports between hosts, but I don't really think there is a easy way to do it.
I was thinking about using broadcast domain as a communication channel, so device HOST1 sends encrypted message to broadcast address, and HOST2 listens to broadcast and decrypts the message.
The downsize of this is, all devices within LAN will receive the message, thus putting some(?) overhead to the network.
Are there any other methods I can use except the broadcast one?
from socket import *
cs = socket(AF_INET, SOCK_DGRAM)
cs.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
cs.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
cs.sendto('This is a test', ('255.255.255.255', 54545))


text:
Q: Is it possible to to define all my layout only with constraints? I am trying to define the height of the constraintLayout1 30% of the available size. And the remaining for the constraintLayout2. But I want to define percentage not pixels.
The Button1 should be 50% with and the button2 the others 50%.
I want to define everything with constraints and not with fix values (as I am doing now marginBottom="500dp).
Is this possible to do in any way? I am using Android 3.6.2.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/constraintLayout1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="500dp"
        android:background="#E91E63"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0">

    </androidx.constraintlayout.widget.ConstraintLayout>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/constraintLayout2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#8BC34A"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/constraintLayout1"
        app:layout_constraintVertical_bias="0.0">

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:text="Button"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:text="Button"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
```[enter image description here][1]

  [1]: https://i.stack.imgur.com/NzZwz.png

A: You can use layout_constraintVertical_weight and layout_constraintHorizontal_weight
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/constraintLayout1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#E91E63"
        app:layout_constraintBottom_toTopOf="@id/constraintLayout2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_weight="0.3">

    </androidx.constraintlayout.widget.ConstraintLayout>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/constraintLayout2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#8BC34A"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/constraintLayout1"
        app:layout_constraintVertical_weight="0.7">

        <Button
            android:id="@+id/button1"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:text="Button"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@id/button2"
            app:layout_constraintHorizontal_weight="0.5"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="@id/constraintLayout2" />

        <Button
            android:id="@+id/button2"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintHorizontal_weight="0.5"
            android:text="Button"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@id/button1"
            app:layout_constraintTop_toTopOf="@id/constraintLayout2" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

A: Yes, an easy way to do this is Guidelines
You would basically say that you create a horizontal/vertical line at 0-100% of the width/height (in your case 30% or 50%) and then connect your buttons with that Guideline
Also it is bad practice to have multiple Constraintlayouts within eachother when not needed, you should only have one
Ask if you have any further questions


text:
Q: Expose modules from module to module I've node application which need to get path to folder and read all the files from there.
e.g
moduleA
 -server.js
 -controller
  --load.js

in the load.js I've method(loadFolderFiles) which should get path to file
path and load all the files from it.
Now from module B I need to require moduleA and add path to folder to read files
Application B structured like following:
 appB
   -src
    --files
      ---fileA.js
      ---fileB.js
   -server.js

Inside the appB server.js I'm doing the following(to load moduleA)
var moduleA = require('moduleA')
moduleA.loadFolderFiles('/appB/src/files')

moduleA.start();

Now moduleA will start to load the files for the provided path(I want to use glob for it).
My question are:

*

*I publish moduleA as npm module and my question how should I expose
the API of moduleA.loadFolderFiles(recommended way)?

2.How should I provide the path for it(relative /absolute) and read the files
from module appB?
This is the "moduleA" in npm (for testing)
https://www.npmjs.com/package/samplenodeapp
This is the code for moduleB to load moduleA
 var sample = require('samplenodeapp');
    sample.start();

The code which I expose module a is like following
var express = require('express');
var loadModule = require('./controller/load')
var app = express();
function start (){
    app.listen(3001, function () {
        console.log("App is listenting on port 3000");
    })
}
module.exports = {
    start:start,
    loadModule:loadModule
};

As you can see I exposed method from the controller/load like following (to provide the api for loadFolderFiles, is it OK?

A: If setting load folder is required, I would suggest to move it either to start arguments or to module settings.
var moduleA = require('moduleA')({ loadFolder: '/path/to/folder' });

// or
var moduleA = require('moduleA');

moduleA.start({ loadFolder: '/path/to/folder' });

If you chose to move it to the module settings, you should export a function from that module.
var createLoader = require('./controller/load');

module.exports = function (params) {
   // params === { loadFolder: '/path/to/folder' }

   var loadModule = createLoader(params.loadFolder);

   return {
       start: start,
       loadModule: loadModule
   }
};


text:
Q: How to get the root cause when createFile fails? Trying to create a file using createFile API on iOS.
createFile(path, data, attr)

Document says,
Return Value:
true if the operation was successful or if the item already exists, otherwise false.
I wonder if the operation was not successful, how can I get the exact cause of the failure?. Expected some API like,
createFile(path, data, attr, &error)

A: Use Data.write(to:options:) instead, it throws.
I use FileManager.default.createDirectory to create folders. I create Data that I want to write, and then I use Data.write to save it to disk.
var docDir = URL()
do {
    docDir = try FileManager.default.url(
        for: .documentDirectory,
        in: .userDomainMask,
        appropriateFor: nil,
        create: true
    )
} catch {
    fatalError("\(error)")
}
let subDir = docDir.appendPathComponents("mySubDir")
do {
    try FileManager.default.createDirectory(
        at: subdir,
        withIntermediateDirectories: true,
        attributes: nil
    )
} catch {
    if (error as NSError).code == 516 {
        // "The file "x" couldn't be saved in the folder "y" because a file with the same name already exists."
        // This is OK.
    } else {
        fatalError("\(error)")
    }
}
let filePath = subdir.appendingPathComponent("yourFileName")
let object:Codable = Whatever()
let data = try! JSONEncoder().encode(object)
do {
    try data.write(to: filePath)
} catch {
    fatalError("\(error)")
}

I do not know why Apple devs chose FileManager.createFile to be different. It seems strange to me.


text:
Q: Inequality derived Schwarz's Lemma Let $f$ be a holomorphic function on $U(0,R)$ with $0< R.$ Assume there exists an $M > 0$ such that $|f(z)| \leq M$ for $z \in U(0,R)$ and an $n \in \mathbb{Z}_{\geq 0}$ satisfying $$0 = f(0) = f'(0) = ... = f^{(n)}(0).$$
Show that $$|f(z)| \leq M(\frac{|z|}{R})^{n+1}$$ for all $z \in U(0,R)$, and $$\frac{|f^{(n+1)}(0)|}{(n+1)!} \leq \frac{M}{R^{n+1}}.$$
I think I should use Schwarz's Lemma to show it. Since $f$ is holomorphic on $U(0,R)$, then $$f(z) = \sum_{k=0}^{\infty} a_kz^k = \sum_{k = n+1}^\infty a_kz^k$$ for $z \in U(0,R)$ (because $f^{(j)}(0) = 0$ for $ 0 \leq j \leq n)$.
Set $g : U(0,1) \rightarrow \mathbb{C}$, $$g(\frac{z}{R}) = \frac{R^nf(z)}{z^nM} =\frac{R^n}{M} \sum_{k= n+1}^\infty a_kz^{n-k}.$$ Notice that $g$ is holomorphic on $U(0,1)$ and $g(0) = 0.$ If I can show that $|g(\frac{z}{R})| < 1 $ for $z \in U(0,R)$, I can apply Schwarz 's Lemma and the result will be immediate. But I cannot show that $|g(\frac{z}{R})| < 1$ for $z \in U(0,R)$. Can anyone give a hint ? Is my approach suitable ?

A: $f$ has a zero of multiplicity at least $n+1$ in $0$. Thus, $g$ holomorphic with with $f(z) = z^{n+1}g(z)$ exists. By maximum principle we have $|g(z)| = \left|\frac{f(z)}{z^{n+1}}\right| \leq \frac{M}{R^{n+1}}$ for all $z\in U(0,R)$.
Hence $|f(z)| \leq M\frac{|z^{n+1}|}{R^{n+1}}$ for all $z\in U(0,R)$.

A: Note that $f(Rz)/M$ maps the unit disc to itself, since $f(Rz) \leqslant M$ for $0<\lvert z \rvert < 1$.
Define
$$ g(z) = \begin{cases}
\frac{1}{M} \frac{f(Rz)}{z^{n+1}} & z \neq 0 \\
\frac{R^{n+1}}{M}\frac{f^{(n+1)}(0)}{(n+1)!} & z=0
\end{cases},  $$
and now the proof goes in the same way as Schwarz's lemma: By the conditions in the question, $g$ is analytic on $U(0,1)$, (obviously you need to check this at $0$: use the Taylor series) so the maximum principle applies. On the boundary, $g(z) \leqslant 1$, so we find that for $0 < \lvert z \rvert \leqslant 1$,
$$ \frac{1}{M} \frac{f(Rz)}{z^{n+1}} \leqslant 1, $$
which gives the right answer after untangling the substitution. Further, what does this give at $z=0$? Why,
$$ \frac{R^{n+1}}{M}\frac{f^{(n+1)}(0)}{(n+1)!} \leqslant 1, $$
which is the other thing we wanted.

The second part can also be done using the Cauchy Integral formula:
$$ f^{(n+1)}(0) = \frac{(n+1)!}{2\pi i} \int_{|z|=r} \frac{f(z)}{z^{n+2}} \, dz, $$
by using the trivial inequality $\int_{\gamma} h(z) \, dz < l(\gamma) \max_{\gamma} \lvert h(z) \rvert $, where $l(\gamma)$ is the length of $\gamma$, and then taking $r \to R$ (note you have to do this because the function is not known to be holomorphic on the boundary, so you can't just integrate round that directly). However, given the form of the question, the first method is probably the one required.


text:
Q: Firefox protractor testing not working Tried testing (protractor on angularjs application) with firefox 47 and backfired. Tried downgrading to 46.0.1 after SO'ing around, still nothing. Anybody found a current solution? Looks like the solutions keep changing. Now we need a new one. (tests run with chrome so far)
Here's my error;

C:\this\is\my\folder\for\protractor\tests\e2e>protractor conf.js
[11:02:12] I/direct - Using FirefoxDriver directly...
[11:02:12] I/launcher - Running 1 instances of WebDriver
C:\Users\dev\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\webdriver.js:62

let session = flow.execute(function() {

Error: Could not locate Firefox on the current system

at Error (native)

conf.js
exports.config = {
  seleniumAddress: 'http://localhost:4444/wd/hub',

  capabilities: {
      'browserName': 'firefox'
  },

  directConnect: true,

  framework: 'jasmine2',

  specs: ['specs/*spec.js'],
};

A: Protractor cannot locate the Firefox executable on the standard location. To fix this, add the following line:
firefoxPath: 'C:/Programs/Firefox/firefox.exe',

in your 'protractor.config.js' file (after the 'directConnect' property). Of course, the directories names should match these on your machine.
Additional note: if you use portable version of Firefox, try the standard one.


text:
Q: Reformatting Dates Python I have a file with dates in a few different formats and am trying to get them all into YYYYMMDD format in Python. Most of the dates are in the below format:
Mon, 01 Jul 2013 16:33:59 GMT
and I have no idea how to get them into
20130701
I apologize if this is a pretty simple question---I am sort of new to python
EDIT: I am trying to do this for ANY given date. I used the 01 July as an example and in retrospect made it seem like I was asking a different question. So I guess I am looking for something that can both find dates and reformat them

A: Use the python-dateutil library:
from dateutil import parser

dtobject = parser.parse(datestring)

The datutil.parser.parse() method recognises a wide variety of date formats, and returns a datetime.datetime() object.
Use the datetime.strftime() method if you want to format the result as a (uniform) string again:
dtobject.strftime('%Y%m%d')

Demo:
>>> from dateutil import parser
>>> parser.parse('Mon, 01 Jul 2013 16:33:59 GMT')
datetime.datetime(2013, 7, 1, 16, 33, 59, tzinfo=tzlocal())
>>> parser.parse('Mon, 01 Jul 2013 16:33:59 GMT').strftime('%Y%m%d')
'20130701'

A: This can be achieved following way also:
import datetime
x = 'Mon, 01 Jul 2013 16:33:59 GMT'
''.join(str(datetime.datetime.strptime(x, '%a, %d %b %Y  %H:%M:%S %Z').date()).split('-'))

if any other parameter is introduced in your date string, you can include the directive . for example %p is Locale's equivalent of either AM or PM.


text:
Q: how to save ggplots as separate R-objects using For loop It is intended to produce a number of plots and then merge them freely together using multiplot function. Please could you tell me how to save each plot as a separate R-object instead of having it printed as png file:
Examplary dataframe:
 df1 <- data.frame(A = rnorm(50), B = rnorm(50), C = rnorm(50), group = rep(LETTERS[24:25], 25))

we use a for loop to produce pictures and save them in a file:
And the loop to change:
for(i in names(df1)[1:3]) {
  png(paste(i, "png", sep = "."), width = 800, height = 600)
  df2 <- df1[, c(i, "group")]
  print(ggplot(df2) + geom_boxplot(aes_string(x = "group", y = i, fill = "group")) + theme_bw())
  dev.off()
}

Could you please help with changing the code in order to save each plot as  R-object on my screen?
Big Thanks in advance!

A: I'm not sure what you are talking about with "merge them freely together using multiplot function", but you can save ggplot objects using the standard assignment operator. Like any R object, they can be stored in a list.
# empty list for storage
gg_list <- list()

# if you must use a loop, loop through an indexing vector
for(i in 1:3) {
  # if you need the i'th name in df1 use:
  names(df1)[i]
  # assign your ggplot call to the i'th position in the list
  gg_list[[i]]  <- ggplot(...)
}

# Now you can recall the ggplots by reference to the list.
# E.g., display the 1st one:
print(gg_list[[1]])

A: Instead of using a for loop, if you're gonna store in a list you could just use lapply:
df1 <- data.frame(A = rnorm(50),
                  B = rnorm(50),
                  C = rnorm(50),
                  group = rep(LETTERS[24:25], 25))

gg_list <- lapply(names(df1)[1:3], function(i) {
    df2 <- df1[, c(i, "group")]
    ggplot(df2) +
    geom_boxplot(aes_string(x = "group", y = i, fill = "group")) +
    theme_bw()
})

gg_list[[1]]

You can even save the list in an RDS object:
saveRDS(gg_list, file = "./gg_list.RDS")

A: Here's an alternative strategy that I find more straight-forward (no need to fiddle with names and aes_string): melt the data to long format, and plot subsets
 df1 <- data.frame(A = rnorm(50), B = rnorm(50), C = rnorm(50),
                   group = rep(LETTERS[24:25], 25))

m = reshape2::melt(df1, id="group")

## base plot, all the data
p = ggplot(m) + geom_boxplot(aes(x = group, y = value)) + theme_bw()

## split-and-apply strategy, using the `%+%` operator to change datasets
pl = plyr::dlply(m, "variable", `%+%`, e1 = p)

do.call(gridExtra::grid.arrange, pl)


text:
Q: How combine 3 mysql queries together? I have 3 different types of queries to retrieve data in same page. How will I combine altogether? The following is the query:
<?php
$sql = "SELECT * FROM general WHERE ((day1sql >= now()))";
if($_GET!=""){
$mydate = mysql_real_escape_string($_GET['datepicker']);
if($mydate!=""){
$sql = "SELECT * FROM general WHERE ((day1 = '$mydate'))";
}
}
if($_GET!=""){
$city1 = mysql_real_escape_string($_GET['cityText']);
if($city1!=""){
$sql = "SELECT * FROM general WHERE (city = $city1))";
}
}

datepicker is a calendar, users can get data according to date. And Have an dropdown menu, users can select city name. The first two queries is working fine. I am confused how to integrate the third query?

A: You can use the logical OR operator to combine your filter criteria:
SELECT * FROM general WHERE day1sql >= now() OR day1 = '$mydate' OR city = '$city1'

A: Something like this might work:
sql = "SELECT * FROM general WHERE (day1sql >= now())";

if(isset($_GET['datepicker'])){
    $mydate = mysql_real_escape_string($_GET['datepicker']);
    $sql .= " AND (day1 = '$mydate')";
}
if(isset($_GET['cityText'])){
    $city1 = mysql_real_escape_string($_GET['cityText']);
    $sql .= " AND (city = $city1)";
}

// execute $sql

We are appending the sql with AND conditions. I believe that's what you are trying to do.


text:
Q: PandocRuby: set default options (so they will be used whenever I call #convert)? I'm using PandocRuby to generate HTML and docx from the same source.
So far, I simply used PandocRuby.convert two times with quite independent options. But now I want to introduce options (f: 'markdown-raw_html') that need to be applied to both calls, so instead of copy&pasting and creating smelly code, I'd love to set this option somewhere globally.
# config/initializers/pandoc.rb
PANDOC_OPTIONS = {f: 'markdown-raw_html'}

# In my controller, rendering HTML
pandoc_options = PANDOC_OPTIONS.merge(
                   to: :html
                 )

render plain: PandocRuby.convert(report_content, :s, pandoc_options)

# In my controller, rendering docx
pandoc_options = PANDOC_OPTIONS.merge(
                   to: :docx,
                   'toc-depth' => 2
                 ).compact
send_report(PandocRuby.convert(report_content, :toc, pandoc_options), @report, :docx)

But I'm unsure how to do that. My dirty workaround at the moment is to create a global variable PANDOC_OPTIONS and merging it with the additional options of each call, but that's very smelly (and prone to be forgotten somewhere else).
Thanks for suggestions.


text:
Q: Fourier transform of two pulses of light I have laser beam path that fires two pulses of light in a gaussian distribution, so the intensity graph over time is two identical gaussians separated by a distance $t_0$. In other words, a gaussian convolved with two $\delta$ functions equidistant from the origin. When I take the Fourier transform of this, I get a graph with beats, but I'm having trouble figuring out what this graph means physically. When we feed this beam through a spectrometer, we are trying to find out if we should see fringes, and if so, what their frequency is.
Any help would be appreciated.

A: This is a great question because you have to think carefully about what you experiment is actually doing to answer it.
As in Andreas H's answer, you may in principle (and in some practice) see the intensity comb (the "beats" as you call them) at the output of grating spectrometer. But in practice it won't always be like this and you have to analyse your kit a bit more deeply to find out whether you will see the beats or a smooth Gaussian on your image plane.
First and foremost, the laser's coherence time must be greater than the time interval spanned by the two pulses. Otherwise the two pulses' spectrums may tend to add incoherently and you may simply see the spectrum for one pulse alone but simply double in intensity. The laser's and modulation system's physics will have something to say here. If the pulses are made by pulsing the laser's supply current, or by Q-switching, then you will just get to pulses comprising mutually incoherent photons, so you do see simply a continuous Gaussian as the spectrum. If the pulses arise from mode locking, or by passive modulation of a continuous wave, long coherence time laser, then the comb spectrum will in principle be seen at the output.
Now let's think about the grating. Firstly, we need to assume our imaging system for the grating has to be of low enough aberration that the grating spectrometer's output truly is the spatial Fourier transform (Fraunhofer diffraction) of the input aperture (i.e. the grating lit by the time-pulsed field). If there is aberration, or if the output is not truly a far field image, then the output will be some more-compicated-than-simply-the-Fourier-transform diffraction integral (a Fresnel diffraction integral, for instance) of the input aperture, which may mask the comb, so that you may tend to see more like a smooth Gaussian spectrum.
Moreover, the grating's spectrometer abilities arise from the spatial frequency upconversion imposed on a spatial field distribution by multiplying this distribution by an infinitely wide comb function. This spatial frequency upconversion depends on the light's wavelength, so the grating diffracts different wavelength components at different Bragg angles and thus splits spectrum. In practice, the grating is of finite width, i.e. multiplied by some compactly supported gating function. In the Fraunhofer diffraction, this modification by the gating function corresponds to a convolution with the gating function's Fourier transform. So you theoretical Fourier transform of the form $\exp\left(-\frac{x^2}{2\,\sigma^2}\right) \cos(\alpha\,x\,\Delta t)$ get convolved with something like a $\mathrm{sinc}$ function and thus the combs can get smeared into one another, particularly if the time separation between the input pulses is very big. Here $x$ is the sideways distance from the output spectrum's centre, $\alpha$ is set by the system's dimensions and delays and $\Delta t$ is the delay between the two input pulses. The output intensity can thus look more like $\exp\left(-\frac{x^2}{2\,\sigma^2}\right)$.
Lastly, the combs can be very very finely spaced, so, depending on the spatial resolution of your CCD array or whatever sensor you use in the spectrometer, the imaging sensor might impose a spread-out kernel that smears over the combs. In this case, you will also only tend to see a continuous Gaussian spectrum.

A: The spectrometer measures the absolute value squared of the Fourier transform of the input signal, so you see "beating".
It is just a fact that also far "separated" pulses in time domain affect the spectrum and you see beating. But this is nothing mysterious, because if you have two pulses the frequency component corresponding to the inverse time delay is increased in the spectrum, compared to the single pulse case (because there is only a single pulse).
I think the term "beating" is just misleading since it sounds that something needs actively to interact. But this is incorrect. Also the spectrometer, to resolve this beating, always has to measure longer than the inverse of the beat frequency (so the pulses both have to arrive during measurement). This is the uncertainty principle and quite obvious because to discriminate a frequency component from others you have to measure at least for one period length of that beat frequency.
Essentially it lies in the definition of the Fourier transform (and definition of frequency).
If you google frequency comb (that is a laser that has a discrete line spectrum), you will notice that this in time domain are just pulses (e.g. a femtosecond laser).

A: As an aside, this effect is called spectral interferometry in optics.  But it's even seen in seismology of surface waves that go around the earth many times.  If you Fourier transform a long (say 24 hour) surface wave record, the fringes are much narrower than a short recording (say 4 hours).  Here is an example of the same effect in laser ultrasound:  http://acoustics.mines.edu/preprints/PRE46618.pdf Figure 2 shows a surface wave pulse going around a cylinder many times, and Figure 3 shows the periodogram of two pulses vs six.  In the limit of an infinite number of pulses the power spectrum becomes a Dirac comb.


text:
Q: Numbering lines in textarea after enter I have a textarea and I want to numbering lines after enter key press. TextArea at once must display the number "1." and after all pressing enter add next numbers in new line, like "2. ", "3. ".
How to do that in javascript?


text:
Q: static route configuration? i rewiew my router configuration and i found :-
ip route 0.0.0.0 0.0.0.0 Serial1/0:1
ip route 10.0.14.31 255.255.255.255 FastEthernet0/0
what we mean by two command ??? and what we mean by 255.255.255.255 and 0.0.0.0 0.0.0.0

A: Let's dissect this one line at a time.
ip route 0.0.0.0 0.0.0.0 Serial1/0:1

The first ip route command will dictate Serial1/0:1 as a default interface for all packet routing.
ip route 10.0.14.31 255.255.255.255 FastEthernet0/0

The second ip route command dictates that any network packet that is seeking for a destination address that's within the range of 10.0.14.31/255.255.255.255 will be routed through FastEthernet0/0
The value of 255.255.255.255 is a subnet mask value. It is a deterministic value that defines that scope of the network that your router has been assigned to handle.


text:
Q: Cannot install deepdive dependencies on Ubuntu 20.4 I tried installing DeepDive using the code in http://deepdive.stanford.edu/quickstart.
I couldn't install DeepDive, so I installed Deepdive_from_releases Then I tried to install dependencies, but there was an error.
Error I got
I installed python software-properties-common but still not working.


text:
Q: Mixer-Unit on Altera DE2-115 Cyclone IV I'm supposed to add to parallel 16-bits audio signals into a mixer-unit , then run the resulting signal through a parallel 2 serial unit , got 16 errors while trying to use srl functions and other stuff , could you please help ? After the code you will find a picture of the errors.
for this code i use the package Audiofx with it

--  Institute of Microelectronic Systems
--  Architectures and Systems
--  Leibniz Universitaet Hannover
--  lab :           Design Methods for FPGAs
--  file :          mixer_unit.vhdl
--  authors :
--  last update :
--  description :
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

library work;
use work.fpga_audiofx_pkg.all;

entity mixer_unit is
port (
    clock       : in  std_ulogic;
    reset       : in  std_ulogic;`
    -- serial audio-data inputs
    ain_sync    : in  std_ulogic_vector(1 downto 0);
    ain_data    : in  std_ulogic_vector(1 downto 0);
    -- serial audio-data output
    aout_sync   : out std_ulogic;
    aout_data   : out std_ulogic;
    -- Mono
    mono       : out std_ulogic_vector(16 downto 0);
    -- serial mono
    Serialmono  : out std_ulogic
         );
end mixer_unit;

architecture rtl of mixer_unit is

component s2p_unit is
port (
    clock       : in  std_ulogic;
    reset       : in  std_ulogic;
    -- serial audio-data signals
    ain_sync    : in  std_ulogic;
    ain_data    : in  std_ulogic;
    -- parallel audio-data signals
    smp_valid   : out std_ulogic;
    smp_ack     : in  std_ulogic;
    smp_data    : out std_ulogic_vector(15 downto 0)
);
end component s2p_unit;

component p2s_unit is
port (
    clock       : in  std_ulogic;
    reset       : in  std_ulogic;
    -- parallel audio-data signals
    smp_valid   : in  std_ulogic;
    smp_ack     : out std_ulogic;
    smp_data    : in  std_ulogic_vector(SAMPLE_WIDTH-1 downto 0);
    -- serial audio-data signals
    aout_sync   : out std_ulogic;
    aout_data   : out std_ulogic
);
end component p2s_unit;

signal ain_left_sync    : std_ulogic;
signal ain_left_data    : std_ulogic;
signal ain_right_sync   : std_ulogic;
signal ain_right_data   : std_ulogic;

signal test_valid_right : std_ulogic;
signal test_ack_right : std_ulogic;
signal test_valid_left: std_ulogic;
signal test_ack_left : std_ulogic;
signal aout_left_data : std_ulogic_vector(15 downto 0);
signal aout_right_data : std_ulogic_vector(15 downto 0);

begin
mono<= srl(aout_left_data,1) + srl(aout_right_data,1);
serialmono<= p2s_unit(mono);

S2P_left: s2p_unit port map (
clock => clock,
reset => reset,
ain_sync => ain_left_sync,
ain_data => ain_left_data,
smp_valid => test_valid_left ,
smp_ack => test_ack_left ,
smp_data => aout_left_data

);
S2P_right: s2p_unit port map (
clock => clock,
reset => reset,
ain_sync => ain_right_sync,
ain_data => ain_right_data,
smp_valid => test_valid_right ,
smp_ack => test_ack_right ,
smp_data => aout_right_data

);
P2S: p2s_unit port map (
    clock => clock,
    reset => reset,
    -- serial audio-data inputs
    smp_valid => smp_valid,
    smp_ack   => smp_ack,
    smp_data  => smp_data,
    -- serial audio-data output
    aout_sync => aout_sync,
    aout_data => aout_data,
    mono => mono,
    serialmono => serialmono
);

-- ERRORS are shown in the link


text:
Q: Fire a jquery plugins function in ajax done portion I am using a table filter plugin which working just fine but after a AJAXcall when I load certain portion of the page and then call the plugin function in AJAX done method. But this time its not working. I have to reload the page to again get the plugins functionality.
function on page load
(function($) {
    $('#studentTable').ddTableFilter();
})(jQuery);

Function in AJAX Done method
.done(function() {
    var currentPageUrl = window.location.href;
    $('.student_list').load(currentPageUrl + ' .student_list');
    $('#studentTable').ddTableFilter();
});


text:
Q: How to put cloud message on Code Listings fragment on LaTeX I make a presentation 'beamer' with several slides of code using 'Code Listings', I would like to put cloud messages in some reserved words of the code for its explanation.
I have searched and I have not seen any questions or examples that make the messages about 'Code Listings' in the place that I indicate.
Similar to this:

This is possible?
regards

A: An example:

\documentclass{article}
\usepackage{listings}
\usepackage{tikz}
\usetikzlibrary{tikzmark, shapes.callouts}

\begin{document}
\begin{lstlisting}[mathescape]
this is the first$\tikzmark{aux}$ line
This is the second line
\end{lstlisting}

\begin{tikzpicture}[overlay, remember picture]
\node[rectangle callout, rounded corners,
      callout absolute pointer={(pic cs:aux)},
      draw] at ([yshift=1cm]pic cs:aux){Note};
\end{tikzpicture}
\end{document}

Update: For beamer which I skipped reading the question.
\documentclass{beamer}
\usepackage{listings}
\usepackage{tikz}
\usetikzlibrary{tikzmark, shapes.callouts}

\begin{document}

\begin{frame}[fragile]{First frame}
\begin{lstlisting}[mathescape]
this is the first$\tikzmark{aux}$ line
This is the second line
\end{lstlisting}

\begin{tikzpicture}[overlay, remember picture]

\node[rectangle callout, rounded corners, callout absolute pointer={(pic cs:aux)}, draw] at ([yshift=1cm]pic cs:aux){Note};
\end{tikzpicture}
\end{frame}
\end{document}


text:
Q: TypeError: Cannot read property 'XXX' of null
*

*Puppeteer version: 1.0.0

*OS version: Mac OS

*Node.js version: 8.9.1
Error log:
TypeError: Cannot read property 'innerText' of null

here is my code
I am in trouble.Can anyone helps me?


text:
Q: How to change focus color in listview in preferences? First please take a look at picture below:

I already changed background color in text color via @styles like that
 <style name="PreferenceTheme">

    <item name="android:background">#000000</item>
    <item name="android:textColor">#FFFFFF</item>

</style>

In my application i want to change focus color ( when scrolling with optical mouse ). How do i do that? I want to change that color in preferences ( like here on pic ).

A: You can make use of android:listSelector="@android:color/transparent" property in xml.
Ex:
  <ListView
    android:id="@+id/mainListView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:listSelector="@color/white">

</ListView>

Even
android:listSelector="@drawable/list_selector"

also works i guess

A: Use setOnItemClickListener something like this:
YourListView.setOnItemClickListener(new OnItemClickListener() {

     public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                      long arg3) {
     arg1.setBackgroundColor(Color.BLUE);
    }
});


text:
Q: Using Btree to store data of dictionary? I have a problem using btree to store data of 100.000 words in a dictionary ( a word include a head and definition), i don't know how to hash 100.000 words to 100.000 different key with a hash function , my teacher give some hint that just hash 3 first character of word but i can't image what would do with some word have more than 3 character. please help me T_T

A: The idea here is probably that hash-collisions are fine: you calculate a hash (for example by adding the ASCCI values of the first three characters; but that hardly qualifies as "hash" in the real world) and compare the hashes. If they are equal, you do a (more expensive) string comparison. Like:
int compare(Node *left, Node *right) {
    if (left->hash == right->hash) {
        return stringCompare(left, right);
    }

    if (left->hash < right->hash) {
        return -1;
    } else {
        return 1;
    }
}


text:
Q: Parsing Escaped javascript I have the following string which I am trying to parse into a JSON object and then turn into a javascript array:
"[{\"items\":\"nut\",\"sales\":6,\"prices\":10},\n {\"items\":\"bolt\",\"sales\":8,\"prices\":20},\n {\"items\":\"cam\",\"sales\":0,\"prices\":15},\n {\"items\":\"cog\",\"sales\":3,\"prices\":20}]"

which i remove the newline character to get
"{\"items\":\"nut\",\"sales\":6,\"prices\":10}, {\"items\":\"bolt\",\"sales\":8,\"prices\":20}, {\"items\":\"cam\",\"sales\":0,\"prices\":15}, {\"items\":\"cog\",\"sales\":3,\"prices\":20}"

I tried this
   dd = "[{\"items\":\"nut\",\"sales\":6,\"prices\":10},\n {\"items\":\"bolt\",\"sales\":8,\"prices\":20},\n {\"items\":\"cam\",\"sales\":0,\"prices\":15},\n {\"items\":\"cog\",\"sales\":3,\"prices\":20}]";
   dd = dd.replace(/\\n/g, '');
   dd = dd.replace(/[\[\]']+/g,'');
   console.log(JSON.parse(dd));
   dd= JSON.parse(dd));

But this doesnt actually parse the json for some reason as dd.items is null

A:
But this doesnt actually parse the json for some reason as dd.items is
  null

There is no need to remove newline \n from the string, just directly do JSON.parse

var dd = JSON.parse( "[{\"items\":\"nut\",\"sales\":6,\"prices\":10},\n {\"items\":\"bolt\",\"sales\":8,\"prices\":20},\n {\"items\":\"cam\",\"sales\":0,\"prices\":15},\n {\"items\":\"cog\",\"sales\":3,\"prices\":20}]" );
console.log(dd);

Also, dd is an array so you need to iterate dd to get items
dd.forEach( s => console.log(s.items) );

A:

let x = "[{\"items\":\"nut\",\"sales\":6,\"prices\":10},\n {\"items\":\"bolt\",\"sales\":8,\"prices\":20},\n {\"items\":\"cam\",\"sales\":0,\"prices\":15},\n {\"items\":\"cog\",\"sales\":3,\"prices\":20}]";
let y = x.substr(1, x.length - 2).split(',\n').map(JSON.parse);
console.log(y);

A: Use
   JSON.parse(dd);
function to remove this

A:

var data="[{\"items\":\"nut\",\"sales\":6,\"prices\":10},\n {\"items\":\"bolt\",\"sales\":8,\"prices\":20},\n {\"items\":\"cam\",\"sales\":0,\"prices\":15},\n {\"items\":\"cog\",\"sales\":3,\"prices\":20}]";

//use JSON parse that will convert the string to JSON like array of objects please dont do any modification in the returned string

console.log(JSON.parse(data));


text:
Q: Crashlytics Failing to Initialize I am having trouble getting Crashlytics to work with the Amazon Fire TV. I have a project that targets Android, Android TV, and FireTV. Crashlytics seems to work just fine for Android and Android TV, but I'm getting an error when I run it, saying it timed out during initialization.
Here is the error:
04-16 12:30:11.051 6661-6661/com.acompany.app.firetvclient E/CrashlyticsCore: Crashlytics timed out during initialization.
    java.util.concurrent.TimeoutException
        at java.util.concurrent.FutureTask.get(FutureTask.java:176)
        at com.crashlytics.android.core.CrashlyticsCore.finishInitSynchronously(CrashlyticsCore.java:727)
        at com.crashlytics.android.core.CrashlyticsCore.onPreExecute(CrashlyticsCore.java:298)
        at com.crashlytics.android.core.CrashlyticsCore.onPreExecute(CrashlyticsCore.java:211)
        at io.fabric.sdk.android.InitializationTask.onPreExecute(InitializationTask.java:44)
        at io.fabric.sdk.android.services.concurrency.AsyncTask.executeOnExecutor(AsyncTask.java:611)
        at io.fabric.sdk.android.services.concurrency.PriorityAsyncTask.executeOnExecutor(PriorityAsyncTask.java:43)
        at io.fabric.sdk.android.Kit.initialize(Kit.java:69)
        at io.fabric.sdk.android.Fabric.initializeKits(Fabric.java:466)
        at io.fabric.sdk.android.Fabric.init(Fabric.java:410)
        at io.fabric.sdk.android.Fabric.setFabric(Fabric.java:368)
        at io.fabric.sdk.android.Fabric.with(Fabric.java:339)
        at com.crashlytics.android.CrashlyticsInitProvider.onCreate(CrashlyticsInitProvider.java:27)
        at android.content.ContentProvider.attachInfo(ContentProvider.java:1696)
        at android.content.ContentProvider.attachInfo(ContentProvider.java:1671)
        at android.app.ActivityThread.installProvider(ActivityThread.java:5340)
        at android.app.ActivityThread.installContentProviders(ActivityThread.java:4935)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4861)
        at android.app.ActivityThread.access$1500(ActivityThread.java:160)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1382)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5597)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:984)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)

Here is my build.gradle files for my project, and the firetv target:
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
        maven{
            url 'https://maven.fabric.io/public'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.2'
        classpath 'com.google.gms:google-services:4.2.0'
        classpath 'io.fabric.tools:gradle:1.28.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven {
            url "https://maven.fabric.io/public"
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.acompay.app.firetvclient"
        minSdkVersion 22
        targetSdkVersion 28
        versionCode 260
        versionName "2.6.0"
    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        debug {
            debuggable true
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    buildToolsVersion '28.0.3'
}

dependencies {
    compileOnly files('libs/amazon-device-messaging-1.0.1.jar')
    implementation files('assets/api_key.txt')
    implementation 'com.android.support:support-v4:28.0.0'
    implementation 'com.android.support:leanback-v17:28.0.0'
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.google.firebase:firebase-core:16.0.8'
    implementation 'com.crashlytics.sdk.android:crashlytics:2.9.9'
    implementation project(':bftools')
}

apply plugin: 'com.google.gms.google-services'

Do I need to set up Crashlytics differently for the Fire TV? I don't really understand why I'm getting that error.


text:
Q: Loop over only the names that match the string instead of the entire array There are two names stored in ^ZNAME and they are MITCHELL, DAVID J and SMITH, JOHN A.
N prompt,val
S prompt="Enter a name (LAST,FIRST MI): "
F  W !,prompt R val Q:val=""  D
.   I val'?1.A1",".1" "1.A.1(1" "1A) W !,"Invalid name"
.   E  S ^ZNAME(val)=""
F  S val=$O(^ZNAME(val)) Q:val=""  D
.   W !,"You entered: ",val
Q

^ZNAME("MITCHELL, DAVID J")
^ZNAME("SMITH, JOHN A")

I can enter "SM" and get the desired results of SMITH, JOHN A. But I want to improve this code to loop over only the names that match the string instead of the entire array. I have been at this for two days now. I have added $L and $E commands to this code, but failed at getting the desired result. I definitely want to know what I am doing wrong. Would someone be able to offer guidance on the steps to obtain this improvement. Thank you.
N partial,val
S partial="Enter a name or partial name: "
F  W !,partial R val Q:val=""  D
.   W !,$O(^ZNAME(val))
Q

I made some changes to the code to try and get the result but it keeps reading the ^ZNAME and not reading in the name.
N name,val,len,pos,char,
    S name="Enter a name or partial name: "
    I name=""  Q
    S len=$L(name)
    F pos=1:1:len  D
    .S char=$E(name,pos)
    S char=""
    F  S char=$O(^ZNAME(char)) Q:char=""  D
    .W !,char
    Q

A: Why ^ZNAME("val") when it should be ^ZNAME(val)


text:
Q: Bootstrap Navbar not rendering on Heroku (Meteor) I am running a Meteor app on Heroku with a bootstrap Navbar. My local version runs fine however when I deploy to Heroku the Navbar doesn't render. Some people experiencing similar issues in Rails had to precompile the assets in order to solve this problem.
Has anyone come across a similar issue using Heroku/Meteor and how did you resolve it?

A: It was a Meteor issue, some helper functions were buggy. It was not a heroku / bootstrap issue.


text:
Q: invalid arithmetic operator working with cygwin and writing a script to show my my current ip address minus 2.  For some reason it is giving me the follwing error:  ")syntax error: invalid arithmetic operator (error token is "
this is the script I am using.
$ cat test3.sh
#!/bin/bash
#
function IPADDRESS {
    v=$4
    echo $1.$2.$3.$((v-2))
}
ADDRESS=$(ipconfig | grep Address | cut -f2 -d :)
# echo $ADDRESS
IPADDRESS ${ADDRESS//\./ }

any help or suggestion is apprieciated!

A: You've actually got a couple of problems with that script. The major one is that ipconfig will output "\r" characters at the end of the line which stuffs up the calculation.
Another is that you're not allowing for multiple NICs, hence my "head -1" addition. You'll need to select which NIC you want a little more intelligently.
And finally, I stripped out the leading space (actually all spaces) from the front of the IP address.
The following works for me:
#!/bin/bash
#set -x

function IPADDRESS {
    ((v = $4 - 2))
    echo $1.$2.$3.$v
}
ADDRESS=$(ipconfig | grep Address | head -1 | cut -f2 -d: | sed 's/[ \r]//g')
echo $ADDRESS
IPADDRESS $ADDRESS

outputting:
192.168.91.7
192.168.91.5

Actually, my version output the following:
192.168.91.1
192.168.91.-1

so you'll need to watch out for that.
I'm no stranger to dummying up the output to impress/cajole management :-).
USEFUL SNIPPET:
The "set -x" at the top of the script (when un-commented) is ideal for finding these sorts of errors. It outputs each line after all the substitutions but before executing, so that you can see exactly what's going on.

A: I tried a couple different combinations.  The following worked for me.  The set -x really helped.  Thanks again.
#!/bin/bash
#set -x
function IPADDRESS {
    v=$4
echo $1.$2.$3.$((v-2))
}
ADDRESS=$(ipconfig | grep Address | head -1 | cut -f2 -d: | sed 's/[ \r]//g')
IPADDRESS ${ADDRESS//\./}


text:
Q: CMake: Enable '/arch:AVX2' in Visual Studio 2013 projects I'm trying to enable AVX2 code-generation via CMake on my Visual Studio 2013 projects and so far, I'm out of luck.
Things I've tried are:

*

*Set CMAKE_CXX_FLAGS_* to include /arch:AVX2 like so: SET(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /arch:AVX2")

*Set target properties like so: SET_TARGET_PROPERTIES("myproject" PROPERTIES COMPILE_FLAGS "/arch:AVX2"). I also tried replacing COMPILE_FLAGS with COMPILE_DEFINITIONS, COMPILE_FEATURES (fails to generate project) and COMPILE_OPTIONS.

Each time I try generating the projects, I would make sure to delete the CMake cache so that it doesn't get in the way of generating the project files.
What am I missing? Any help to shed light on this would be much appreciated. Thanks for your time.


text:
Q: Can i be two places at once in python cycle I'm doing this in python, in case that changes anything.
I'm trying to make a lamp/bit go 1-0-1-0 until the user says "okay"
the "okay" should indicate that the user has found the lamp/Bit IRL.
Now i'm struggling to find a way to ask the user a question, (because it stops the program cycle), when I also want the lamp bit to go On/Off on repeat, while waiting for the user to write yes or click yes
Atm i'm looking at this idea
def click(x, y):
    win32api.SetCursorPos((x, y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)

newLampsadded = int(input( " How many new lamps : " ))
lamps = newLampsadded - 1

for lamp in range(lamps):
    while feedback is not "y":
        Click(x, y)              #On
        Click(x+50, y+10)        #Off
        feedback = input("have you found the lamp y/n") #Is the lamp found

anyway i can get a feedback that doesnt stop the cycle of turning the lamp On/Off
Thanks

A: I'm not immediately familiar with the Win32API, but you're going to need to multi-thread this application. Because the for loop for the click needs to happen at the same time as your input (which is a blocking call) it needs to happen on a different thread.


text:
Q: How to add properties to a styled material-ui props class in react with typescript I am wanting to use material-ui, using react and typescript. I would like to pass properties to the components, but cannot figure out how to do it. I am using the react-typescript example from the material-UI repo. What I tried is as follows:
Add a properties interface:
const styles = (theme: Theme) =>
  createStyles({
    root: {
      textAlign: 'center',
      paddingTop: theme.spacing.unit * 20,
    },
  });

interface IndexProps
  extends WithStyles<typeof styles> {
  myText: string;
}

then define my component, and use the property:
class Index extends React.Component<IndexProps> {
  render() {
    return (
      <div className={this.props.classes.root}>
        <Typography variant="display1" gutterBottom>
          Material-UI
        </Typography>
        <Typography variant="subheading" gutterBottom>
          example project text=[{this.props.myText}]
        </Typography>
        <Button variant="raised" color="secondary" >
          Super Secret Password
        </Button>
      </div>
    );
  }
}

export default withRoot(withStyles(styles)(Index));

On my Index page I put:
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import Index from './pages/index';

ReactDOM.render(<Index myText="Foo" />, document.querySelector('#root'));

But get a compile error:
(5,18): Type '{ myText: string; }' has no properties in common with type 'IntrinsicAttributes'.

What am I doing wrong here? Any help would be greatly appreciated
For completeness, my packages.json file is:
{
  "name": "create-react-app-with-typescript",
  "version": "0.1.0",
  "private": true,
  "main": "src/index.tsx",
  "dependencies": {
    "@material-ui/core": "latest",
    "@types/react": "*",
    "@types/react-dom": "*",
    "react": "latest",
    "react-dom": "latest",
    "react-scripts-ts": "latest"
  },
  "devDependencies": {
    "@types/jest": "*",
    "@types/node": "*",
    "typescript": "latest"
  },
  "scripts": {
    "start": "react-scripts-ts start",
    "build": "react-scripts-ts build",
    "test": "react-scripts-ts test --env=jsdom",
    "eject": "react-scripts-ts eject"
  }
}

A: I'm assuming that you are using this definition of withRoot.  If you hover over the call to withRoot, you'll see its return type is:
(props: object) => JSX.Element

This is wrong: the props type should be {myText: string}, not object.  If you go to the definition of withRoot, you'll see where this is coming from:
function withRoot(Component: React.ComponentType) {
  function WithRoot(props: object) {

Those lines should be replaced with:
function withRoot<P>(Component: React.ComponentType<P>) {
  function WithRoot(props: P) {

You could consider sending a pull request to fix this in the original example.
Round 2
(Referring to the example in the comment)
This turns out to have an unrelated root cause.  I see the error on src/App.tsx line 60:
let drawer = <ItemsList myText="asdf" history={history} />;

referring to the definition at the bottom of src/components/ItemsList.tsx:
export default withStyles(styles)<{}>(connect(mapStateToProps)(withWidth()(ItemsList))
);

For starters, get rid of that explicit type argument <{}>, which is overriding whatever is being determined automatically; I'm surprised that didn't give you an error by itself.  Then the error in App.tsx changes to say that the location prop is missing.  You might already recognize this as one of the RouteComponentProps, but I didn't, so I proceeded to look at the entire set of props of the final component by adding the following to ItemsList.tsx:
type PropsOf<C> = C extends React.ComponentType<infer P> ? P : never;
const ItemsListWrapped = withStyles(styles)(connect(mapStateToProps)(withWidth()(ItemsList));
type FinalProps = PropsOf<typeof ItemsListWrapped>;
let x: FinalProps;
x.  // look at completion menu here (Ctrl-Space in Visual Studio Code)

Unfortunately, these complicated type operations give rise to type expressions that are hard to understand or even get truncated in the hover pop-up, so the best way I found to see all the props was to look at the completion menu, as indicated.  Then we see four unexpected props: history, location, match, and staticContext.  If we look at all the places these might have come from, hopefully they are recognizable as coming from the ItemsList.Props extends RouteComponentProps<void>.  Indeed, that declaration is wrong because you are not using ItemsList as a route component nor manually passing all of those props, nor does ItemsList actually use any of the props except for history, which you declare again (and do pass).  So just remove RouteComponentProps<void> from the extends list.
As we've seen, type errors on using a wrapped React component can have many different causes.  I hope I've given you some sense of how to track down future such errors yourself.


text:
Q: syncookies and tcp options enabling syncookies is  helping against some attacks
but the official docs still say syncookies seriously violate TCP protocol, do not allow
    to use TCP extensions
Today I discover that once upon a time in the kernel development syncookies were extended to handle also Timestamp, ECN, SACK, WScale
So

*

*how can I find from which kernel version ?

*enabling syncookies and also Timestamp, ECN, SACK, WScale : how do other operating systems behave ?