问:
Fast way reduce noise of autocorrelation function in python?
I can compute the autocorrelation using numpy's built in functionality:
numpy.correlate(x,x,mode='same')

However the resulting correlation is naturally noisy. I can partition my data, and compute the correlation on each resulting window, then average them all together to compute cleaner autocorrelation, similar to what signal.welch does. Is there a handy function in either numpy or scipy that does this, possibly faster than I would get if I were to compute partition and loop through the data myself?

UPDATE

This is motivated by @kazemakase answer. I have tried to show what I mean with some code used to generate the figure below.

One can see that @kazemakase is correct with the fact that the AC function naturally averages out the noise. However the averaging of the AC has the advantage that it is much faster! np.correlate seems to scale as the slow O(n^2) rather than O(nlogn) that I would expect if the correlation was calculated using circular convolution via the FFT...

```<code>from statsmodels.tsa.arima_model import ARIMA
import statsmodels as sm
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(12345)
arparams = np.array([.75, -.25, 0.2, -0.15])
maparams = np.array([.65, .35])
ar = np.r_[1, -arparams] # add zero-lag and negate
ma = np.r_[1, maparams] # add zero-lag
x = sm.tsa.arima_process.arma_generate_sample(ar, ma, 10000)

def calc_rxx(x):
    x = x-x.mean()
    N = len(x)
    Rxx = np.correlate(x,x,mode="same")[N/2::]/N
    #Rxx = np.correlate(x,x,mode="same")[N/2::]/np.arange(N,N/2,-1)
    return  Rxx/x.var()

def avg_rxx(x,nperseg=1024):
    rxx_windows = []
    Nw = int(np.floor(len(x)/nperseg))
    print Nw
    first = True
    for i in range(Nw-1):
        xw = x[i*nperseg:nperseg*(i+1)]
        y = calc_rxx(xw)
        if i%1 == 0:
            if first:
                plt.semilogx(y,"k",alpha=0.2,label="Short AC")
                first = False
            else:
                plt.semilogx(y,"k",alpha=0.2)

        rxx_windows.append(y)

    print np.shape(rxx_windows)
    return np.mean(rxx_windows,axis=0)

plt.figure()
r_avg = avg_rxx(x,nperseg=300)
r = calc_rxx(x)
plt.semilogx(r_avg,label="Average AC")
plt.semilogx(r,label="Long AC")

plt.xlabel("Lag")
plt.ylabel("Auto-correlation")
plt.legend()
plt.xlim([0,150])
plt.show()
</code>```

答:
TL-DR: To decrease noise in the autocorrelation function increase the length of your signal x.

Partitioning the data and averaging like in spectral estimation is an interesting idea. I wish it would work...

The autocorrelation is defined as

Let's say we partition the data into two windows. Their autocorrelations become

Note how they are only different in the limits of the sumations. Basically, we split the summation of the autocorrelation into two parts. When we add these back together we are back to the original autocorrelation! So we did not gain anything.

The conclusion is, there is no such thing implemented in numpy/scipy because there is no point in doing so.

Remarks:

I hope it's easy to see that this extends to any number of partitions.

to keep it simple I left the normalization out. If you divide Rxx by n and the partial Rxx by n/2 you get Rxx / n == (Rxx1 * 2/n + Rxx2 * 2/n) / 2. I.e. The mean of the normalized partial autocorrelation is equal to the complete normalized autocorrelation.

to keep it even simpler I assumed the signal x could be indexed beyond the limits of 0 and n-1. In practice, if the signal is stored in an array this is often not possible. In this case there is a small difference between the full and the partialized autocorrelations that increases with the lag l. Unfortunately, this is merely a loss of precision and does not reduce noise.

Code heretic! I don't belive your evil math!

Of course we can try things out and see:

```<code>import matplotlib.pyplot as plt
import numpy as np

n = 2**16
n_segments = 8

x = np.random.randn(n)  # data

rx = np.correlate(x, x, mode='same') / n  # ACF
l1 = np.arange(-n//2, n//2)  # Lags

segments = x.reshape(n_segments, -1)
m = segments.shape[1]

rs = []
for y in segments:
    ry = np.correlate(y, y, mode='same') / m  # partial ACF
    rs.append(ry)

l2 = np.arange(-m//2, m//2)  # lags of partial ACFs

plt.plot(l1, rx, label='full ACF')
plt.plot(l2, np.mean(rs, axis=0), label='partial ACF')
plt.xlim(-m, m)
plt.legend()
plt.show()
</code>```

Although we used 8 segments to average the ACF, the noise level visually stays the same.

Okay, so that's why it does not work but what is the solution?

Here are the good news: Autocorrelation is already a noise reduction technique! Well, in some way at least: An application of the ACF is to find periodic signals hidden by noise.

Since noise (ideally) has zero mean, its influence diminishes the more elements we sum up. In other words, you can reduce noise in the autocorrelation by using longer signals. (I guess this is probably not true for every type of noise, but should hold for the usual Gaussian white noise and its relatives.)

Behold the noise getting lower with more data samples:

```<code>import matplotlib.pyplot as plt
import numpy as np

for n in [2**6, 2**8, 2**12]:
    x = np.random.randn(n)

    rx = np.correlate(x, x, mode='same') / n  # ACF
    l1 = np.arange(-n//2, n//2)  # Lags

    plt.plot(l1, rx, label='n={}'.format(n))

plt.legend()
plt.xlim(-20, 20)
plt.show()
</code>```

Body:
I can compute the autocorrelation using numpy's built in functionality:
numpy.correlate(x,x,mode='same')

However the resulting correlation is naturally noisy. I can partition my data, and compute the correlation on each resulting window, then average them all together to compute cleaner autocorrelation, similar to what signal.welch does. Is there a handy function in either numpy or scipy that does this, possibly faster than I would get if I were to compute partition and loop through the data myself?

UPDATE

This is motivated by @kazemakase answer. I have tried to show what I mean with some code used to generate the figure below.

One can see that @kazemakase is correct with the fact that the AC function naturally averages out the noise. However the averaging of the AC has the advantage that it is much faster! np.correlate seems to scale as the slow O(n^2) rather than O(nlogn) that I would expect if the correlation was calculated using circular convolution via the FFT...

from statsmodels.tsa.arima_model import ARIMA
import statsmodels as sm
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(12345)
arparams = np.array([.75, -.25, 0.2, -0.15])
maparams = np.array([.65, .35])
ar = np.r_[1, -arparams] # add zero-lag and negate
ma = np.r_[1, maparams] # add zero-lag
x = sm.tsa.arima_process.arma_generate_sample(ar, ma, 10000)

def calc_rxx(x):
    x = x-x.mean()
    N = len(x)
    Rxx = np.correlate(x,x,mode="same")[N/2::]/N
    #Rxx = np.correlate(x,x,mode="same")[N/2::]/np.arange(N,N/2,-1)
    return  Rxx/x.var()

def avg_rxx(x,nperseg=1024):
    rxx_windows = []
    Nw = int(np.floor(len(x)/nperseg))
    print Nw
    first = True
    for i in range(Nw-1):
        xw = x[i*nperseg:nperseg*(i+1)]
        y = calc_rxx(xw)
        if i%1 == 0:
            if first:
                plt.semilogx(y,"k",alpha=0.2,label="Short AC")
                first = False
            else:
                plt.semilogx(y,"k",alpha=0.2)

        rxx_windows.append(y)

    print np.shape(rxx_windows)
    return np.mean(rxx_windows,axis=0)

plt.figure()
r_avg = avg_rxx(x,nperseg=300)
r = calc_rxx(x)
plt.semilogx(r_avg,label="Average AC")
plt.semilogx(r,label="Long AC")

plt.xlabel("Lag")
plt.ylabel("Auto-correlation")
plt.legend()
plt.xlim([0,150])
plt.show()

Body:
TL-DR: To decrease noise in the autocorrelation function increase the length of your signal x.

Partitioning the data and averaging like in spectral estimation is an interesting idea. I wish it would work...

The autocorrelation is defined as

Let's say we partition the data into two windows. Their autocorrelations become

Note how they are only different in the limits of the sumations. Basically, we split the summation of the autocorrelation into two parts. When we add these back together we are back to the original autocorrelation! So we did not gain anything.

The conclusion is, there is no such thing implemented in numpy/scipy because there is no point in doing so.

Remarks:

I hope it's easy to see that this extends to any number of partitions.

to keep it simple I left the normalization out. If you divide Rxx by n and the partial Rxx by n/2 you get Rxx / n == (Rxx1 * 2/n + Rxx2 * 2/n) / 2. I.e. The mean of the normalized partial autocorrelation is equal to the complete normalized autocorrelation.

to keep it even simpler I assumed the signal x could be indexed beyond the limits of 0 and n-1. In practice, if the signal is stored in an array this is often not possible. In this case there is a small difference between the full and the partialized autocorrelations that increases with the lag l. Unfortunately, this is merely a loss of precision and does not reduce noise.

Code heretic! I don't belive your evil math!

Of course we can try things out and see:

import matplotlib.pyplot as plt
import numpy as np

n = 2**16
n_segments = 8

x = np.random.randn(n)  # data

rx = np.correlate(x, x, mode='same') / n  # ACF
l1 = np.arange(-n//2, n//2)  # Lags

segments = x.reshape(n_segments, -1)
m = segments.shape[1]

rs = []
for y in segments:
    ry = np.correlate(y, y, mode='same') / m  # partial ACF
    rs.append(ry)

l2 = np.arange(-m//2, m//2)  # lags of partial ACFs

plt.plot(l1, rx, label='full ACF')
plt.plot(l2, np.mean(rs, axis=0), label='partial ACF')
plt.xlim(-m, m)
plt.legend()
plt.show()

Although we used 8 segments to average the ACF, the noise level visually stays the same.

Okay, so that's why it does not work but what is the solution?

Here are the good news: Autocorrelation is already a noise reduction technique! Well, in some way at least: An application of the ACF is to find periodic signals hidden by noise.

Since noise (ideally) has zero mean, its influence diminishes the more elements we sum up. In other words, you can reduce noise in the autocorrelation by using longer signals. (I guess this is probably not true for every type of noise, but should hold for the usual Gaussian white noise and its relatives.)

Behold the noise getting lower with more data samples:

import matplotlib.pyplot as plt
import numpy as np

for n in [2**6, 2**8, 2**12]:
    x = np.random.randn(n)

    rx = np.correlate(x, x, mode='same') / n  # ACF
    l1 = np.arange(-n//2, n//2)  # Lags

    plt.plot(l1, rx, label='n={}'.format(n))

plt.legend()
plt.xlim(-20, 20)
plt.show()


来源: stackexchange

问:
How can I get today's timestamp in PHP
I tried

```<code>$dtToday = DateTime::createFromFormat('Y-m-d', date('Y-m-d'));
</code>```

but when I output it

```<code>die($dtToday->format('d M Y g:i:s a'));
</code>```

I still get the time eg "22 Jan 2011 4:53:59 pm". Why is that?

UPDATE

Ah... many people misunderstood me, my bad, I forgot to point out the main point. I created the date with just the date portion, I don't want the time. So I'd expect something like

```<code>22 Jan 2011 12:00:00 am
</code>```

答:
Remove this part g:i:s a from your code.

Now, if you want a nice date formatted according to your local, i recommand you to use strftime() function.

ContentLicense: CC BY-SA 2.5

Title: How can I get today's timestamp in PHP

Body:
I tried

$dtToday = DateTime::createFromFormat('Y-m-d', date('Y-m-d'));

but when I output it

die($dtToday->format('d M Y g:i:s a'));

I still get the time eg "22 Jan 2011 4:53:59 pm". Why is that?

UPDATE

Ah... many people misunderstood me, my bad, I forgot to point out the main point. I created the date with just the date portion, I don't want the time. So I'd expect something like

22 Jan 2011 12:00:00 am


问:
Missing one element of dictionary cause of If statement
i use this code to store items of dictionaries in doc variable.
This code works fine but I miss the first element of time because of the if statement.

```<code>def convert(old):
    time_key = 'Time '
    # Save the time
    time_item = (time_key, old[time_key])
    # Add remove it
    del old[time_key]
    # Copy remaining items to new dicts and save them in a list
    return [dict([time_item, item]) for item in old.items()]

row = {
    'Time ': '2017-12-01T13:54:04',
    'Energy [kWh]': '0.01',
    'Voltage [V]': '221.64',
    'Current [A]': '0.08',
}

new_data = convert(row)
#print(new_data)
Zeitvalue= ""
Device=""
Value=""
for d in new_data:
    #print(d)
    for key, value in d.items():
        if key == 'Time ':
            Zeitvalue = value
            #print(value)
            continue
        else:
            Device = key
            Value = value
        doc = {'Time ':Zeitvalue,'Device':Device, 'Measure':Value}
        print("This is doc variable:",doc) # doc vaiable with missed time element
</code>```

SO when i print doc i got this
Output:

```<code>doc:     {'Device': 'Voltage [V]', 'Measure': '221.64', 'Time ': ''} # **ISSUE: variable time is missed here, How to fix it ?**
   doc:     {'Device': 'Current [A]', 'Measure': '0.08', 'Time ': '2017-12-01T13:54:04'}
   doc:     {'Device': 'Energy [kWh]', 'Measure': '0.01', 'Time ': '2017-12-01T13:54:04'}
</code>```

答:
See the below changes in the code. Remove continue statement. Also assign value to doc after the inner loop for dictionary is over as you need all three values.</p>

```<code>for d in new_data:
#print(d)
    for key, value in d.items():
        if key == 'Time ':
            Zeitvalue = value
            #print(value)

        else:
            Device = key
            Value = value

    doc = {'Time ':Zeitvalue,'Device':Device, 'Measure':Value}
    print(doc)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i use this code to store items of dictionaries in doc variable.
This code works fine but I miss the first element of time because of the if statement.

def convert(old):
    time_key = 'Time '
    # Save the time
    time_item = (time_key, old[time_key])
    # Add remove it
    del old[time_key]
    # Copy remaining items to new dicts and save them in a list
    return [dict([time_item, item]) for item in old.items()]

row = {
    'Time ': '2017-12-01T13:54:04',
    'Energy [kWh]': '0.01',
    'Voltage [V]': '221.64',
    'Current [A]': '0.08',
}

new_data = convert(row)
#print(new_data)
Zeitvalue= ""
Device=""
Value=""
for d in new_data:
    #print(d)
    for key, value in d.items():
        if key == 'Time ':
            Zeitvalue = value
            #print(value)
            continue
        else:
            Device = key
            Value = value
        doc = {'Time ':Zeitvalue,'Device':Device, 'Measure':Value}
        print("This is doc variable:",doc) # doc vaiable with missed time element

SO when i print doc i got this
Output:

doc:     {'Device': 'Voltage [V]', 'Measure': '221.64', 'Time ': ''} # **ISSUE: variable time is missed here, How to fix it ?**
   doc:     {'Device': 'Current [A]', 'Measure': '0.08', 'Time ': '2017-12-01T13:54:04'}
   doc:     {'Device': 'Energy [kWh]', 'Measure': '0.01', 'Time ': '2017-12-01T13:54:04'}

Body:
See the below changes in the code. Remove continue statement. Also assign value to doc after the inner loop for dictionary is over as you need all three values.

for d in new_data:
#print(d)
    for key, value in d.items():
        if key == 'Time ':
            Zeitvalue = value
            #print(value)

        else:
            Device = key
            Value = value

    doc = {'Time ':Zeitvalue,'Device':Device, 'Measure':Value}
    print(doc)


问:
Sequelize findOrCreate returns SequelizeUniqueContraintError on a model with an additional unique keys
I am using Sequelize with NodeJS and MySql. (latest versions)

I have a user model with -

'id' and unique and primary key. 'id' is set to auto increment.

some user details such as firstName, lastName, email etc.

Two additional unique keys  (marked as unique in the sequelize model and in the database) - 'username' and 'email'

I am using the  'findOrCreate' method to create or lookup. My code creates a record if it does not exist but throws a UniqueConstraintError (ER_DUP_ENTRY) --> SequelizeUniqueContraintError on the "username" field when I try to find this record. Basically, the findOrCreate tries to create a record for the second time instead of finding it.

I was able to fix this issue by manually doing a find and if not found
  then create. But I need the flag returned by the 'findOrCreate' method
  which helps determine whether a record was created or found.

Can someone please help?

答:
I was able to resolve this by passing the unique key to the 'findOrCreate' method of the model in the 'where' clause and setting values for all other table attributes in the 'defaults' clause.

For Eg. - Employee.findOrCreate({where: {employeeId: 'ABCD1234'}, defaults: {role: 'Analyst'}});

Where employeeId is a Unique Key. (I assume that the primary key 'id' field is set to Auto Increment)

Please refer to the example provided in the official tutorial. here


问:
client certificate forwarding from haproxy to tomcat
I've been using httpd to offload my SSL processing and forward http requests to tomcat via AJP. I'm now moving to haproxy instead of httpd and HTTP instead of AJP. I am able to connect to haproxy via https and see an appropriate http request arrive at tomcat. when trying to verify the client certificate my tomcat code cannot retrieve the CN from the certificate. I added the following lines to haproxy.cfg in the hope that it will forward the client certificate information in the http header:

```<code>http-request set-header X-SSL                       %[ssl_fc]
http-request set-header X-SSL-Client-Verify         %[ssl_c_verify]
http-request set-header X-SSL-Client-SHA1           %{+Q}[ssl_c_sha1]
http-request set-header X-SSL-Client-DN             %{+Q}[ssl_c_s_dn]
http-request set-header X-SSL-Client-CN             %{+Q}[ssl_c_s_dn(cn)]
http-request set-header X-SSL-Issuer                %{+Q}[ssl_c_i_dn]
http-request set-header X-SSL-Client-Not-Before     %{+Q}[ssl_c_notbefore]
http-request set-header X-SSL-Client-Not-After      %{+Q}[ssl_c_notafter]
</code>```

looking at the capture file for the http connection I see the following http header:

```<code>GET /api/subscriber/count?_=1511258656303 HTTP/1.1
Host: 192.168.20.192
Accept: */*
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
Referer: https://192.168.20.192/dashboard.jsp
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8,he;q=0.6
Cookie: gsScrollPos-1158=0; gsScrollPos-536=0; gsScrollPos-873=2579; gsScrollPos-2263=0; gsScrollPos-472=0; gsScrollPos-468=; JSESSIONID=B433B96FB2616A8447703BFAE541DC2C
X-SSL: 1
X-SSL-Client-Verify: 0
X-SSL-Client-SHA1:
X-SSL-Client-DN:
X-SSL-Client-CN:
X-SSL-Issuer:
X-SSL-Client-Not-Before:
X-SSL-Client-Not-After:
X-Forwarded-Proto: https
X-Forwarded-For: ::ffff:192.168.12.171
Connection: close
</code>```

as you can see the certificate information is blank.

Am I doing something wrong? is there something else needed to pass the certificate to tomcat?
alternatively can this be made to work using AJP?

here is my full haproxy.cfg:

```<code>global
    log         127.0.0.1 local4

    chroot      /var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     4000
    user        haproxy
    group       haproxy
    daemon

    # turn on stats unix socket
    stats socket /var/lib/haproxy/stats

    # ssl ciphers and options
    ssl-default-bind-options no-sslv3
    ssl-default-bind-ciphers ECDH+AESGCM:ECDH+AES256:ECDH+AES128:ECDH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS
    tune.ssl.default-dh-param 2048

#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------
defaults
    mode                    http
    log                     global
    option                  httplog
    option                  dontlognull
    option http-server-close
    option forwardfor       except 127.0.0.0/8
    option                  redispatch
    retries                 3
    timeout http-request    10s
    timeout queue           1m
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    timeout http-keep-alive 10s
    timeout check           10s
    maxconn                 3000

frontend https
    mode http
    bind :::443 ssl crt /opt/vasona/CA/private/sa_bundle.pem ca-file /opt/vasona/CA/certs/crtServer.crt verify optional

    http-request set-header X-SSL                       %[ssl_fc]
    http-request set-header X-SSL-Client-Verify         %[ssl_c_verify]
    http-request set-header X-SSL-Client-SHA1           %{+Q}[ssl_c_sha1]
    http-request set-header X-SSL-Client-DN             %{+Q}[ssl_c_s_dn]
    http-request set-header X-SSL-Client-CN             %{+Q}[ssl_c_s_dn(cn)]
    http-request set-header X-SSL-Issuer                %{+Q}[ssl_c_i_dn]
    http-request set-header X-SSL-Client-Not-Before     %{+Q}[ssl_c_notbefore]
    http-request set-header X-SSL-Client-Not-After      %{+Q}[ssl_c_notafter]
    reqadd X-Forwarded-Proto:\ https
    default_backend tomcat-mgmt

backend tomcat-mgmt
    mode http
    option tcp-smart-connect
    server tomcat :8009

backend tomcat-cp-events
    mode http
    option tcp-smart-connect
    server tomcat :23237
</code>```

please let me know if any other info is needed.
Thanks,
Gidon

答: turns out I was using the wrong certificate file as ca-file. once using the correct pem file the certificate information passes to the backend correctly.</p>

Body:
I've been using httpd to offload my SSL processing and forward http requests to tomcat via AJP. I'm now moving to haproxy instead of httpd and HTTP instead of AJP. I am able to connect to haproxy via https and see an appropriate http request arrive at tomcat. when trying to verify the client certificate my tomcat code cannot retrieve the CN from the certificate. I added the following lines to haproxy.cfg in the hope that it will forward the client certificate information in the http header:

http-request set-header X-SSL                       %[ssl_fc]
http-request set-header X-SSL-Client-Verify         %[ssl_c_verify]
http-request set-header X-SSL-Client-SHA1           %{+Q}[ssl_c_sha1]
http-request set-header X-SSL-Client-DN             %{+Q}[ssl_c_s_dn]
http-request set-header X-SSL-Client-CN             %{+Q}[ssl_c_s_dn(cn)]
http-request set-header X-SSL-Issuer                %{+Q}[ssl_c_i_dn]
http-request set-header X-SSL-Client-Not-Before     %{+Q}[ssl_c_notbefore]
http-request set-header X-SSL-Client-Not-After      %{+Q}[ssl_c_notafter]

looking at the capture file for the http connection I see the following http header:

GET /api/subscriber/count?_=1511258656303 HTTP/1.1
Host: 192.168.20.192
Accept: */*
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
Referer: https://192.168.20.192/dashboard.jsp
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8,he;q=0.6
Cookie: gsScrollPos-1158=0; gsScrollPos-536=0; gsScrollPos-873=2579; gsScrollPos-2263=0; gsScrollPos-472=0; gsScrollPos-468=; JSESSIONID=B433B96FB2616A8447703BFAE541DC2C
X-SSL: 1
X-SSL-Client-Verify: 0
X-SSL-Client-SHA1:
X-SSL-Client-DN:
X-SSL-Client-CN:
X-SSL-Issuer:
X-SSL-Client-Not-Before:
X-SSL-Client-Not-After:
X-Forwarded-Proto: https
X-Forwarded-For: ::ffff:192.168.12.171
Connection: close

as you can see the certificate information is blank.

Am I doing something wrong? is there something else needed to pass the certificate to tomcat?
alternatively can this be made to work using AJP?

here is my full haproxy.cfg:

global
    log         127.0.0.1 local4

    chroot      /var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     4000
    user        haproxy
    group       haproxy
    daemon

    # turn on stats unix socket
    stats socket /var/lib/haproxy/stats

    # ssl ciphers and options
    ssl-default-bind-options no-sslv3
    ssl-default-bind-ciphers ECDH+AESGCM:ECDH+AES256:ECDH+AES128:ECDH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS
    tune.ssl.default-dh-param 2048

#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------
defaults
    mode                    http
    log                     global
    option                  httplog
    option                  dontlognull
    option http-server-close
    option forwardfor       except 127.0.0.0/8
    option                  redispatch
    retries                 3
    timeout http-request    10s
    timeout queue           1m
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    timeout http-keep-alive 10s
    timeout check           10s
    maxconn                 3000

frontend https
    mode http
    bind :::443 ssl crt /opt/vasona/CA/private/sa_bundle.pem ca-file /opt/vasona/CA/certs/crtServer.crt verify optional

    http-request set-header X-SSL                       %[ssl_fc]
    http-request set-header X-SSL-Client-Verify         %[ssl_c_verify]
    http-request set-header X-SSL-Client-SHA1           %{+Q}[ssl_c_sha1]
    http-request set-header X-SSL-Client-DN             %{+Q}[ssl_c_s_dn]
    http-request set-header X-SSL-Client-CN             %{+Q}[ssl_c_s_dn(cn)]
    http-request set-header X-SSL-Issuer                %{+Q}[ssl_c_i_dn]
    http-request set-header X-SSL-Client-Not-Before     %{+Q}[ssl_c_notbefore]
    http-request set-header X-SSL-Client-Not-After      %{+Q}[ssl_c_notafter]
    reqadd X-Forwarded-Proto:\ https
    default_backend tomcat-mgmt

backend tomcat-mgmt
    mode http
    option tcp-smart-connect
    server tomcat :8009

backend tomcat-cp-events
    mode http
    option tcp-smart-connect
    server tomcat :23237

please let me know if any other info is needed.
Thanks,
Gidon


答:
if you are just setting values then place the doc assignment outside the for loop</p>

```<code>for d in new_data:

    for key, value in d.items():
        if key == 'Time ':
            Zeitvalue = value
            continue
        else:
            Device = key
            Value = value
    doc = {'Time ':Zeitvalue,'Device':Device, 'Measure':Value}
</code>```

Title: Missing one element of dictionary cause of If statement

Body:
if you are just setting values then place the doc assignment outside the for loop

for d in new_data:

    for key, value in d.items():
        if key == 'Time ':
            Zeitvalue = value
            continue
        else:
            Device = key
            Value = value
    doc = {'Time ':Zeitvalue,'Device':Device, 'Measure':Value}


问:
Docker-image-as-executable: should I execute in CMD or ENTRYPOINT?
I am creating a Docker image to initialize my PostgreSQL database. It looks like this:

```<code>FROM debian:stretc

RUN set -x \
     && ... ommitted ...
     && apt-get install postgresql-client -y

COPY scripts /scripts

CMD cd /scripts && psql -f myscript.sql
</code>```

This works great. Every time I need to initialize my database I start the container (docker run --rm my-image). After the psql command is done, the container is automatically stopped and removed (because of the --rm). So basically, I have a Docker-image-as-executable.

But, I am confused whether that last line should be:

```<code>CMD cd /scripts && psql -f myscript.sql
</code>```

or

```<code>ENTRYPOINT cd /scripts && psql -f myscript.sql
</code>```

Which one should be used in my case (Docker-image-as-excutable)? Why?

答:
You need to use ENTRYPOINT if you need to make it as "Docker-image-as-executable"

RUN executes the command(s) that you give in a new layer and creates
a new image. This is mainly used for installing a new package.

CMD sets default command and/or parameters, however, we can overwrite
those commands or pass in and bypass the default parameters    from
the command line when docker runs

ENTRYPOINT is used when yo want to run a container as an executable.

Body:
I am creating a Docker image to initialize my PostgreSQL database. It looks like this:

FROM debian:stretc

RUN set -x \
     && ... ommitted ...
     && apt-get install postgresql-client -y

COPY scripts /scripts

CMD cd /scripts && psql -f myscript.sql

This works great. Every time I need to initialize my database I start the container (docker run --rm my-image). After the psql command is done, the container is automatically stopped and removed (because of the --rm). So basically, I have a Docker-image-as-executable.

But, I am confused whether that last line should be:

CMD cd /scripts && psql -f myscript.sql

or

ENTRYPOINT cd /scripts && psql -f myscript.sql

Which one should be used in my case (Docker-image-as-excutable)? Why?


问:
Creating debug builds of Ocaml code with Jbuilder
I have been reading the tutorials for the Ocaml language and for Jbuilder. The official tutorial indicates that one must compile Ocaml code using the '-g' flag with ocamlc in order to then run ocamldebug.

I cannot find any mention of debug builds on the Jbuilder documentation. The only section that seems close is https://jbuilder.readthedocs.io/en/latest/jbuild.html#ocaml-flags. However, even if I add '-g' as a compilation flag..

```<code>(executable
 ((name [REDACTED])
  (public_name [REDACTED])
  (libraries ([REDACTED]))
  (flags (:standard -w -9+27-30-32-40@8
                    -safe-string
                    -linkall
                    -g))
  (modules ([REDACTED]))))
</code>```

..I still don't seem to get a debug binary:

```<code>$ ocamldebug [REDACTED]
    OCaml Debugger version 4.04.2

(ocd) r
Loading program... [REDACTED] is not a bytecode file.
</code>```

Am I doing something wrong? If not, what is the recommended way to produce debug builds from jbuilder?

答:
ocamldebug only works with bytecode builds. You're producing native code. To create a bytecode build, you can invoke jbuilder using prog.bc instead of prog.exe.

Note that this might not be what you're after: you can also debug native programs using plain old gdb, but you'll need to be a bit familiar with the runtime.

Body:
I have been reading the tutorials for the Ocaml language and for Jbuilder. The official tutorial indicates that one must compile Ocaml code using the '-g' flag with ocamlc in order to then run ocamldebug.

I cannot find any mention of debug builds on the Jbuilder documentation. The only section that seems close is https://jbuilder.readthedocs.io/en/latest/jbuild.html#ocaml-flags. However, even if I add '-g' as a compilation flag..

(executable
 ((name [REDACTED])
  (public_name [REDACTED])
  (libraries ([REDACTED]))
  (flags (:standard -w -9+27-30-32-40@8
                    -safe-string
                    -linkall
                    -g))
  (modules ([REDACTED]))))

..I still don't seem to get a debug binary:

$ ocamldebug [REDACTED]
    OCaml Debugger version 4.04.2

(ocd) r
Loading program... [REDACTED] is not a bytecode file.

Am I doing something wrong? If not, what is the recommended way to produce debug builds from jbuilder?


问:
Select the specific column of ListView and print it in a new messagebox in C#.net
I've just started to use ListView in C#.net.

I got to know how to add items and subitems. Going through the listview I wanted to fetch all the data from a whole column with multiple rows.

I want to know how to do this.

I found this code to list a specific selected data from a row:

ListView.SelectedIndexCollection sel = listView1.SelectedIndices;

```<code>        if (sel.Count == 1)
        {
            ListViewItem selItem = listView1.Items[sel[0]];
            MessageBox.Show(selItem.SubItems[2].Text);
        }
</code>```

That was helpful but i want to list all the items in a row, may be i want to add all the column items in array?

答:
```foreach (ListViewItem item in listView1.Items) {
    // Do something with item
}```

Body:
I've just started to use ListView in C#.net.

I got to know how to add items and subitems. Going through the listview I wanted to fetch all the data from a whole column with multiple rows.

I want to know how to do this.

I found this code to list a specific selected data from a row:

ListView.SelectedIndexCollection sel = listView1.SelectedIndices;

        if (sel.Count == 1)
        {
            ListViewItem selItem = listView1.Items[sel[0]];
            MessageBox.Show(selItem.SubItems[2].Text);
        }

That was helpful but i want to list all the items in a row, may be i want to add all the column items in array?


问:
SonarQube build errors in TFS 2017
Currently having the following errors on the "Complete the SonarQube analysis" step of our TFS 2017 build:

2017-12-05T22:04:24.5437340Z ##[error]System.Management.Automation.CommandNotFoundException: The term 'Get-TaskVariable' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

2017-12-05T22:04:24.5837397Z ##[error]System.Management.Automation.RuntimeException: The MSBuild.SonarQube.Runner executable could not be found. Check that the build definition includes a SonarQube Pre-Build step ---> System.Management.Automation.RuntimeException: The MSBuild.SonarQube.Runner executable could not be found. Check that the build definition includes a SonarQube Pre-Build step

SonarQube version: Version 6.7 (build 33306)
SonarQube Scanner for MSBuild version: 3.0.2

The "Prepare the SonarQube Analysis" step completes prior to the Visual Studio build step with no errors.

答:
According to the error seems SonarQube.Runner  didn't captured by TFS build agent.

Double confirm the configuration in SonarQube Scanner for MSBuild - Begin Analysis  task which used  to prepare the analysis before executing the build. Such as SonarQube Endpoint.

Besides, on the build agent:

Make sure the .NET Framework v4.5.2+ is installed

Make sure the Java Runtime Environment 8 is installed

Source Link: Analyzing with SonarQube Extension for VSTS/TFS

Try to create a new build definition with a simple test project to see if got the same error.

Title: SonarQube build errors in TFS 2017


问:
How to download android support library 25.1.0 via curl?
I need to download android support library 25.1.0 and google repo 10.0.1 via curl (behind GFW) but I cannot find the link via recent Android SDK xml. How can I find archived packages?</p>

答:
Addons: https://dl.google.com/android/repository/addon.xml

Ctrl+F "librar". Find the url for the m2repository: android_m2repository_r47.zip.

Then use curl to download the file:

https://dl.google.com/android/repository/android_m2repository_r47.zip.


问:
Entity Framework if statement inside select
I have a problem in generating an Entity Framework query and not okay with linq style one :.....

This is my attempt:

```<code>var query = db.table
              .Where(x => x.colA == 1)
              .GroupBy(x => new {x.min,x.max})
              .Select(y => if(y.key.min==0 && y.key.max==0)
                              { " unchanged " }
                           else
                              { y.key.min.tostring()+" "+y.key.max.tostring() })
              .ToList()
</code>```

I want to get "unchanged" string, if both value ofmin and max are zero, otherwise concat them

答:
Use the conditional operator</p>

```<code>// ...

.Select(y=> y.key.min==0 && y.key.max==0
             ? " unchanged "
             : y.key.min.tostring()+" "+y.key.max.tostring())
// ...
</code>```

Body:
I have a problem in generating an Entity Framework query and not okay with linq style one :.....

This is my attempt:

var query = db.table
              .Where(x => x.colA == 1)
              .GroupBy(x => new {x.min,x.max})
              .Select(y => if(y.key.min==0 && y.key.max==0)
                              { " unchanged " }
                           else
                              { y.key.min.tostring()+" "+y.key.max.tostring() })
              .ToList()

I want to get "unchanged" string, if both value ofmin and max are zero, otherwise concat them

Body:
Use the conditional operator

// ...

.Select(y=> y.key.min==0 && y.key.max==0
             ? " unchanged "
             : y.key.min.tostring()+" "+y.key.max.tostring())
// ...


问:
After laravel installation localhost doesn't work
so i am having to do a project on laravel and I installed it all right and it works fine (can be accessed via localhost:8000) however I cannot access localhost. I am trying to run a laravel installation and wordpress concurrently. also Wordpress and localhost worked fine before I installed laravel.

My Laravel installation is in html/laravel and Wordpress in html/wordpress.

I have been trying out a lot of things I came across online to no avail.
The .htaccess file in my /html is empty. Some of the links suggested that I have to write new .conf files for each installation and yet others suggested me to change .htaccess. nothing helped.
I am at a loss. Any help much appreciated. Thanks

I am on a ubuntu16.4 machine.

答:
So from the chat we had in the comments we came to the following conclusions:

You're using a linux(ubuntu) server.

You're using lamp, more information about lamp can be found here

You're trying to run lamp (localhost) and laravel (localhost:8000) together.

With this information i think the issue is within the laravel and localhost application combined. There are a couple of things we should keep in mind

To run laravel on a localhost:8000 environment be sure to run the following command php artisan serve.

The configuration as told in older answers should be set right in laravel

Give 775 permission to storage & bootstrap folder inside laravel folder and access url through html/laravel/public. *credits to: @vijay_Kashyap

Check the .conf file of apache and make sure all items are set right.

Look for the file: 000-default.conf -> tutorial

Even if all these things are set correctly the mistake could still appear due to wrong url-rewriting or the server that clashes with the laravel installation.

If you're sure that the above settings are set correctly you should take a look at the configuration of your lamp installation and the setup steps of laravel. Think about some of the following things:

Are the right packages installed

Is everything up to date -> command: sudo apt-get upgrade, sudo apt-get update (use -dist in case you're not completely sure).

Is Apache's mod rewrite enabled? -> sudo a2enmod rewrite

Did you install composer -> curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer

check my_app.conf (if exists in your case).

If none of these things work for you it maybe would be an idea to restart from the beginning. Maybe you've made some changes to files you didn't need to change but forgot about them due to frustration etc. (happend to me the first time i installed multiple application types).

I would also like to refer you to laracasts and this tutorial about lamp

Since i'm not able to review the server for myself i can't give you much more information at the moment. Do ask questions if anything is unclear or new errors occur.

Hope this helps!


问:
How can I make this PowerShell script more efficient?
I am trying to make a script that takes an XML file, looks for a matching condition, if it finds it adds a new line of asteriks, then when done going through the file to strip it of all its XML tags and leave the data in a plain text file.

The script has been tested on a small input xml file and works fine, but when I pass a large XML file to it takes forever (not actually sure how long as I ran it for over an hour and still no result so I just stopped it).

I'm guessing I must be performing the work in an extremely inefficient manner, hoping you guys can help me make it fast and efficient.

Here is the script below:

```<code># Takes input XML File, cleans up XML elements, outputs plain text file

$FileName = "C:\Users\someguy\Desktop\input.xml"
$Pattern = "ProcessSpecifier = ""true"""
$FileOriginal = Get-Content $FileName

[String[]] $FileModified = @()
Foreach ($Line in $FileOriginal)
{
    $FileModified += $Line
    if ($Line -match $Pattern)
    {
        #Add Lines after the selected pattern
        $FileModified += "*************isActive=true*****************"
    }
}

$FileModified -replace "<[^>]+>", "" | Out-File C:\Users\someguy\Desktop\Output.txt
</code>```

答:
Variation of TheMadTechnician's answer:

```<code># Takes input XML File, cleans up XML elements, outputs plain text file

$FileName = "C:\Users\someguy\Desktop\input.xml"
$Pattern = '(?<=^.*ProcessSpecifier = "true".*$)'
Set-Content -Path C:\Users\someguy\Desktop\Output.txt -Value (((Get-Content $FileName) -replace $Pattern, "`n*************isActive=true*****************" -replace '<[^>]+?>' -replace '^\s*|\s$').Where{$_})
</code>```

I actually try to avoid the pipeline, it is rather slow afaik. Of course you will run into problem with memory consumption if the files are very large.
The "().Where" construct doesn't work on all powershell versions (Version 4+ iirc).

This is a guess, I am not sure whether this is actually faster than TheMadTechnician's. I'd be curious about the result :)

Body:
I am trying to make a script that takes an XML file, looks for a matching condition, if it finds it adds a new line of asteriks, then when done going through the file to strip it of all its XML tags and leave the data in a plain text file.

The script has been tested on a small input xml file and works fine, but when I pass a large XML file to it takes forever (not actually sure how long as I ran it for over an hour and still no result so I just stopped it).

I'm guessing I must be performing the work in an extremely inefficient manner, hoping you guys can help me make it fast and efficient.

Here is the script below:

# Takes input XML File, cleans up XML elements, outputs plain text file

$FileName = "C:\Users\someguy\Desktop\input.xml"
$Pattern = "ProcessSpecifier = ""true"""
$FileOriginal = Get-Content $FileName

[String[]] $FileModified = @()
Foreach ($Line in $FileOriginal)
{
    $FileModified += $Line
    if ($Line -match $Pattern)
    {
        #Add Lines after the selected pattern
        $FileModified += "*************isActive=true*****************"
    }
}

$FileModified -replace "<[^>]+>", "" | Out-File C:\Users\someguy\Desktop\Output.txt

Body:
Variation of TheMadTechnician's answer:

# Takes input XML File, cleans up XML elements, outputs plain text file

$FileName = "C:\Users\someguy\Desktop\input.xml"
$Pattern = '(?<=^.*ProcessSpecifier = "true".*$)'
Set-Content -Path C:\Users\someguy\Desktop\Output.txt -Value (((Get-Content $FileName) -replace $Pattern, "`n*************isActive=true*****************" -replace '<[^>]+?>' -replace '^\s*|\s$').Where{$_})

I actually try to avoid the pipeline, it is rather slow afaik. Of course you will run into problem with memory consumption if the files are very large.
The "().Where" construct doesn't work on all powershell versions (Version 4+ iirc).

This is a guess, I am not sure whether this is actually faster than TheMadTechnician's. I'd be curious about the result :)


问:
Why does CSS padding increase size of element?
I am trying to give my div and textarea some padding. When I do this, it increases the size of the element, instead of shrinking the content area inside of it. Is there any way to achieve what I am trying to do?</p>

答:
According to CSS2 specs, the rendered width of a box type element is equal to the sum of its width, left/right border and left/right padding (left/right margin comes into play as well). If your box has a width of '100%' and also has margin, border and padding, they will affect (increase) the width occupied by the object.

So, if your textarea needs to be 100% wide, assign values to width, margin-left/right, border-left/right and padding-left/right in such a way that their sum equals 100%.

In CSS3 we have three box-sizing models. You can use border-box model:

The specified width and height (and respective min/max properties) on
  this element determine the border box of the element. That is, any
  padding or border specified on the element is laid out and drawn
  inside this specified width and height. The content width and height
  are calculated by subtracting the border and padding widths of the
  respective sides from the specified ‘width’ and ‘height’ properties.

ContentLicense: CC BY-SA 4.0


问:
MatPaginator gets undefined
I have replicated thsi case:  Angular 5 Material Table not getting data from service

But when I try access any property from paginator I get undefined error from this objet.

Any ideas?

Thanks

答: I got the same issue. Placing  mat-paginator tag outside *ngIf resolved my issue. Make sure it is available to component class without any conditions.</p>

Title: MatPaginator gets undefined


答:
Sorry I can't try it right now, but i think this should work</p>

```<code>var query = db.table
   .Where(x=> x.colA == 1)
   .GroupBy(x=> new {x.min,x.max})
   .Select(y=>  {if(y.key.min==0 && y.key.max==0)
                {
                    " unchanged "
                } else
                {
                    y.key.min.tostring()+" "+y.key.max.tostring();
                } return y;})
    .ToList()
</code>```

Title: Entity Framework if statement inside select

Body:
Sorry I can't try it right now, but i think this should work

var query = db.table
   .Where(x=> x.colA == 1)
   .GroupBy(x=> new {x.min,x.max})
   .Select(y=>  {if(y.key.min==0 && y.key.max==0)
                {
                    " unchanged "
                } else
                {
                    y.key.min.tostring()+" "+y.key.max.tostring();
                } return y;})
    .ToList()


问:
numpy boolean indexing selecting and setting
I'm not very familiar with python. I reading the book 'Python for Data Analysis' recently, and I'm a bit confused about the numpy boolean indexing and setting.
The book said:

Selecting data from an array by boolean indexing always creates a copy of the data, even if the returned array is unchanged.

Setting values with boolean arrays works in a common-sense way.

And I have tried it as the follow code:

First:

```<code>data = np.random.randn(7, 4)
data[data < 0] = 0 # this could change the `data`
</code>```

Second:

```<code>data = np.random.randn(7, 4)
copied = data[data < 0]
copied[1] = 1  # this couldn't change the `data`
</code>```

I do not quite understand here, anyone can explain it. In my understanding, copied should be pointer to the data[data < 0] slices.

答:
Based on the sequence of the code:

data = np.random.randn(7, 4) : Thi step creates an array of size 7 by 4

data[data < 0] = 0 :  makes all the elements in data which are < 0 as 0

copied = data[data < 0] :  This step generates an empty array as there is no element in data which is < 0, because of step 4

copied[1] = 1 : This step raises an error as copied is an empty array and thus index 1 does not exist

Body:
I'm not very familiar with python. I reading the book 'Python for Data Analysis' recently, and I'm a bit confused about the numpy boolean indexing and setting.
The book said:

Selecting data from an array by boolean indexing always creates a copy of the data, even if the returned array is unchanged.

Setting values with boolean arrays works in a common-sense way.

And I have tried it as the follow code:

First:

data = np.random.randn(7, 4)
data[data < 0] = 0 # this could change the `data`

Second:

data = np.random.randn(7, 4)
copied = data[data < 0]
copied[1] = 1  # this couldn't change the `data`

I do not quite understand here, anyone can explain it. In my understanding, copied should be pointer to the data[data < 0] slices.


问:
Iterate through two dimensional array while changing each element
I want to fill a two dimensional array with certain values. I want to get:

```<code>[
  ['Num00', 'Num01', 'Num02'],
  ['Num10', 'Num11', 'Num12'],
  ['Num20', 'Num21', 'Num22']
]
</code>```

How can I do it?

This is my code:

```<code>game_field = Array.new(3, Array.new(3))
3.times do |i|
  3.times do |j|
    game_field[i][j] = 'Num' + i.to_s + j.to_s
  end
end
game_field
</code>```

答:
you can also try </p>

```<code>game_field = (0..2).map do |i|
  (0..2).map do |j|
    "Num#{i}#{j}"
  end
end
</code>```

<p>One liner </p>

```<code>game_field = (0..2).map {|i| (0..2).map {|j|  "Num#{i}#{j}"} }
</code>```

Body:
I want to fill a two dimensional array with certain values. I want to get:

[
  ['Num00', 'Num01', 'Num02'],
  ['Num10', 'Num11', 'Num12'],
  ['Num20', 'Num21', 'Num22']
]

How can I do it?

This is my code:

game_field = Array.new(3, Array.new(3))
3.times do |i|
  3.times do |j|
    game_field[i][j] = 'Num' + i.to_s + j.to_s
  end
end
game_field

Body:
you can also try

game_field = (0..2).map do |i|
  (0..2).map do |j|
    "Num#{i}#{j}"
  end
end

One liner

game_field = (0..2).map {|i| (0..2).map {|j|  "Num#{i}#{j}"} }


问:
How to parse unix timestamp to time.Time
I'm trying to parse an Unix timestamp but I get out of range error. That doesn't really makes sense to me, because the layout is correct (as in the Go docs):

```<code>package main

import "fmt"
import "time"

func main() {
    tm, err := time.Parse("1136239445", "1405544146")
    if err != nil{
        panic(err)
    }

    fmt.Println(tm)
}
</code>```

Playground

答:
You can directly use time.Unix function of time which converts the unix time stamp to UTC

```<code>package main

import (
  "fmt"
  "time"
)

func main() {
    unixTimeUTC:=time.Unix(1405544146, 0) //gives unix time stamp in utc

    unitTimeInRFC3339 :=unixTimeUTC.Format(time.RFC3339) // converts utc time to RFC3339 format

    fmt.Println("unix time stamp in UTC :--->",unixTimeUTC)
    fmt.Println("unix time stamp in unitTimeInRFC3339 format :->",unitTimeInRFC3339)
}
</code>```

Output

```<code>unix time stamp in UTC :---> 2014-07-16 20:55:46 +0000 UTC
unix time stamp in unitTimeInRFC3339 format :----> 2014-07-16T20:55:46Z
</code>```

Check in Go Playground: https://play.golang.org/p/5FtRdnkxAd

Body:
I'm trying to parse an Unix timestamp but I get out of range error. That doesn't really makes sense to me, because the layout is correct (as in the Go docs):

package main

import "fmt"
import "time"

func main() {
    tm, err := time.Parse("1136239445", "1405544146")
    if err != nil{
        panic(err)
    }

    fmt.Println(tm)
}

Playground

Body:
You can directly use time.Unix function of time which converts the unix time stamp to UTC

package main

import (
  "fmt"
  "time"
)

func main() {
    unixTimeUTC:=time.Unix(1405544146, 0) //gives unix time stamp in utc

    unitTimeInRFC3339 :=unixTimeUTC.Format(time.RFC3339) // converts utc time to RFC3339 format

    fmt.Println("unix time stamp in UTC :--->",unixTimeUTC)
    fmt.Println("unix time stamp in unitTimeInRFC3339 format :->",unitTimeInRFC3339)
}

Output

unix time stamp in UTC :---> 2014-07-16 20:55:46 +0000 UTC
unix time stamp in unitTimeInRFC3339 format :----> 2014-07-16T20:55:46Z

Check in Go Playground: https://play.golang.org/p/5FtRdnkxAd


问:
How to merge a branch into master without changes?
I want to merge integration branch into master, but I don't want to change anything only to look good.

Integration branch is that with gray. This branch contains a lot of changes, and I want to make a trick. To reset it, when was splitted from master, because I can saw last changes and put them with one commit on master. So master will contain last version of files from integration branch, but integration will remain splitted from master.

I want to merge integration into master, only visual (without changes), to look good on history, because I already have changes with that single commit.

The final question is: How to merge integration in master without to put changes on master, only to affect history (visually)?

I want to do that BECAUSE:

after I split integration from master project structure was modified and now I have to much conflicts. It's more easier to make merge manually. After that I only want to "merge" integration on master without to put changes (because already are there).

答:
The steps you need to do in order to achieve this are:

checkout integration branch

do a rebase with master (git pull --rebase master)

push integration branch

checkout master

merge integration branch

push master branch.

But this will work only if integration is not a public branch. If it is, then you will rewrite its history and is not a good thing. If its public, then the only thing you can do is merge it with master, but you won't have a linear history.


问:
Visual Studio Team Services Build yml npm test not recognized
I'm trying to run an npm install and test on Visual Studio Team Services Build (configuring the build using YAML). I have the following definition.

** updated **

```<code>
queue:
  name: Hosted VS2017
  demands: npm</p>

<p>steps:
- task: NodeTool@0
  inputs:
    versionSpec: "8.x"</p>

<ul>
<li><p>task: Npm@1
inputs:
command: "custom"
verbose: "false"
customCommand: "install @angular/cli -g"</p></li>
<li><p>task: Npm@1
inputs:
verbose: "false"</p></li>
<li><p>task: CmdLine@1
inputs:
filename: "ng"
arguments: "test --watch=false --single-run=true --reporters=junit,progress"</p></li>
<li><p>task: PublishTestResults@2
inputs:
testResultsFiles: "**\test.xml"
testRunTitle: "Jasmine Tests"</p></li>
</ul>

<p>```

The install runs fine, but I get an error on the test step:

 85% chunk id optimization               86% hashing 87% module assets processing  88% chunk assets processing 89% additional chunk assets processing                          90% recording 91% additional asset processing    92% chunk asset optimization       94% asset optimization           95% emitting

2017-12-06T06:21:34.7643927Z ##[error]Process completed with exit code 1.
2017-12-06T06:21:34.7682485Z ##[section]Finishing: Run  Tests

I'm using puppeteer to workaround lack of chrome to run the tests.

答:
Finally got it working, but not 100% satisfied with the solutiuon, posting here the progress and open points plus detailed info to reproduce it, hope it can help other and that we can refine it.

Scenario: I'm in the need of configuring CI on an Angular 4 project and running it under Visual Studio Team Service CI hosted environment, and I want to use the yaml based config.

Issues that I have found:

Hosted enviroment come with old node version (1).

Chrome is not installed by default on the hosted environment, phantom browser is not anymore a solution since it's an abandoned project.

You need to install angular-cli globally.

The current working solution I got, steps:

On your project:

Open your command prompt, install puppeteer, karma-junit-reporter

```<code>npm install puppeteer karma-junit-reporter --save-dev
</code>```

Configure your karma.conf.js

At the top of your file add the following line of code

```<code>process.env.CHROME_BIN = require('puppeteer').executablePath();
</code>```

Then on the pluging sections (add karma-junit-reporter)

```<code>    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-junit-reporter'), // add karma-unit reporter
      require('karma-coverage-istanbul-reporter'),
      require('@angular/cli/plugins/karma')
    ],
```

On the reporters section set junit reporter as a valid one,and configure it:

```<code>    reporters: config.angularCli && config.angularCli.codeCoverage
              ? ['progress', 'coverage-istanbul', 'junit']
              : ['progress', 'kjhtml', 'junit'],
    junitReporter: {
      outputDir: '',
      outputFile: 'test.xml',
    },
```

Now it's time to add on the root of your project a file named .vsts-ci.yml (just pasted the raw content in this link: https://pastebin.com/0XpmpPrp)

```<code>
queue:
  name: Hosted VS2017
  demands: npm</p>

<p>steps:
- task: NodeTool@0
  displayName: "Updating node to version 8.x"
  inputs:
    versionSpec: "8.x"</p>

<ul>
<li><p>task: Npm@1
displayName: "installing angular-cli"
inputs:
command: "custom"
verbose: "false"
customCommand: "install @angular/cli@1.0.2 -g"</p></li>
<li><p>task: Npm@1
inputs:
verbose: "false"</p></li>
<li><p>task: CmdLine@1
displayName: "run tests: ng test"
inputs:
filename: "ng"
arguments: "test --watch=false --single-run=true --reporters=junit,progress"</p></li>
<li><p>task: PublishTestResults@2
displayName: "Publish Test Results (test.xml)"
inputs:
testResultsFiles: "**\test.xml"
testRunTitle: "Jasmine Tests"
```

What it does:

Update node version.

Globally install angular-cli (I stick to the version that is being used in the package).

Execute a noop command (I don't know why it's needed, but if I don't add this it breaks).

Execute ng test (single run and using junit as reporter).

Publish test results.

Tips and interesting posts I have found:

Use the UI build tool to create the build, then there is an option to convert it to yaml.

Node tool updated task: https://learn.microsoft.com/en-us/vsts/build-release/tasks/tool/node-js

Puppeteer and VSTS: http://benjaminspencer.me/post/14/headless-chrome-vsts

Angular 4 and VSTS (I): https://csharperimage.jeremylikness.com/2016/12/integrating-angular-2-unit-tests-with.html

Angular 4 and VSTS (II): https://blogs.msdn.microsoft.com/premier_developer/2017/05/17/integrating-angular-4-unit-tests-with-visual-studio-team-services-vsts/

Room for improvement:

Avoid having to install angular-cli globally, tried to add a custom script to my package-json, but when I call something like "npm run test:ci" it's not recognized by the visual studio build runner.

I would like to get rid of puppeteer, is karma-jsdom-launcher an option?

Body:
I'm trying to run an npm install and test on Visual Studio Team Services Build (configuring the build using YAML). I have the following definition.

** updated **

queue:
  name: Hosted VS2017
  demands: npm

steps:
- task: NodeTool@0
  inputs:
    versionSpec: "8.x"

task: Npm@1
inputs:
command: "custom"
verbose: "false"
customCommand: "install @angular/cli -g"

task: Npm@1
inputs:
verbose: "false"

task: CmdLine@1
inputs:
filename: "ng"
arguments: "test --watch=false --single-run=true --reporters=junit,progress"

task: PublishTestResults@2
inputs:
testResultsFiles: "**\test.xml"
testRunTitle: "Jasmine Tests"

The install runs fine, but I get an error on the test step:

 85% chunk id optimization               86% hashing 87% module assets processing  88% chunk assets processing 89% additional chunk assets processing                          90% recording 91% additional asset processing    92% chunk asset optimization       94% asset optimization           95% emitting

2017-12-06T06:21:34.7643927Z ##[error]Process completed with exit code 1.
2017-12-06T06:21:34.7682485Z ##[section]Finishing: Run  Tests

I'm using puppeteer to workaround lack of chrome to run the tests.

Body:
Finally got it working, but not 100% satisfied with the solutiuon, posting here the progress and open points plus detailed info to reproduce it, hope it can help other and that we can refine it.

Scenario: I'm in the need of configuring CI on an Angular 4 project and running it under Visual Studio Team Service CI hosted environment, and I want to use the yaml based config.

Issues that I have found:

Hosted enviroment come with old node version (1).

Chrome is not installed by default on the hosted environment, phantom browser is not anymore a solution since it's an abandoned project.

You need to install angular-cli globally.

The current working solution I got, steps:

On your project:

Open your command prompt, install puppeteer, karma-junit-reporter

npm install puppeteer karma-junit-reporter --save-dev

Configure your karma.conf.js

At the top of your file add the following line of code

process.env.CHROME_BIN = require('puppeteer').executablePath();

Then on the pluging sections (add karma-junit-reporter)

    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-junit-reporter'), // add karma-unit reporter
      require('karma-coverage-istanbul-reporter'),
      require('@angular/cli/plugins/karma')
    ],

On the reporters section set junit reporter as a valid one,and configure it:

    reporters: config.angularCli && config.angularCli.codeCoverage
              ? ['progress', 'coverage-istanbul', 'junit']
              : ['progress', 'kjhtml', 'junit'],
    junitReporter: {
      outputDir: '',
      outputFile: 'test.xml',
    },

Now it's time to add on the root of your project a file named .vsts-ci.yml (just pasted the raw content in this link: https://pastebin.com/0XpmpPrp)

queue:
  name: Hosted VS2017
  demands: npm

steps:
- task: NodeTool@0
  displayName: "Updating node to version 8.x"
  inputs:
    versionSpec: "8.x"

task: Npm@1
displayName: "installing angular-cli"
inputs:
command: "custom"
verbose: "false"
customCommand: "install @angular/cli@1.0.2 -g"

task: Npm@1
inputs:
verbose: "false"

task: CmdLine@1
displayName: "run tests: ng test"
inputs:
filename: "ng"
arguments: "test --watch=false --single-run=true --reporters=junit,progress"

task: PublishTestResults@2
displayName: "Publish Test Results (test.xml)"
inputs:
testResultsFiles: "**\test.xml"
testRunTitle: "Jasmine Tests"

What it does:

Update node version.

Globally install angular-cli (I stick to the version that is being used in the package).

Execute a noop command (I don't know why it's needed, but if I don't add this it breaks).

Execute ng test (single run and using junit as reporter).

Publish test results.

Tips and interesting posts I have found:

Use the UI build tool to create the build, then there is an option to convert it to yaml.

Node tool updated task: https://learn.microsoft.com/en-us/vsts/build-release/tasks/tool/node-js

Puppeteer and VSTS: http://benjaminspencer.me/post/14/headless-chrome-vsts

Angular 4 and VSTS (I): https://csharperimage.jeremylikness.com/2016/12/integrating-angular-2-unit-tests-with.html

Angular 4 and VSTS (II): https://blogs.msdn.microsoft.com/premier_developer/2017/05/17/integrating-angular-4-unit-tests-with-visual-studio-team-services-vsts/

Room for improvement:

Avoid having to install angular-cli globally, tried to add a custom script to my package-json, but when I call something like "npm run test:ci" it's not recognized by the visual studio build runner.

I would like to get rid of puppeteer, is karma-jsdom-launcher an option?


问:
Unable to run react-native app on android device - installDebug error
I am trying to run my react-native app on my android device via cable with USB debugging enabled in developer mode. The android version is 5.1 (Lolipop). I keep on getting this error, please suggest how

```<code>Unable to install E:\react-native\AwesomeProject\android\app\build\outputs\apk\app-debug.apk
com.android.ddmlib.InstallException: Failed to install all
        at com.android.ddmlib.SplitApkInstaller.install(SplitApkInstaller.java:89)
        at com.android.ddmlib.Device.installPackages(Device.java:904)
        at com.android.builder.testing.ConnectedDevice.installPackages(ConnectedDevice.java:137)
        at com.android.build.gradle.internal.tasks.InstallVariantTask.install(InstallVariantTask.java:134)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:75)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.doExecute    (AnnotationProcessingTaskFactory.java:228)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute    (AnnotationProcessingTaskFactory.java:221)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute    (AnnotationProcessingTaskFactory.java:210)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:621)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:604)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
        at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:66)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:203)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:185)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:66)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:50)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:25)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:110)
        at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
        at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
        at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
        at org.gradle.initialization.DefaultGradleLauncher$4.run(DefaultGradleLauncher.java:153)
        at org.gradle.internal.Factories$1.create(Factories.java:22)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:53)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:150)
        at org.gradle.initialization.DefaultGradleLauncher.access$200(DefaultGradleLauncher.java:32)
        at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:98)
        at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:92)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:63)
        at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:92)
        at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:83)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:99)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:48)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:30)
        at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:81)
        at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:46)
        at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:51)
        at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:28)
        at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:43)
        at org.gradle.internal.Actions$RunnableActionAdapter.execute(Actions.java:173)
        at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:239)
        at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:212)
        at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:35)
        at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:24)
        at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33)
        at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22)
        at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:205)
        at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:169)
        at org.gradle.launcher.Main.doAction(Main.java:33)
        at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:55)
        at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:36)
        at org.gradle.launcher.GradleMain.main(GradleMain.java:23)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.gradle.wrapper.BootstrapMainStarter.start(BootstrapMainStarter.java:30)
        at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:127)
        at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
12:43:11 E/1258563779: Error while uploading app-debug.apk : Unknown failure ([CDS]close[0])
                                                                                :app:installDebug FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:installDebug'.
> com.android.builder.testing.api.DeviceException: com.android.ddmlib.InstallException: Failed to install all

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 1 mins 43.72 secs
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/android-setup.html
</code>```

I don't want to use the android emulator, instead, i want to test the app on my physical device.

I have already installed required stuff as per the react-native getting started documentation. Still, I keep on getting the same error.

Thanks in advance

答:
I have suffered from this prolem before, it cause by MIUI Optimization of my device. Since you are not running on Mi device so you may have 2 ways to solve this.

Work around solution: com.android.tools.build:gradle to 2.3.0 and gradle plugins to version 3.3.

Restart adb:

You had to type:

adb kill-server

adb connect 192.168.0.14:5555

Wait a moment then run:

adb devices

This will show you the DEVICE_ID of your device running android. It is usually its IP address followed by the port 5555 (usually, not always).

react-native run-android --deviceId DEVICE_ID

The important part was the --deviceId DEVICE_ID. Without this, the apk would never get uploaded to the phone.

Then, IF the app launched with a red screen... You had to shake it, go to "dev settings", adjust the "debug server host & port for device", putting your computer's IP address and port, like this:

192.168.0.15:8081

Many people have same issues: See this and this

Body:
I am trying to run my react-native app on my android device via cable with USB debugging enabled in developer mode. The android version is 5.1 (Lolipop). I keep on getting this error, please suggest how

Unable to install E:\react-native\AwesomeProject\android\app\build\outputs\apk\app-debug.apk
com.android.ddmlib.InstallException: Failed to install all
        at com.android.ddmlib.SplitApkInstaller.install(SplitApkInstaller.java:89)
        at com.android.ddmlib.Device.installPackages(Device.java:904)
        at com.android.builder.testing.ConnectedDevice.installPackages(ConnectedDevice.java:137)
        at com.android.build.gradle.internal.tasks.InstallVariantTask.install(InstallVariantTask.java:134)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:75)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.doExecute    (AnnotationProcessingTaskFactory.java:228)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute    (AnnotationProcessingTaskFactory.java:221)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute    (AnnotationProcessingTaskFactory.java:210)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:621)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:604)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
        at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:66)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:203)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:185)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:66)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:50)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:25)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:110)
        at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
        at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
        at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
        at org.gradle.initialization.DefaultGradleLauncher$4.run(DefaultGradleLauncher.java:153)
        at org.gradle.internal.Factories$1.create(Factories.java:22)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:53)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:150)
        at org.gradle.initialization.DefaultGradleLauncher.access$200(DefaultGradleLauncher.java:32)
        at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:98)
        at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:92)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:63)
        at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:92)
        at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:83)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:99)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:48)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:30)
        at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:81)
        at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:46)
        at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:51)
        at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:28)
        at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:43)
        at org.gradle.internal.Actions$RunnableActionAdapter.execute(Actions.java:173)
        at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:239)
        at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:212)
        at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:35)
        at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:24)
        at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33)
        at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22)
        at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:205)
        at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:169)
        at org.gradle.launcher.Main.doAction(Main.java:33)
        at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:55)
        at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:36)
        at org.gradle.launcher.GradleMain.main(GradleMain.java:23)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.gradle.wrapper.BootstrapMainStarter.start(BootstrapMainStarter.java:30)
        at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:127)
        at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
12:43:11 E/1258563779: Error while uploading app-debug.apk : Unknown failure ([CDS]close[0])
                                                                                :app:installDebug FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:installDebug'.
> com.android.builder.testing.api.DeviceException: com.android.ddmlib.InstallException: Failed to install all

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 1 mins 43.72 secs
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/android-setup.html

I don't want to use the android emulator, instead, i want to test the app on my physical device.

I have already installed required stuff as per the react-native getting started documentation. Still, I keep on getting the same error.

Thanks in advance


问:
GridView does not change on page change
Gridview: Data does not change on page change.

Hi, im working on a asp.net website with c#.
I have a gridview with paging, the gridview is populated from an sql database, and on the PageIndexChanging I have:

```<code>protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    BindGridControl();

    gridView.PageIndex = e.NewPageIndex;
    gridView.DataBind();
}
</code>```

If I click on page 2 for example, the next rows of data display fine.
But if I click back to the page 1, the data does not change, it keep displaying the data from the page 2.

How can I solve this?

答:
I had this problem too for a long time.
I came up with this and it finally works for me.

```<code>protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    BindGridControl(e.NewPageIndex);
}
</code>```

And then in your BindGridControl function:

```<code>protected void BindGridControl(int pageNumber = 0)
{
    SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings[connection].ConnectionString);
    SqlDataReader dr;
    SqlCommand cmd;
    cmd = new SqlCommand();
    cmd.Connection = sqlConn;
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "sp_load";
    sqlConn.Open();
    dr = cmd.ExecuteReader();
    DataTable dt = new DataTable();
    dt.Load(dr);
    GridView1.PageIndex = pageNumber;
    GridView1.DataSource = dt;
    GridView1.DataBind();
    sqlConn.Close();
}
</code>```

Title: GridView does not change on page change

Body:
Gridview: Data does not change on page change.

Hi, im working on a asp.net website with c#.
I have a gridview with paging, the gridview is populated from an sql database, and on the PageIndexChanging I have:

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    BindGridControl();

    gridView.PageIndex = e.NewPageIndex;
    gridView.DataBind();
}

If I click on page 2 for example, the next rows of data display fine.
But if I click back to the page 1, the data does not change, it keep displaying the data from the page 2.

How can I solve this?

Body:
I had this problem too for a long time.
I came up with this and it finally works for me.

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    BindGridControl(e.NewPageIndex);
}

And then in your BindGridControl function:

protected void BindGridControl(int pageNumber = 0)
{
    SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings[connection].ConnectionString);
    SqlDataReader dr;
    SqlCommand cmd;
    cmd = new SqlCommand();
    cmd.Connection = sqlConn;
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "sp_load";
    sqlConn.Open();
    dr = cmd.ExecuteReader();
    DataTable dt = new DataTable();
    dt.Load(dr);
    GridView1.PageIndex = pageNumber;
    GridView1.DataSource = dt;
    GridView1.DataBind();
    sqlConn.Close();
}


问:
Asp.net MVC Layout - Routing Issue With Areas
I've got an issue with MVC routing(or at least I think it's mvc routing :) )...

here's details of my work flow

In my project i have to create separate user wise login.this is fully customize login section.
so what i did was append my menu bar html in by calling a ajax function ,
$(document).ready(function ()) of that layout page.

Code:

```<code>$(document).ready(function () {
        $("#divProcessing").show();
        $.ajax({
            url: '@Url.Action("UICustomize", "Home")',
            data: {
            },
            type: 'POST',
            cache: false,
            success: function (data) {

                if (data != '')
                {
                    $('#sidemenulist').append(data);
                    $("#divProcessing").hide();
                }
                else {
                    location.href = "/Home/Login";
                }

            }
        });
 });
</code>```

"UICustomize", "Home"

Now UI changed dynamically user wise.so up-to this part there is no issue.

After that i have to use Area in asp.net mvc for particular modules wise.
then i'm getting issue.
In this area , i cannot use my layout ajax function because my path getting changed.

'/ClientManagement/Home/UICustomize'

i want to redirect that path to Home/UICustomize only.
how can that be done?

here's the route:
RouteConfig

```<code> public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
          name: "Default",
          url: "{controller}/{action}/{id}",
          defaults: new { controller = "Home", action = "Login", id = UrlParameter.Optional }
      );
</code>```

Area

```<code>public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "ClientManagement_default",
            "ClientManagement/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }

        );

    }
</code>```

答:
Url.Action() will default to using the current area which is why its generating a url with the name of your area. To remove it, use

```<code>$.ajax({
    url: '@Url.Action("UICustomize", "Home", new { area = "" })',
    ....
</code>```

which in your case will generate /Home/UICustomize instead of /ClientManagement/Home/UICustomize.

However you should not be rendering your side bar using ajax. Instead, decorate you UICustomize() method with a [ChildActionOnly] attribute (so it cannot be navigated to by the user), and in your layout, use

```<code>@Html.Action("UICustomize", "Home", new { area = "" })
</code>```

or

```<code>@{ Html.RenderAction("UICustomize", "Home", new { area = "" }); }
</code>```

to render the partial view of your sidebar menu.

Body:
I've got an issue with MVC routing(or at least I think it's mvc routing :) )...

here's details of my work flow

In my project i have to create separate user wise login.this is fully customize login section.
so what i did was append my menu bar html in by calling a ajax function ,
$(document).ready(function ()) of that layout page.

Code:

$(document).ready(function () {
        $("#divProcessing").show();
        $.ajax({
            url: '@Url.Action("UICustomize", "Home")',
            data: {
            },
            type: 'POST',
            cache: false,
            success: function (data) {

                if (data != '')
                {
                    $('#sidemenulist').append(data);
                    $("#divProcessing").hide();
                }
                else {
                    location.href = "/Home/Login";
                }

            }
        });
 });

"UICustomize", "Home"

Now UI changed dynamically user wise.so up-to this part there is no issue.

After that i have to use Area in asp.net mvc for particular modules wise.
then i'm getting issue.
In this area , i cannot use my layout ajax function because my path getting changed.

'/ClientManagement/Home/UICustomize'

i want to redirect that path to Home/UICustomize only.
how can that be done?

here's the route:
RouteConfig

 public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
          name: "Default",
          url: "{controller}/{action}/{id}",
          defaults: new { controller = "Home", action = "Login", id = UrlParameter.Optional }
      );

Area

public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "ClientManagement_default",
            "ClientManagement/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }

        );

    }

Body:
Url.Action() will default to using the current area which is why its generating a url with the name of your area. To remove it, use

$.ajax({
    url: '@Url.Action("UICustomize", "Home", new { area = "" })',
    ....

which in your case will generate /Home/UICustomize instead of /ClientManagement/Home/UICustomize.

However you should not be rendering your side bar using ajax. Instead, decorate you UICustomize() method with a [ChildActionOnly] attribute (so it cannot be navigated to by the user), and in your layout, use

@Html.Action("UICustomize", "Home", new { area = "" })

or

@{ Html.RenderAction("UICustomize", "Home", new { area = "" }); }

to render the partial view of your sidebar menu.


问:
How to print a html page with header and footer on all pages?
would like some help as i m trying to print the html page. I would like to have the header and the footer on all pages when printing.

this is my current code

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" media="all" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  </head>
  <body>

    <style media="screen">
      .header{
        top: 0;
        width: 100%;
        height: 100px;
        height: 100px;
      }
      .content{

      }
      .footer{
        padding-top: 50px;
        width: 100%;
        height: 100px;
      }
    </style>

    <div class="header">
      header
    </div>

    <div class="content">
      <table>
        <tr><td>dfdsfsdfsdf start</td></tr>
        <tr><td>dfdsfsdfsdf</td></tr>
        <tr><td>dfdsfsdfsdf</td></tr>
        <tr><td>dfdsfsdfsdf end</td></tr>
        <!-- there will be around 1000 record of  <tr><td></td></tr>-->
      </table>
    </div>

    <div class="footer">
      footer
    </div>

  </body>
</html>
</code>```

currently the header is not in the second page and the footer goes to the second page and there is no footer for the first page. So how can i do it so that it will look like a bank statement or any other statement where on every page there is a header and a footer and the value from the table remains in the middle of every page

Here is the image which i m getting currently
Here is the image which i m getting currently

答:
You may just want to provide the data as a downloadable .pdf or .doc, and configure that file to have a header and footer on each page. That's what my bank does with my statements.

I don't think HTML5 supports what you're trying to do. Though it would be cool feature for HTML6.

Body:
would like some help as i m trying to print the html page. I would like to have the header and the footer on all pages when printing.

this is my current code

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" media="all" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

      header

dfdsfsdfsdf start

dfdsfsdfsdf

dfdsfsdfsdf

dfdsfsdfsdf end

      footer

currently the header is not in the second page and the footer goes to the second page and there is no footer for the first page. So how can i do it so that it will look like a bank statement or any other statement where on every page there is a header and a footer and the value from the table remains in the middle of every page

Here is the image which i m getting currently
Here is the image which i m getting currently


问:
Check if an object is equal to array
I would like to check if an object has a child object array

for example

```<code>{
   "parent_category_id": "ABC",
   "parent_category_name": "ABC COMPANY",
   "place_id": 733,
   "industry": {
       "@nil": "true"
   }
   "street_id": 733
}
</code>```

How would you check if the "Industry" object would have a child array.
Like if "Industry" has a child array value of "@nil: true". Then alert Has Child

答:
You can do:

info = {
  "string": "ABC",
  "array": [1, 2, 3],
  "object": {
    "key": "value"
  },
  "object(empty)": {},
}

function isEmpty(obj) {
  if (obj instanceof Object && !(obj instanceof Array)) {
    for (var i in obj) {
      if (hasOwnProperty.call(obj, i)) return false;
    }
  }
  return true;
}

for (var i in info) {
  if (isEmpty(info[i]) == false) {
    console.log(info[i]);
  }
}```

Reference: Is object empty?

Title: Check if an object is equal to array

Body:
I would like to check if an object has a child object array

for example

{
   "parent_category_id": "ABC",
   "parent_category_name": "ABC COMPANY",
   "place_id": 733,
   "industry": {
       "@nil": "true"
   }
   "street_id": 733
}

How would you check if the "Industry" object would have a child array.
Like if "Industry" has a child array value of "@nil: true". Then alert Has Child

Body:
You can do:

info = {
  "string": "ABC",
  "array": [1, 2, 3],
  "object": {
    "key": "value"
  },
  "object(empty)": {},
}

function isEmpty(obj) {
  if (obj instanceof Object && !(obj instanceof Array)) {
    for (var i in obj) {
      if (hasOwnProperty.call(obj, i)) return false;
    }
  }
  return true;
}

for (var i in info) {
  if (isEmpty(info[i]) == false) {
    console.log(info[i]);
  }
}

Reference: Is object empty?