问:
Error setting Coturn Server on Google Compute Cloud VM instance
I am trying to setup the coturn server on a google compute cloud VM instance running ubuntu 14.04. I think this is a firewall issue but I have opened the port tcp:3478 and udp:3478 in the firewall settings. No other process is running on the 3478 port. Anyone tried setting this on gcloud?
What am I doing wrong.</p>

```<code>$ sudo turnserver -a -v -n -r north.gov -L 35.189.173.237
0: log file opened: /var/log/turn_2564_2017-07-06.log
0:
RFC 3489/5389/5766/5780/6062/6156 STUN/TURN Server
Version Coturn-4.5.0.6 'dan Eider'
0:
Max number of open files/sockets allowed for this process: 65536
0:
Due to the open files/sockets limitation,
max supported number of TURN Sessions possible is: 32500 (approximately)
0:

==== Show him the instruments, Practical Frost: ====

0: TLS supported
0: DTLS supported
0: DTLS 1.2 supported
0: TURN/STUN ALPN supported
0: Third-party authorization (oAuth) supported
0: GCM (AEAD) supported
0: OpenSSL compile-time version: OpenSSL 1.0.2g  1 Mar 2016 (0x1000207f)
0:
0: SQLite supported, default database location is /usr/local/var/db/turndb
0: Redis is not supported
0: PostgreSQL is not supported
0: MySQL is not supported
0: MongoDB is not supported
0:
0: Default Net Engine version: 3 (UDP thread per CPU core)

=====================================================

0: Listener address to use: 35.189.173.237
0: Domain name:
0: Default realm: north.gov
0: WARNING: cannot find certificate file: turn_server_cert.pem (1)
0: WARNING: cannot start TLS and DTLS listeners because certificate file is not set properly
0: WARNING: cannot find private key file: turn_server_pkey.pem (1)
0: WARNING: cannot start TLS and DTLS listeners because private key file is not set properly
0: Relay address to use: 35.189.173.237
0: pid file created: /var/run/turnserver.pid
0: IO method (main listener thread): epoll (with changelist)
0: WARNING: I cannot support STUN CHANGE_REQUEST functionality because only one IP address is provided
0: Wait for relay ports initialization...
0:   relay 35.189.173.237 initialization...
0:   relay 35.189.173.237 initialization done
0: Relay ports initialization done
0: IO method (general relay thread): epoll (with changelist)
0: turn server id=1 created
bind: Cannot assign requested address
0: IO method (general relay thread): epoll (with changelist)
0: turn server id=0 created
bind: Cannot assign requested address
bind: Cannot assign requested address
0: Trying to bind fd 16 to <35.189.173.237:3478>: errno=99
Cannot bind local socket to addr: Cannot assign requested address
0: Trying to bind fd 20 to <35.189.173.237:3478>: errno=99
Cannot bind local socket to addr: Cannot assign requested address
0: Cannot bind DTLS/UDP listener socket to addr 35.189.173.237:3478
0: Trying to bind DTLS/UDP listener socket to addr 35.189.173.237:3478, again...
0: Cannot bind TLS/TCP listener socket to addr 35.189.173.237:3478
0: Trying to bind TLS/TCP listener socket to addr 35.189.173.237:3478, again...
0: Trying to bind fd 18 to <35.189.173.237:3478>: errno=99
Cannot bind local socket to addr: Cannot assign requested address
0: Cannot bind TLS/TCP listener socket to addr 35.189.173.237:3478
0: Trying to bind TLS/TCP listener socket to addr 35.189.173.237:3478, again...
bind: Cannot assign requested address
0: Trying to bind fd 20 to <35.189.173.237:3478>: errno=99
Cannot bind local socket to addr: Cannot assign requested address
0: Cannot bind DTLS/UDP listener socket to addr 35.189.173.237:3478
0: Trying to bind DTLS/UDP listener socket to addr 35.189.173.237:3478, again...
bind: Cannot assign requested address
0: Trying to bind fd 16 to <35.189.173.237:3478>: errno=99
bind: Cannot assign requested address
0: Trying to bind fd 18 to <35.189.173.237:3478>: errno=99
Cannot bind local socket to addr: Cannot assign requested address
Cannot bind local socket to addr: Cannot assign requested address
0: Cannot bind TLS/TCP listener socket to addr 35.189.173.237:3478
0: Trying to bind TLS/TCP listener socket to addr 35.189.173.237:3478, again...
0: Cannot bind TLS/TCP listener socket to addr 35.189.173.237:3478
0: Trying to bind TLS/TCP listener socket to addr 35.189.173.237:3478, again...
bind: Cannot assign requested address
0: Trying to bind fd 20 to <35.189.173.237:3478>: errno=99
Cannot bind local socket to addr: Cannot assign requested address
0: Cannot bind DTLS/UDP listener socket to addr 35.189.173.237:3478
0: Trying to bind DTLS/UDP listener socket to addr 35.189.173.237:3478, again...
bind: Cannot assign requested address
bind: Cannot assign requested address
</code>```

答: I figured out I was using a wrong command to start the turnserver. If anyone is facing problems setting up a a coturn server on AmazaonEC2/GCloud, this really helped me a lot: https://blog.knoldus.com/2013/10/24/configure-turn-server-for-webrtc-on-amazon-ec2/</p>

Body:
I am trying to setup the coturn server on a google compute cloud VM instance running ubuntu 14.04. I think this is a firewall issue but I have opened the port tcp:3478 and udp:3478 in the firewall settings. No other process is running on the 3478 port. Anyone tried setting this on gcloud?
What am I doing wrong.

$ sudo turnserver -a -v -n -r north.gov -L 35.189.173.237
0: log file opened: /var/log/turn_2564_2017-07-06.log
0:
RFC 3489/5389/5766/5780/6062/6156 STUN/TURN Server
Version Coturn-4.5.0.6 'dan Eider'
0:
Max number of open files/sockets allowed for this process: 65536
0:
Due to the open files/sockets limitation,
max supported number of TURN Sessions possible is: 32500 (approximately)
0:

==== Show him the instruments, Practical Frost: ====

0: TLS supported
0: DTLS supported
0: DTLS 1.2 supported
0: TURN/STUN ALPN supported
0: Third-party authorization (oAuth) supported
0: GCM (AEAD) supported
0: OpenSSL compile-time version: OpenSSL 1.0.2g  1 Mar 2016 (0x1000207f)
0:
0: SQLite supported, default database location is /usr/local/var/db/turndb
0: Redis is not supported
0: PostgreSQL is not supported
0: MySQL is not supported
0: MongoDB is not supported
0:
0: Default Net Engine version: 3 (UDP thread per CPU core)

=====================================================

0: Listener address to use: 35.189.173.237
0: Domain name:
0: Default realm: north.gov
0: WARNING: cannot find certificate file: turn_server_cert.pem (1)
0: WARNING: cannot start TLS and DTLS listeners because certificate file is not set properly
0: WARNING: cannot find private key file: turn_server_pkey.pem (1)
0: WARNING: cannot start TLS and DTLS listeners because private key file is not set properly
0: Relay address to use: 35.189.173.237
0: pid file created: /var/run/turnserver.pid
0: IO method (main listener thread): epoll (with changelist)
0: WARNING: I cannot support STUN CHANGE_REQUEST functionality because only one IP address is provided
0: Wait for relay ports initialization...
0:   relay 35.189.173.237 initialization...
0:   relay 35.189.173.237 initialization done
0: Relay ports initialization done
0: IO method (general relay thread): epoll (with changelist)
0: turn server id=1 created
bind: Cannot assign requested address
0: IO method (general relay thread): epoll (with changelist)
0: turn server id=0 created
bind: Cannot assign requested address
bind: Cannot assign requested address
0: Trying to bind fd 16 to <35.189.173.237:3478>: errno=99
Cannot bind local socket to addr: Cannot assign requested address
0: Trying to bind fd 20 to <35.189.173.237:3478>: errno=99
Cannot bind local socket to addr: Cannot assign requested address
0: Cannot bind DTLS/UDP listener socket to addr 35.189.173.237:3478
0: Trying to bind DTLS/UDP listener socket to addr 35.189.173.237:3478, again...
0: Cannot bind TLS/TCP listener socket to addr 35.189.173.237:3478
0: Trying to bind TLS/TCP listener socket to addr 35.189.173.237:3478, again...
0: Trying to bind fd 18 to <35.189.173.237:3478>: errno=99
Cannot bind local socket to addr: Cannot assign requested address
0: Cannot bind TLS/TCP listener socket to addr 35.189.173.237:3478
0: Trying to bind TLS/TCP listener socket to addr 35.189.173.237:3478, again...
bind: Cannot assign requested address
0: Trying to bind fd 20 to <35.189.173.237:3478>: errno=99
Cannot bind local socket to addr: Cannot assign requested address
0: Cannot bind DTLS/UDP listener socket to addr 35.189.173.237:3478
0: Trying to bind DTLS/UDP listener socket to addr 35.189.173.237:3478, again...
bind: Cannot assign requested address
0: Trying to bind fd 16 to <35.189.173.237:3478>: errno=99
bind: Cannot assign requested address
0: Trying to bind fd 18 to <35.189.173.237:3478>: errno=99
Cannot bind local socket to addr: Cannot assign requested address
Cannot bind local socket to addr: Cannot assign requested address
0: Cannot bind TLS/TCP listener socket to addr 35.189.173.237:3478
0: Trying to bind TLS/TCP listener socket to addr 35.189.173.237:3478, again...
0: Cannot bind TLS/TCP listener socket to addr 35.189.173.237:3478
0: Trying to bind TLS/TCP listener socket to addr 35.189.173.237:3478, again...
bind: Cannot assign requested address
0: Trying to bind fd 20 to <35.189.173.237:3478>: errno=99
Cannot bind local socket to addr: Cannot assign requested address
0: Cannot bind DTLS/UDP listener socket to addr 35.189.173.237:3478
0: Trying to bind DTLS/UDP listener socket to addr 35.189.173.237:3478, again...
bind: Cannot assign requested address
bind: Cannot assign requested address


来源: stackexchange

问:
pandas expanding apply for regression beta
Hi I'm trying to calculate regression betas for an expanding window in pandas. I have the following function to calculate beta

```<code>  def beta(row, col1, col2):
      return numpy.cov(row[col1],row[col2]) / numpy.var(row[col1])
</code>```

And I've tried the following to get the expanding beta on my dataframe df

```<code>pandas.expanding_apply(df, beta, col1='col1', col2='col2')
pandas.expanding_apply(df, beta, kwargs={'col1':'col1', 'col2':'col2'})
df.expanding.apply(...)
</code>```

However none of them work, I either get something that says the kwargs aren't getting passed through or if I hardcode the column names in the beta function I get

```<code>*** IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
</code>```

Thanks

Example:

```<code>def beta(row, col1, col2):
    return numpy.cov(row[col1],row[col2]) / numpy.var(row[col1])
df = pandas.DataFrame({'a':[1,2,3,4,5],'b':[.1,5,.3,.5,6]})
pandas.expanding_apply(compute_df, beta, col1='a', col2='b')
pandas.expanding_apply(compute_df, beta, kwargs={'col1':'a', 'col2':'b'})
</code>```

Both of those return errors

答:
I've run into this issue when trying to calculate betas for rolling multiple regression, very similar to what you're doing (see here).  The key issue is that with Expanding.apply(func, args=(), kwargs={}), the func param

Must produce a single value from an ndarray input *args and **kwargs
  are passed to the function

[source]

And there is really no way to accomodate using expanding.apply.  (Note: as mentioned, expanding_apply is deprecated.)

Below is a workaround.  It's more computationally expensive (will eat up memory) but will get you to your output.  It creates a list of expanding-window NumPy arrays and then calculates a beta over each.

```<code>from pandas_datareader.data import DataReader as dr
import numpy as np
import pandas as pd

df = (dr(['GOOG', 'SPY'], 'google')['Close']
      .pct_change()
      .dropna())

# i is the asset, m is market/index
# [0, 1] grabs cov_i,j from the covar. matrix
def beta(i, m):
    return np.cov(i, m)[0, 1] / np.var(m)

def expwins(x, min_periods):
    return [x[:i] for i in range(min_periods, x.shape[0] + 1)]

# Example:
# arr = np.arange(10).reshape(5, 2)
# print(expwins(arr, min_periods=3)[1]) # the 2nd window of the set
# array([[0, 1],
       # [2, 3],
       # [4, 5],
       # [6, 7]])

min_periods = 21
# Create "blocks" of expanding windows
wins = expwins(df.values, min_periods=min_periods)
# Calculate a beta (single scalar val.) for each
betas = [beta(win[:, 0], win[:, 1]) for win in wins]
betas = pd.Series(betas, index=df.index[min_periods - 1:])

print(betas)
Date
2010-02-03    0.77572
2010-02-04    0.74769
2010-02-05    0.76692
2010-02-08    0.74301
2010-02-09    0.74741
2010-02-10    0.74635
2010-02-11    0.74735
2010-02-12    0.74605
2010-02-16    0.78521
2010-02-17    0.77619
2010-02-18    0.79188
2010-02-19    0.78952

2017-06-19    0.97387
2017-06-20    0.97390
2017-06-21    0.97386
2017-06-22    0.97387
2017-06-23    0.97391
2017-06-26    0.97389
2017-06-27    0.97482
2017-06-28    0.97508
2017-06-29    0.97594
2017-06-30    0.97584
2017-07-03    0.97575
2017-07-05    0.97588
dtype: float64
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hi I'm trying to calculate regression betas for an expanding window in pandas. I have the following function to calculate beta

  def beta(row, col1, col2):
      return numpy.cov(row[col1],row[col2]) / numpy.var(row[col1])

And I've tried the following to get the expanding beta on my dataframe df

pandas.expanding_apply(df, beta, col1='col1', col2='col2')
pandas.expanding_apply(df, beta, kwargs={'col1':'col1', 'col2':'col2'})
df.expanding.apply(...)

However none of them work, I either get something that says the kwargs aren't getting passed through or if I hardcode the column names in the beta function I get

*** IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

Thanks

Example:

def beta(row, col1, col2):
    return numpy.cov(row[col1],row[col2]) / numpy.var(row[col1])
df = pandas.DataFrame({'a':[1,2,3,4,5],'b':[.1,5,.3,.5,6]})
pandas.expanding_apply(compute_df, beta, col1='a', col2='b')
pandas.expanding_apply(compute_df, beta, kwargs={'col1':'a', 'col2':'b'})

Both of those return errors

Body:
I've run into this issue when trying to calculate betas for rolling multiple regression, very similar to what you're doing (see here).  The key issue is that with Expanding.apply(func, args=(), kwargs={}), the func param

Must produce a single value from an ndarray input *args and **kwargs
  are passed to the function

[source]

And there is really no way to accomodate using expanding.apply.  (Note: as mentioned, expanding_apply is deprecated.)

Below is a workaround.  It's more computationally expensive (will eat up memory) but will get you to your output.  It creates a list of expanding-window NumPy arrays and then calculates a beta over each.

from pandas_datareader.data import DataReader as dr
import numpy as np
import pandas as pd

df = (dr(['GOOG', 'SPY'], 'google')['Close']
      .pct_change()
      .dropna())

# i is the asset, m is market/index
# [0, 1] grabs cov_i,j from the covar. matrix
def beta(i, m):
    return np.cov(i, m)[0, 1] / np.var(m)

def expwins(x, min_periods):
    return [x[:i] for i in range(min_periods, x.shape[0] + 1)]

# Example:
# arr = np.arange(10).reshape(5, 2)
# print(expwins(arr, min_periods=3)[1]) # the 2nd window of the set
# array([[0, 1],
       # [2, 3],
       # [4, 5],
       # [6, 7]])

min_periods = 21
# Create "blocks" of expanding windows
wins = expwins(df.values, min_periods=min_periods)
# Calculate a beta (single scalar val.) for each
betas = [beta(win[:, 0], win[:, 1]) for win in wins]
betas = pd.Series(betas, index=df.index[min_periods - 1:])

print(betas)
Date
2010-02-03    0.77572
2010-02-04    0.74769
2010-02-05    0.76692
2010-02-08    0.74301
2010-02-09    0.74741
2010-02-10    0.74635
2010-02-11    0.74735
2010-02-12    0.74605
2010-02-16    0.78521
2010-02-17    0.77619
2010-02-18    0.79188
2010-02-19    0.78952

2017-06-19    0.97387
2017-06-20    0.97390
2017-06-21    0.97386
2017-06-22    0.97387
2017-06-23    0.97391
2017-06-26    0.97389
2017-06-27    0.97482
2017-06-28    0.97508
2017-06-29    0.97594
2017-06-30    0.97584
2017-07-03    0.97575
2017-07-05    0.97588
dtype: float64


问:
SVN Commit failed: error 413 Request Entity too large
I am facing the following issue: I have a folder under SVN control and several jar files within it.
The point is that there is a file I cannot commit and I get the mentioned error, but the rest of the jar files were commited with no problem.
And actually, this jar file I cannot commit is the one with lowest size (320kb) and I have commited files with 2.5MB under the same folder.

Any idea?
Thanks in advance.

答: You should contact the admin or manager of your server for assistance. I recall that a broken antivirus on server or client side can cause this behavior. Don't forget to check your firewall and proxy (if any) and make sure that you use up to date SVN client and server versions.</p>


问:
List contents of a location in the registry
I am trying to populate a list box on a form with the contents of: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts.  I am able to read the details of an specific entry within "Fonts" and populate a text box, but my desire is to just show everything that resides in "Fonts" in a list box. Can anyone assist?</p>

答:
You can use Registry.LocalMachine and its OpenSubKey() method in order to open the registry key for reading. Then just call GetSubKeyNames() on that to retrieve all the names of its sub keys:

```<code>Using FontKey As RegistryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts")
    For Each SubKey As String In FontKey.GetSubKeyNames()
        ListBox1.Items.Add(SubKey)
    Next
End Using
</code>```

Also put this in the top of your code file:

```<code>Imports Microsoft.Win32
</code>```

EDIT:

Since the above doesn't seem to work for you try this method which closes the registry key manually:

```<code>Dim FontKey As RegistryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts")
For Each SubKey As String In FontKey.GetSubKeyNames()
    ListBox1.Items.Add(SubKey)
Next
FontKey.Close()
</code>```

EDIT 2:

Getting the value from the specified value name isn't hard, just call the GetValue() method of the FontKey:

```<code>Dim FontKey As RegistryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts")
For Each ValueName As String In FontKey.GetValueNames()
    Dim Value As Object = FontKey.GetValue(ValueName) 'Get the value (data) of the specified value name.
    If Value IsNot Nothing Then 'Make sure it exists.
        ListBox1.Items.Add(Value.ToString())
    End If
Next
FontKey.Close()
</code>```

Body:
You can use Registry.LocalMachine and its OpenSubKey() method in order to open the registry key for reading. Then just call GetSubKeyNames() on that to retrieve all the names of its sub keys:

Using FontKey As RegistryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts")
    For Each SubKey As String In FontKey.GetSubKeyNames()
        ListBox1.Items.Add(SubKey)
    Next
End Using

Also put this in the top of your code file:

Imports Microsoft.Win32

EDIT:

Since the above doesn't seem to work for you try this method which closes the registry key manually:

Dim FontKey As RegistryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts")
For Each SubKey As String In FontKey.GetSubKeyNames()
    ListBox1.Items.Add(SubKey)
Next
FontKey.Close()

EDIT 2:

Getting the value from the specified value name isn't hard, just call the GetValue() method of the FontKey:

Dim FontKey As RegistryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts")
For Each ValueName As String In FontKey.GetValueNames()
    Dim Value As Object = FontKey.GetValue(ValueName) 'Get the value (data) of the specified value name.
    If Value IsNot Nothing Then 'Make sure it exists.
        ListBox1.Items.Add(Value.ToString())
    End If
Next
FontKey.Close()


问:
why ajax call not succeed?
I create this ajax function:

```<code>function getAssociatedProperties(callback, error) {
    $.ajax({
        url: '/LayerProperty/get',
        type: "GET",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: 5,
        crossDomain: true,
        success: callback,
        error: function () {

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

And here is my web api class:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace GeomindMobile.Controllers
{
    public class LayerProperty : ApiController
    {
        // GET api/<controller>
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/<controller>/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/<controller>
        public void Post([FromBody]string value)
        {
        }

        // PUT api/<controller>/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/<controller>/5
        public void Delete(int id)
        {
        }
    }
}
</code>```

Whenever ajax function fired I get this error:

```<code>http://localhost/LayerProperty/get 404 (Not Found)
</code>```

Update

```<code>Here is my 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 = "Index", id = UrlParameter.Optional }
            );
        }
</code>```

What is wrong with my code?why ajax call not succeed?

答:
you have error in url.</p>

```<code>function getAssociatedProperties(callback, error) {
    $.ajax({
        url: '/api/LayerProperty/get',
        type: "GET",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: 5,
        crossDomain: true,
        success: callback,
        error: function () {

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

Title: why ajax call not succeed?

Body:
I create this ajax function:

function getAssociatedProperties(callback, error) {
    $.ajax({
        url: '/LayerProperty/get',
        type: "GET",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: 5,
        crossDomain: true,
        success: callback,
        error: function () {

        }
    });
}

And here is my web api class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace GeomindMobile.Controllers
{
    public class LayerProperty : ApiController
    {
        // GET api/<controller>
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/<controller>/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/<controller>
        public void Post([FromBody]string value)
        {
        }

        // PUT api/<controller>/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/<controller>/5
        public void Delete(int id)
        {
        }
    }
}

Whenever ajax function fired I get this error:

http://localhost/LayerProperty/get 404 (Not Found)

Update

Here is my 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 = "Index", id = UrlParameter.Optional }
            );
        }

What is wrong with my code?why ajax call not succeed?

Body:
you have error in url.

function getAssociatedProperties(callback, error) {
    $.ajax({
        url: '/api/LayerProperty/get',
        type: "GET",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: 5,
        crossDomain: true,
        success: callback,
        error: function () {

        }
    });
}


问:
regex validate height without apostrophe
I am needing to validate person's height to feet and inches without the use of single or double quotes.  Here is an example I am looking for:

508 ==> 5' 8"

Zero's are used as place holders in this requirement.  Additionally, I need to check for valid inches but must have placeholder:

08 ==> 8 inches valid

8  ==> 8 inches invalid (missing placeholder)

13 ==> invalid (11 is max)

Feet and inches together:

511 ==> 5'11" (valid)

512 ==> 5'12" (invalid, should be written as 600)

513 ==> 5'13" (invalid, should be written as 601)

I have tried the following:

^(\d{1,5})((\s?)(-?)(\s?)([0-9]|(1[0-1])))?$

but this does not check for placeholder neither does it handle numbers greater than 12.

Appreciate any help in resolving this!

Body:
How about this:

^\d{0,1}0[1-9]|1[0-2]$


答:
```<code>function getAssociatedProperties(callback, error) {
    $.ajax({
        url: '/api/LayerProperty', // <--- You do not need the 'get' here, but you do need the /api/
        type: "GET",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: 5,
        crossDomain: true,
        success: callback,
        error: function () {

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

Title: why ajax call not succeed?


问:
how to permit an array with strong parameters
I have a functioning Rails 3 app that uses has_many :through associations which is not, as I remake it as a Rails 4 app, letting me save ids from the associated model in the Rails 4 version.

These are the three relevant models are the same for the two versions.

Categorization.rb

```<code>class Categorization < ActiveRecord::Base

  belongs_to :question
  belongs_to :category
end
</code>```

Question.rb

```<code>has_many :categorizations
has_many :categories, through: :categorizations
</code>```

Category.rb

```<code>has_many :categorizations
has_many :questions, through: :categorizations
</code>```

In both apps, the category ids are getting passed into the create action like this

```<code>  "question"=>{"question_content"=>"How do you spell car?", "question_details"=>"blah ", "category_ids"=>["", "2"],
</code>```

In the Rails 3 app, when I create a new question, it inserts into questions table and then into the categorizations table

```<code> SQL (82.1ms)  INSERT INTO "questions" ("accepted_answer_id", "city", "created_at", "details", "province", "province_id", "question", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)  [["accepted_answer_id", nil], ["city", "dd"], ["created_at", Tue, 14 May 2013 17:10:25 UTC +00:00], ["details", "greyound?"], ["province", nil], ["province_id", 2], ["question", "Whos' the biggest dog in the world"], ["updated_at", Tue, 14 May 2013 17:10:25 UTC +00:00], ["user_id", 53]]
  SQL (0.4ms)  INSERT INTO "categorizations" ("category_id", "created_at", "question_id", "updated_at") VALUES (?, ?, ?, ?)  [["category_id", 2], ["created_at", Tue, 14 May 2013 17:10:25 UTC +00:00], ["question_id", 66], ["updated_at", Tue, 14 May 2013 17:10:25 UTC +00:00]]
</code>```

In the rails 4 app, after it processes the parameters in QuestionController#create, I'm getting this error in the server logs

```<code>Unpermitted parameters: category_ids
</code>```

and the question is only getting inserted into the questions table

```<code> (0.2ms)  BEGIN
  SQL (67.6ms)  INSERT INTO "questions" ("city", "created_at", "province_id", "question_content", "question_details", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id"  [["city", "dd"], ["created_at", Tue, 14 May 2013 17:17:53 UTC +00:00], ["province_id", 3], ["question_content", "How's your car?"], ["question_details", "is it runnign"], ["updated_at", Tue, 14 May 2013 17:17:53 UTC +00:00], ["user_id", 12]]
   (31.9ms)  COMMIT
</code>```

Although I am not storing the category_ids on the Questions model, I set category_ids as a permitted parameter in the questions_controller

```<code>   def question_params

      params.require(:question).permit(:question_details, :question_content, :user_id, :accepted_answer_id, :province_id, :city, :category_ids)
    end
</code>```

Can anyone explain how I'm supposed to save the category_ids?  Note, there is no create action in the categories_controller.rb of either app.

These are the three tables that are the same in both apps

```<code> create_table "questions", force: true do |t|
    t.text     "question_details"
    t.string   "question_content"
    t.integer  "user_id"
    t.integer  "accepted_answer_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "province_id"
    t.string   "city"
  end

 create_table "categories", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "categorizations", force: true do |t|
    t.integer  "category_id"
    t.integer  "question_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end
</code>```

Update

This is the create action from the Rails 3 app

```<code>  def create
      @question = Question.new(params[:question])
      respond_to do |format|
      if @question.save
        format.html { redirect_to @question, notice: 'Question was successfully created.' }
        format.json { render json: @question, status: :created, location: @question }
      else
        format.html { render action: "new" }
        format.json { render json: @question.errors, status: :unprocessable_entity }
      end
    end
end
</code>```

This is the create action from the Rails 4 app

```<code>   def create
      @question = Question.new(question_params)

       respond_to do |format|
      if @question.save
        format.html { redirect_to @question, notice: 'Question was successfully created.' }
        format.json { render json: @question, status: :created, location: @question }
      else
        format.html { render action: "new" }
        format.json { render json: @question.errors, status: :unprocessable_entity }
      end
    end
    end
</code>```

This is the question_params method

```<code> private
    def question_params
      params.require(:question).permit(:question_details, :question_content, :user_id, :accepted_answer_id, :province_id, :city, :category_ids)
    end
</code>```

答:
It should be like

```<code>params.permit(:id => [])
</code>```

Also since rails version 4+ you can use:

```<code>params.permit(id: [])
</code>```

Body:
I have a functioning Rails 3 app that uses has_many :through associations which is not, as I remake it as a Rails 4 app, letting me save ids from the associated model in the Rails 4 version.

These are the three relevant models are the same for the two versions.

Categorization.rb

class Categorization < ActiveRecord::Base

  belongs_to :question
  belongs_to :category
end

Question.rb

has_many :categorizations
has_many :categories, through: :categorizations

Category.rb

has_many :categorizations
has_many :questions, through: :categorizations

In both apps, the category ids are getting passed into the create action like this

  "question"=>{"question_content"=>"How do you spell car?", "question_details"=>"blah ", "category_ids"=>["", "2"],

In the Rails 3 app, when I create a new question, it inserts into questions table and then into the categorizations table

 SQL (82.1ms)  INSERT INTO "questions" ("accepted_answer_id", "city", "created_at", "details", "province", "province_id", "question", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)  [["accepted_answer_id", nil], ["city", "dd"], ["created_at", Tue, 14 May 2013 17:10:25 UTC +00:00], ["details", "greyound?"], ["province", nil], ["province_id", 2], ["question", "Whos' the biggest dog in the world"], ["updated_at", Tue, 14 May 2013 17:10:25 UTC +00:00], ["user_id", 53]]
  SQL (0.4ms)  INSERT INTO "categorizations" ("category_id", "created_at", "question_id", "updated_at") VALUES (?, ?, ?, ?)  [["category_id", 2], ["created_at", Tue, 14 May 2013 17:10:25 UTC +00:00], ["question_id", 66], ["updated_at", Tue, 14 May 2013 17:10:25 UTC +00:00]]

In the rails 4 app, after it processes the parameters in QuestionController#create, I'm getting this error in the server logs

Unpermitted parameters: category_ids

and the question is only getting inserted into the questions table

 (0.2ms)  BEGIN
  SQL (67.6ms)  INSERT INTO "questions" ("city", "created_at", "province_id", "question_content", "question_details", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id"  [["city", "dd"], ["created_at", Tue, 14 May 2013 17:17:53 UTC +00:00], ["province_id", 3], ["question_content", "How's your car?"], ["question_details", "is it runnign"], ["updated_at", Tue, 14 May 2013 17:17:53 UTC +00:00], ["user_id", 12]]
   (31.9ms)  COMMIT

Although I am not storing the category_ids on the Questions model, I set category_ids as a permitted parameter in the questions_controller

   def question_params

      params.require(:question).permit(:question_details, :question_content, :user_id, :accepted_answer_id, :province_id, :city, :category_ids)
    end

Can anyone explain how I'm supposed to save the category_ids?  Note, there is no create action in the categories_controller.rb of either app.

These are the three tables that are the same in both apps

 create_table "questions", force: true do |t|
    t.text     "question_details"
    t.string   "question_content"
    t.integer  "user_id"
    t.integer  "accepted_answer_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "province_id"
    t.string   "city"
  end

 create_table "categories", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "categorizations", force: true do |t|
    t.integer  "category_id"
    t.integer  "question_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

Update

This is the create action from the Rails 3 app

  def create
      @question = Question.new(params[:question])
      respond_to do |format|
      if @question.save
        format.html { redirect_to @question, notice: 'Question was successfully created.' }
        format.json { render json: @question, status: :created, location: @question }
      else
        format.html { render action: "new" }
        format.json { render json: @question.errors, status: :unprocessable_entity }
      end
    end
end

This is the create action from the Rails 4 app

   def create
      @question = Question.new(question_params)

       respond_to do |format|
      if @question.save
        format.html { redirect_to @question, notice: 'Question was successfully created.' }
        format.json { render json: @question, status: :created, location: @question }
      else
        format.html { render action: "new" }
        format.json { render json: @question.errors, status: :unprocessable_entity }
      end
    end
    end

This is the question_params method

 private
    def question_params
      params.require(:question).permit(:question_details, :question_content, :user_id, :accepted_answer_id, :province_id, :city, :category_ids)
    end

Body:
It should be like

params.permit(:id => [])

Also since rails version 4+ you can use:

params.permit(id: [])


问:
Modify complicated character vector automatically
I have a complicated character vector, whereby each element of the vector consists of numbers and letters. I want to simplify this vector, so that sequences of numbers and/or letters are put into ranges. Here is an example, how the input and output vectors should look like:

```<code># Input vector
input_vec <- c("1,2,3,4,5", "1,2,3,5,6,7,8", "2,3,4,5", "A,B,C", "1,2,3,4,5,A,B,8,9,10,11")

# Here some function should be applied, to create the desired output vector automatically

# Desired output vector
output_vec <- c("1-5", "1-3,5-8", "2-5", "A-C", "1-5,A-B,8-11")
</code>```

I am sure there must be a way to build a function or to use a package, to do this in an automatized way, but unfortunately I am struggling to find a solution. Any help is highly appreciated!

UPDATE: Added an even more complicated vector

```<code>input_vec2 <- c("1,2,3,4,5", "1,2,3,5,6,7,8", "2,3,4,5", "A,B,C", "1,2,3,4,5,A,B,8,9,10,11",
"1", "1,2,3,-4", "lala,3") # This part is new

output_vec2 <- c("1-5", "1-3,5-8", "2-5", "A-C", "1-5,A-B,8-11",
"1", "1-3,-4", "lala,3") # This part is new
</code>```

答:
This is perhaps a bit bloated still, but I tried to break the problem down into smaller functions. Here they are. First some general helper functions

```<code># Is value numeric?
is_numeric <- function(x) suppressWarnings(!is.na(as.numeric(x)))
# Greate IDs for sequences of values using run-length encoding
rleg <- function(x) {
  r <- rle(x);
  val <- list(group_value = r$values)
  r$values <- seq_along(r$values);
  val$group_id <- inverse.rle(r)
  val
}
</code>```

And now some more specific helpers for the problem

```<code>collapse_sequence <- function(x) {
  if (length(x)>1) {
    paste0(x[1],"-", x[length(x)])
  } else {
    x
  }
}

find_runs <- function(x, key=x) {
  nona <- function(x) {x[is.na(x)]<-0; x}
  run <- cumsum(nona(c(1,diff(key)))!=1)
  Map(collapse_sequence, split(x, run))
}

collapse_numeric <- function(x) {
  paste(sapply(find_runs(x, as.numeric(x)), collapse_sequence), collapse=",")
}

collapse_character <- function(x) {
  key <- sapply(x, function(z) ifelse(nchar(z)==1, utf8ToInt(z), NA))
  paste(sapply(find_runs(x, key), collapse_sequence), collapse=",")
}

collapse_runs <- Vectorize(function(x) {
  x <- strsplit(x, ",")[[1]]
  type <- ifelse(is_numeric(x), 1, ifelse(nchar(x)==1, 2, 3))
  group <- rleg(type)
  runs <- Map(function(v, type) {
    if(type==1) {
      collapse_numeric(v)
    } else {
      collapse_character(v)
    }
  },split(x, group$group_id), group$group_value)
  paste(runs, collapse=",")
})
</code>```

And finally we test it with your input

```<code>input_vec <- c("1,2,3,4,5", "1,2,3,5,6,7,8", "2,3,4,5", "A,B,C", "1,2,3,4,5,A,B,8,9,10,11")
unname(collapse_runs(input_vec))
# [1] "1-5"          "1-3,5-8"      "2-5"          "A-C"          "1-5,A-B,8-11"
input_vec2 <- c("1,2,3,4,5", "1,2,3,5,6,7,8", "2,3,4,5", "A,B,C", "1,2,3,4,5,A,B,8,9,10,11", "1",
            "1,2,3,-4", "lala,3")
unname(collapse_runs(input_vec2))
# [1] "1-5"          "1-3,5-8"      "2-5"          "A-C"          "1-5,A-B,8-11"
# [6] "1"            "1-3,-4"       "lala,3"
</code>```

Body:
I have a complicated character vector, whereby each element of the vector consists of numbers and letters. I want to simplify this vector, so that sequences of numbers and/or letters are put into ranges. Here is an example, how the input and output vectors should look like:

# Input vector
input_vec <- c("1,2,3,4,5", "1,2,3,5,6,7,8", "2,3,4,5", "A,B,C", "1,2,3,4,5,A,B,8,9,10,11")

# Here some function should be applied, to create the desired output vector automatically

# Desired output vector
output_vec <- c("1-5", "1-3,5-8", "2-5", "A-C", "1-5,A-B,8-11")

I am sure there must be a way to build a function or to use a package, to do this in an automatized way, but unfortunately I am struggling to find a solution. Any help is highly appreciated!

UPDATE: Added an even more complicated vector

input_vec2 <- c("1,2,3,4,5", "1,2,3,5,6,7,8", "2,3,4,5", "A,B,C", "1,2,3,4,5,A,B,8,9,10,11",
"1", "1,2,3,-4", "lala,3") # This part is new

output_vec2 <- c("1-5", "1-3,5-8", "2-5", "A-C", "1-5,A-B,8-11",
"1", "1-3,-4", "lala,3") # This part is new

Body:
This is perhaps a bit bloated still, but I tried to break the problem down into smaller functions. Here they are. First some general helper functions

# Is value numeric?
is_numeric <- function(x) suppressWarnings(!is.na(as.numeric(x)))
# Greate IDs for sequences of values using run-length encoding
rleg <- function(x) {
  r <- rle(x);
  val <- list(group_value = r$values)
  r$values <- seq_along(r$values);
  val$group_id <- inverse.rle(r)
  val
}

And now some more specific helpers for the problem

collapse_sequence <- function(x) {
  if (length(x)>1) {
    paste0(x[1],"-", x[length(x)])
  } else {
    x
  }
}

find_runs <- function(x, key=x) {
  nona <- function(x) {x[is.na(x)]<-0; x}
  run <- cumsum(nona(c(1,diff(key)))!=1)
  Map(collapse_sequence, split(x, run))
}

collapse_numeric <- function(x) {
  paste(sapply(find_runs(x, as.numeric(x)), collapse_sequence), collapse=",")
}

collapse_character <- function(x) {
  key <- sapply(x, function(z) ifelse(nchar(z)==1, utf8ToInt(z), NA))
  paste(sapply(find_runs(x, key), collapse_sequence), collapse=",")
}

collapse_runs <- Vectorize(function(x) {
  x <- strsplit(x, ",")[[1]]
  type <- ifelse(is_numeric(x), 1, ifelse(nchar(x)==1, 2, 3))
  group <- rleg(type)
  runs <- Map(function(v, type) {
    if(type==1) {
      collapse_numeric(v)
    } else {
      collapse_character(v)
    }
  },split(x, group$group_id), group$group_value)
  paste(runs, collapse=",")
})

And finally we test it with your input

input_vec <- c("1,2,3,4,5", "1,2,3,5,6,7,8", "2,3,4,5", "A,B,C", "1,2,3,4,5,A,B,8,9,10,11")
unname(collapse_runs(input_vec))
# [1] "1-5"          "1-3,5-8"      "2-5"          "A-C"          "1-5,A-B,8-11"
input_vec2 <- c("1,2,3,4,5", "1,2,3,5,6,7,8", "2,3,4,5", "A,B,C", "1,2,3,4,5,A,B,8,9,10,11", "1",
            "1,2,3,-4", "lala,3")
unname(collapse_runs(input_vec2))
# [1] "1-5"          "1-3,5-8"      "2-5"          "A-C"          "1-5,A-B,8-11"
# [6] "1"            "1-3,-4"       "lala,3"


问:
PHP string replace the first and last occurance
I am trying to replace the occurrence of li tag with a tag but I also replace the other lis used in the string.

for example I have this:

```<code><li id="item" class="list-item" href="#">Item</li>
</code>```

but I want to replace the li tags without the list-item class name replaced.

if I do :

```<code>$f = array( '><a', 'li' );
$r = array( '', 'a' );
// output the menu
echo str_replace( $f, $r, $menu );
</code>```

then the class name list-item becomes ast-item where li is replaced with a.

How can I just replace the li tag and not all the instance of li?

答:
try this</p>

```<code>$input_lines = '<li id="item" class="list-item" href="#">Item</li>';
preg_replace("/\<(\/?)li([^\>]*)\>/", "<$1a$2>", $input_lines);
</code>```

Body:
I am trying to replace the occurrence of li tag with a tag but I also replace the other lis used in the string.

for example I have this:

Item

but I want to replace the li tags without the list-item class name replaced.

if I do :

$f = array( '><a', 'li' );
$r = array( '', 'a' );
// output the menu
echo str_replace( $f, $r, $menu );

then the class name list-item becomes ast-item where li is replaced with a.

How can I just replace the li tag and not all the instance of li?

Body:
try this

$input_lines = '<li id="item" class="list-item" href="#">Item</li>';
preg_replace("/\<(\/?)li([^\>]*)\>/", "<$1a$2>", $input_lines);


答:
You could try making your search params a bit more accurate to avoid that problem. Example:

```<code>$menu = "<li id=\"item\" class=\"list-item\" href=\"#\">Item</li>";
$f = array( '<li', '</li>' );
$r = array( '<a', '</a>' );
// output the menu
$x = str_replace( $f, $r, $menu );
</code>```

Generally speaking, you should avoid parsing HTML with Regexs.

Title: PHP string replace the first and last occurance

Body:
You could try making your search params a bit more accurate to avoid that problem. Example:

$menu = "<li id=\"item\" class=\"list-item\" href=\"#\">Item</li>";
$f = array( '<li', '</li>' );
$r = array( '<a', '</a>' );
// output the menu
$x = str_replace( $f, $r, $menu );

Generally speaking, you should avoid parsing HTML with Regexs.


问:
Rewrite URL doesn't do anything
I'm making a simple blog for my portfolio for school. If I click on a link to show a blogpost, my url is domain.com/post?post_link=First-Post I've read a hunderds of SO items about changing this url, but nothing works for me...

I hope that anyone see what is the problem and give a solution

I have 3 files, blog.php(Here are all the posts showed), post.php(Here is one blogpost showed, based on post tiltle from page before) and a .htaccess file.

My blog.php:

```<code><form method="GET" action="post.php">
                    <input type="hidden" name="post_link" value="<?php echo $post_link;?>">
                    <input type="submit" name="">
                </form>
</code>```

My post.php:

```<code>$post_link = $_GET["post_link"];

$sql = "SELECT * FROM blogposts WHERE post_link='$post_link'";
$result = mysqli_query($conn, $sql);
    if ($result) {
        while ($row = mysqli_fetch_array($result)) {
            $post_link = $row["post_link"];
        }
        echo $post_link;
    }
</code>```

My .htaccess file:

```<code>Options FollowSymLinks
RewriteEngine On
RewriteRule ^post/([0-9a-zA-Z]+)$ post.php?post_link=$1
RewriteRule ^post/([0-9a-zA-Z]+)/ post.php?post_link=$1

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
</code>```

In addition to rewriting the url, everything works fine, like showing the posts and showing a single post

In blog.php, my input type hidden value is correct.

Please help..

Daniël

答:
Change your action to just post

```<code><form method="GET" action="post">
</code>```

The resulting URL should be localhost/takast/post?post_link=First-Post

This Rule will then match this, but you need to keep the querystring [QSA].

Complete .htaccess:

```<code>Options FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [QSA]
</code>```

Title: Rewrite URL doesn't do anything

Body:
I'm making a simple blog for my portfolio for school. If I click on a link to show a blogpost, my url is domain.com/post?post_link=First-Post I've read a hunderds of SO items about changing this url, but nothing works for me...

I hope that anyone see what is the problem and give a solution

I have 3 files, blog.php(Here are all the posts showed), post.php(Here is one blogpost showed, based on post tiltle from page before) and a .htaccess file.

My blog.php:

<form method="GET" action="post.php">
                    <input type="hidden" name="post_link" value="<?php echo $post_link;?>">
                    <input type="submit" name="">
                </form>

My post.php:

$post_link = $_GET["post_link"];

$sql = "SELECT * FROM blogposts WHERE post_link='$post_link'";
$result = mysqli_query($conn, $sql);
    if ($result) {
        while ($row = mysqli_fetch_array($result)) {
            $post_link = $row["post_link"];
        }
        echo $post_link;
    }

My .htaccess file:

Options FollowSymLinks
RewriteEngine On
RewriteRule ^post/([0-9a-zA-Z]+)$ post.php?post_link=$1
RewriteRule ^post/([0-9a-zA-Z]+)/ post.php?post_link=$1

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

In addition to rewriting the url, everything works fine, like showing the posts and showing a single post

In blog.php, my input type hidden value is correct.

Please help..

Daniël

Body:
Change your action to just post

<form method="GET" action="post">

The resulting URL should be localhost/takast/post?post_link=First-Post

This Rule will then match this, but you need to keep the querystring [QSA].

Complete .htaccess:

Options FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [QSA]


问:
Accessing your backend API without using CORS
I'm teaching myself web dev and am just getting into sending XMLHttpRequests from a client-facing page to an Express.js API backend.  In this particular case I'm using it to transmit form data and save it to a Mongo Database.

The specific issue I'm having is this:  I send it encoded as application/json, which throws me a cross-origin error because the Express.js API is running on http://127.0.0.1:3000.  I understand that requests to the same domain but a different port cause this error.

I've been able to get around it by doing npm install cors and then using var cors = require('cors'); and app.use(cors()); in my Express.js source, but as I understand it that will open the API up to requests from anywhere.  What if I really do just want it to only be accessible on my own domain?  I mean supposing it were a production site mysite.com and the form is at mysite.com/form and the backend is at mysite.com:3000.  I think I'm getting those example ideas right, but as I'm new to this I'm not sure.

How can I get them to be running on the same domain so as to not be doing a cross-origin request?  Is there a standard way to do this?  As of now I feel like to get the backend and the form running on the same port would require serving the form page from the Express.js backend itself, but what if I didn't want Express to be my server?  What if I wanted to serve pages some other way, from Apache or something, and just have this form on there that sends its data off to Express for processing?  Or if I wanted to have an Angular app running that POSTs data to the Express backend, again for processing?

Thank you!

答:
If you want to stick with CORS, you can configure it to stick to a certain origin: https://www.npmjs.com/package/cors#configuring-cors
But keep in mind that this doesn't prevent from someone else accessing your API via a simple curl command. CORS is there to guard the browser, not the API.

A better approach (that you mentioned yourself) would be to have both parts running at the same domain and port. This can be achieved by proxying the requests. In Express you could simply deliver your frontend code as static assets with express.static(). In Apache you could also add some proxying, though I cannot help you there, as I'm not that familiar with Apache modules and setups.

Securing your API from third-party access is another topic. You'll need some form of authentication and authorization. Doing that right can be hard. Perhaps you should have a look at Oauth 2 for a proven standard.


问:
String matching objective-c
I need to match my string in this way: *myString*
where * mean any substring.
which method should I use?

can you help me, please?

答:
If it's for iPhone OS 3.2 or later, use NSRegularExpressionSearch. </p>

```<code>NSString *regEx = [NSString stringWithFormat:@".*%@.*", yourSearchString];
NSRange range = [stringToSearch rangeOfString:regEx options:NSRegularExpressionSearch];
if (range.location != NSNotFound) {

}
</code>```

ContentLicense: CC BY-SA 2.5

Title: String matching objective-c

Body:
If it's for iPhone OS 3.2 or later, use NSRegularExpressionSearch.

NSString *regEx = [NSString stringWithFormat:@".*%@.*", yourSearchString];
NSRange range = [stringToSearch rangeOfString:regEx options:NSRegularExpressionSearch];
if (range.location != NSNotFound) {

}


问:
Is client aware of endorsing peers through which it makes a transaction proposal in Hyperledger Fabric?
Is client aware of endorsing peers through which it makes a transaction proposal? If yes, how does it know or where is it configured ?, If No, then which peer first take a proposal to endorse the Transaction. </p>

答:
Yes, client should be aware of the endorsing peers that it will send proposal to while fabric-sdk(node, java, python, etc...) is not aware of the endorsing peers. fabric-sdk just sends proposal to the endorsing peers list that the client told it. Please notice that fabric-sdk is just part of your client application.
You can refer to the example invoke chaincode</p>


问:
Gradle DSL method not found 'compile()' (firebase conflict)
MY ERROR

I've been looking through many posts on stackoverflow with this problem and almost everyone saying that main problem that can cause situation like this is compiling libraries in project-level gradle file, but my file dependencies looks like this:

```<code>dependencies {
    classpath 'com.google.gms:google-services:3.1.0'
    classpath 'com.android.tools.build:gradle:2.3.3'
}
</code>```

also, my app-level gradle file looks like this

```<code>dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'

    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:appcompat-v7:25.3.1'

    compile 'com.github.bumptech.glide:glide:3.7.0'

    complie 'com.google.firebase:firebase-auth:11.0.2'
    compile 'com.google.firebase:firebase-database:11.0.2'
    compile 'com.firebaseui:firebase-ui-auth:2.0.1'
}

apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.android.application'
</code>```

it points on 46 line which equals
    complie 'com.google.firebase:firebase-auth:11.0.2'

This is my first post on stackoverflow, so sorry if given information maybe be not correct, appreciate your help

答:
There's a typo.

You wrote complie instead of compile

Body:
MY ERROR

I've been looking through many posts on stackoverflow with this problem and almost everyone saying that main problem that can cause situation like this is compiling libraries in project-level gradle file, but my file dependencies looks like this:

dependencies {
    classpath 'com.google.gms:google-services:3.1.0'
    classpath 'com.android.tools.build:gradle:2.3.3'
}

also, my app-level gradle file looks like this

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'

    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:appcompat-v7:25.3.1'

    compile 'com.github.bumptech.glide:glide:3.7.0'

    complie 'com.google.firebase:firebase-auth:11.0.2'
    compile 'com.google.firebase:firebase-database:11.0.2'
    compile 'com.firebaseui:firebase-ui-auth:2.0.1'
}

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

it points on 46 line which equals
    complie 'com.google.firebase:firebase-auth:11.0.2'

This is my first post on stackoverflow, so sorry if given information maybe be not correct, appreciate your help


问:
Is this done with a regular expression? Formatting Latitude Longitude
I am trying to format a polygon (several lat/long coordinates connected together) using Leaflet Draw. Here is the format return and what I have done so far:

```<code>map.on("draw:drawstop", polyPointToString);
function polyPointToString(e){
    console.log("Unaltered Coordinates: " + coords);
    polyStringParse = coords.toString().replace(/[^\d,.-]/g, '');
    console.log("Polyparse: " + polyStringParse);
    polyStringParseRegExp = polyStringParse.replace(/([^,]+[^,]),/g,'$1 ');
    console.log("PolyparseRegExp: " + polyStringParseRegExp);
}
</code>```

Unaltered Coordinates is this:

```<code>//Unaltered Coordinates: LatLng(46.58907, -102.74414),LatLng(46.58907, -102.74414),LatLng(46.58907, -102.74414)
</code>```

PolyParse is this (only numbers, dashes, and decimal points left):

```<code>//Polyparse: 46.58907,-102.74414,46.58907,-102.74414,46.58907,-102.74414
</code>```

PolyparseRegExpt is this(it keeps removing ALL commas :-(   ):

```<code>//Polyparse2: 46.58907 -102.74414 46.58907 -102.74414 46.58907 -102.74414
</code>```

What is need: Comma 1, 3, 5, 7.... etc removed so that I have:

number number, number number, number number,........

Basilcally, every odd numbed comma. right now it's removing all commas for some reason.

答:
The simplest solution (?) - add the other coordinate (preceded by it's comma), making it a pair, capturing it separately without the comma:

```<code>([^,]+[^,]),([^,]+[^,],)
</code>```

replacing it with

$1 $2 (space between and trailing)

reforms the coordinate pair, without the separating comma but leaving the trailing.

See it here at regex101.

Body:
I am trying to format a polygon (several lat/long coordinates connected together) using Leaflet Draw. Here is the format return and what I have done so far:

map.on("draw:drawstop", polyPointToString);
function polyPointToString(e){
    console.log("Unaltered Coordinates: " + coords);
    polyStringParse = coords.toString().replace(/[^\d,.-]/g, '');
    console.log("Polyparse: " + polyStringParse);
    polyStringParseRegExp = polyStringParse.replace(/([^,]+[^,]),/g,'$1 ');
    console.log("PolyparseRegExp: " + polyStringParseRegExp);
}

Unaltered Coordinates is this:

//Unaltered Coordinates: LatLng(46.58907, -102.74414),LatLng(46.58907, -102.74414),LatLng(46.58907, -102.74414)

PolyParse is this (only numbers, dashes, and decimal points left):

//Polyparse: 46.58907,-102.74414,46.58907,-102.74414,46.58907,-102.74414

PolyparseRegExpt is this(it keeps removing ALL commas :-(   ):

//Polyparse2: 46.58907 -102.74414 46.58907 -102.74414 46.58907 -102.74414

What is need: Comma 1, 3, 5, 7.... etc removed so that I have:

number number, number number, number number,........

Basilcally, every odd numbed comma. right now it's removing all commas for some reason.

Body:
The simplest solution (?) - add the other coordinate (preceded by it's comma), making it a pair, capturing it separately without the comma:

([^,]+[^,]),([^,]+[^,],)

replacing it with

$1 $2 (space between and trailing)

reforms the coordinate pair, without the separating comma but leaving the trailing.

See it here at regex101.


问:
php - Google Analytics Measurement Protocol POST request
I have issue when sending POST request from my server to google analytics.

I'm trying to send test (event,order etc.), but then I do not receive anything and when I look to events tracker in browser there is absolutely nothing happening...

PHP code

```<code>$x  =   [
            'v'=>'1',
            't'=>'event',
            'tid'=>'.....',    // here goes my tracking ID
            'cid'=>'555',
            'ec'=>'video'
        ];

echo(google_a($x));

function google_a($x)                           {
    $x  = http_build_query($x);
    $ch = curl_init();
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    curl_setopt($ch,CURLOPT_USERAGENT, $user_agent);
    curl_setopt($ch, CURLOPT_URL,"https://www.google-analytics.com/collect");
    curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/x-www-form-urlencoded'));
    curl_setopt($ch,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
    curl_setopt($ch,CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$x);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $server_output = curl_exec ($ch);

    curl_close ($ch);
    return($server_output);
}
</code>```

I think that my CURL configuration isn't good. Can you help me with this?

答:
I've solved this problem by adding this lines. They, as I understand, disable SSL connection verifying:

```<code>curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
</code>```

So, I'm able to control google analytics from server :))

Body:
I have issue when sending POST request from my server to google analytics.

I'm trying to send test (event,order etc.), but then I do not receive anything and when I look to events tracker in browser there is absolutely nothing happening...

PHP code

$x  =   [
            'v'=>'1',
            't'=>'event',
            'tid'=>'.....',    // here goes my tracking ID
            'cid'=>'555',
            'ec'=>'video'
        ];

echo(google_a($x));

function google_a($x)                           {
    $x  = http_build_query($x);
    $ch = curl_init();
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    curl_setopt($ch,CURLOPT_USERAGENT, $user_agent);
    curl_setopt($ch, CURLOPT_URL,"https://www.google-analytics.com/collect");
    curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/x-www-form-urlencoded'));
    curl_setopt($ch,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
    curl_setopt($ch,CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$x);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $server_output = curl_exec ($ch);

    curl_close ($ch);
    return($server_output);
}

I think that my CURL configuration isn't good. Can you help me with this?

Body:
I've solved this problem by adding this lines. They, as I understand, disable SSL connection verifying:

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

So, I'm able to control google analytics from server :))


问:
Frequency of events in a week
My data has trips with datetime info, user id for each trip and trip type (single, round, pseudo).

Here's a data sample (pandas dataframe), named All_Data:

```<code>HoraDTRetirada        idpass        type
2016-02-17 15:36:00  39579449489   'single'
2016-02-18 19:13:00  39579449489   'single'
2016-02-26 09:20:00  72986744521   'pseudo'
2016-02-27 12:11:00  72986744521   'round'
2016-02-27 14:55:00  11533148958   'pseudo'
2016-02-28 12:27:00  72986744521   'round'
2016-02-28 16:32:00  72986744521   'round'
</code>```

I would like to count the number of times each category repeats in a "week of year" by user.

For example, if the event happens on a monday and the next event happens on a thursday for a same user, that makes two events on the same week; however, if one event happens on a saturday and the next event happens on the following monday, they happened in different weeks.

The output I am looking for would be in a form like this:

```<code>idpass        weekofyear   type      frequency
39579449489    1           'single'   2
72986744521    2           'round'    3
72986744521    2           'pseudo'   1
11533148958    2           'pseudo'   1
</code>```

Edit: this older question approaches a similar problem, but I don't know how to do it with pandas.

答:
This is how I got what I was looking for:

Step 1 from suggested answers was skipped because timestamps were already in pandas datetime form.

Step 2: create column for week of year:

df['week'] = df['HoraDTRetirada'].dt.strftime('%U')

Step 3: group by user id, type and week, and count values with size()

df.groupby(['idpass','type','week']).size()

Title: Frequency of events in a week

Body:
My data has trips with datetime info, user id for each trip and trip type (single, round, pseudo).

Here's a data sample (pandas dataframe), named All_Data:

HoraDTRetirada        idpass        type
2016-02-17 15:36:00  39579449489   'single'
2016-02-18 19:13:00  39579449489   'single'
2016-02-26 09:20:00  72986744521   'pseudo'
2016-02-27 12:11:00  72986744521   'round'
2016-02-27 14:55:00  11533148958   'pseudo'
2016-02-28 12:27:00  72986744521   'round'
2016-02-28 16:32:00  72986744521   'round'

I would like to count the number of times each category repeats in a "week of year" by user.

For example, if the event happens on a monday and the next event happens on a thursday for a same user, that makes two events on the same week; however, if one event happens on a saturday and the next event happens on the following monday, they happened in different weeks.

The output I am looking for would be in a form like this:

idpass        weekofyear   type      frequency
39579449489    1           'single'   2
72986744521    2           'round'    3
72986744521    2           'pseudo'   1
11533148958    2           'pseudo'   1

Edit: this older question approaches a similar problem, but I don't know how to do it with pandas.


问:
Native methods and platform independency
Here's a comment extracted from source code of Java's public static native long currentTimeMillis() method of java.lang.System class.

```<code> * Returns the current time in milliseconds.  Note that
 * while the unit of time of the return value is a millisecond,
 * the granularity of the value depends on the underlying
 * operating system and may be larger.  For example, many
 * operating systems measure time in units of tens of
 * milliseconds.
</code>```

It's obvious from this comment that behavior of this native method is platform dependent. If this is the case, should we avoid native method calls for writing truly platform independent code in Java?

答:
It is obvious from this comment that behavior of this native method is platform dependent.

That is correct.

If this is the case, should we avoid native method calls for writing truly platform independent code in Java?

No.  That is not the right lesson to draw from this.

A lot of the functionality of the Java class libraries ultimately depends on native calls.  If you decided to avoid calling native methods, then (for start) your program would not be able to do any I/O.  It would make Java impractical.  And in the case of time, if you avoided all native methods then you would not be able to get the time at all.

The real reason that some standard Java APIs have platform specific behavior is that the differences exist in the platforms themselves.  The differences cannot be hidden without unduly restricting what an application is able to do.

In your example, the comment explains that system clocks provided by different OSes have different granularity time measures.  This is an unavoidable fact.  The only way to hide this (in the name of "portability") would have been to artificially reduce the granularity on systems that provide millisecond or better resolution.  This would not be acceptable to people who need the maximum resolution available.

The correct lessons to learn (IMO) are as follows:

You need to read and understand what the javadocs actually say about platform specific behaviors.

Then you need to design your application so that it doesn't depend on platform specific behavior.  For example, if you need maximal portability, don't design your application to depend on a millisecond granularity clock.

Where possible, use APIs that deal with platform specifics.  For example, use File or Path rather than string bashing when manipulating file-system pathnames.

Body:
Here's a comment extracted from source code of Java's public static native long currentTimeMillis() method of java.lang.System class.

 * Returns the current time in milliseconds.  Note that
 * while the unit of time of the return value is a millisecond,
 * the granularity of the value depends on the underlying
 * operating system and may be larger.  For example, many
 * operating systems measure time in units of tens of
 * milliseconds.

It's obvious from this comment that behavior of this native method is platform dependent. If this is the case, should we avoid native method calls for writing truly platform independent code in Java?


问:
Why OS struck on creating infinite java threads
I was just curious and written following code.
On running code, console showed threads created. I noticed there were around 32k threads created.
My question is,
Why My windows 10 OS hanged and also could not stop forcefully with task manager.
Since my machine has i7 processor, why OS didn't manage to run on other processes?
I believe threads created by java program must have been in one of the processes.

I am a beginner to java.
Kindly let me know what happens internally in above case?

```<code>package infiniteThreads;

public class Main {

    public static void main(String[] args) {
        while(true){
            Thread t = new Thread(new Work());
            t.start();
        }

    }

}
</code>```

```<code>package infiniteThreads;

public class Work implements Runnable{

    @Override
    public void run() {
        while(true){
            System.out.println("inside " + Thread.currentThread().getName());
        }

    }

}
</code>```

答:
As far as java is concerned, it would be consuming all the processors and all CPU threads available on your system. But the limitation that you are hitting with your experiment here is an OS Level limitation which is around Handles could read more about the it here.

Maybe you could try fiddling things around with your system setup to try to get some more insights with your experiment could try this link.

Body:
I was just curious and written following code.
On running code, console showed threads created. I noticed there were around 32k threads created.
My question is,
Why My windows 10 OS hanged and also could not stop forcefully with task manager.
Since my machine has i7 processor, why OS didn't manage to run on other processes?
I believe threads created by java program must have been in one of the processes.

I am a beginner to java.
Kindly let me know what happens internally in above case?

package infiniteThreads;

public class Main {

    public static void main(String[] args) {
        while(true){
            Thread t = new Thread(new Work());
            t.start();
        }

    }

}

package infiniteThreads;

public class Work implements Runnable{

    @Override
    public void run() {
        while(true){
            System.out.println("inside " + Thread.currentThread().getName());
        }

    }

}


问:
What is the "M- notation" and where is it documented?
The man page of cat  says:

```<code>-v, --show-nonprinting
    use ^ and M- notation, except for LFD and TAB
</code>```

What is the M- notation and where is it documented?

Example:

```<code>$cat log -A
wrote 262144 bytes from file test.x in 9.853947s (25.979 KiB/s)^M$
^M> ^H^H  ^H^H>
</code>```

What do ^M and ^H mean?

答:
I was wondering this too. I checked the source but it seemed easier to create a input file to get the mapping.

I created a test input file with a Perl scrip for( my $i=0 ; $i < 256; $i++ ) {  print ( sprintf( "%c is %d %x\n", $i, $i ,$i ) ); } and then ran it through cat -v

Also if you see M-oM-;M-? at the start of a file it is the UTF-8 byte order mark.

Scroll down through these to get to the M- values:

```<code>^@ is 0 0
^A is 1 1
^B is 2 2
^C is 3 3
^D is 4 4
^E is 5 5
^F is 6 6
^G is 7 7
^H is 8 8
(9 is tab)
(10 is NL)
^K is 11 b
^L is 12 c
^M is 13 d
^N is 14 e
^O is 15 f
^P is 16 10
^Q is 17 11
^R is 18 12
^S is 19 13
^T is 20 14
^U is 21 15
^V is 22 16
^W is 23 17
^X is 24 18
^Y is 25 19
^Z is 26 1a
^[ is 27 1b
^\ is 28 1c
^] is 29 1d
^^ is 30 1e
^_ is 31 1f
...printing chars removed...
^? is 127 7f
M-^@ is 128 80
M-^A is 129 81
M-^B is 130 82
M-^C is 131 83
M-^D is 132 84
M-^E is 133 85
M-^F is 134 86
M-^G is 135 87
M-^H is 136 88
M-^I is 137 89
M-^J is 138 8a
M-^K is 139 8b
M-^L is 140 8c
M-^M is 141 8d
M-^N is 142 8e
M-^O is 143 8f
M-^P is 144 90
M-^Q is 145 91
M-^R is 146 92
M-^S is 147 93
M-^T is 148 94
M-^U is 149 95
M-^V is 150 96
M-^W is 151 97
M-^X is 152 98
M-^Y is 153 99
M-^Z is 154 9a
M-^[ is 155 9b
M-^\ is 156 9c
M-^] is 157 9d
M-^^ is 158 9e
M-^_ is 159 9f
M-  is 160 a0
M-! is 161 a1
M-" is 162 a2
M-# is 163 a3
M-$ is 164 a4
M-% is 165 a5
M-& is 166 a6
M-' is 167 a7
M-( is 168 a8
M-) is 169 a9
M-* is 170 aa
M-+ is 171 ab
M-, is 172 ac
M-- is 173 ad
M-. is 174 ae
M-/ is 175 af
M-0 is 176 b0
M-1 is 177 b1
M-2 is 178 b2
M-3 is 179 b3
M-4 is 180 b4
M-5 is 181 b5
M-6 is 182 b6
M-7 is 183 b7
M-8 is 184 b8
M-9 is 185 b9
M-: is 186 ba
M-; is 187 bb
M-< is 188 bc
M-= is 189 bd
M-> is 190 be
M-? is 191 bf
M-@ is 192 c0
M-A is 193 c1
M-B is 194 c2
M-C is 195 c3
M-D is 196 c4
M-E is 197 c5
M-F is 198 c6
M-G is 199 c7
M-H is 200 c8
M-I is 201 c9
M-J is 202 ca
M-K is 203 cb
M-L is 204 cc
M-M is 205 cd
M-N is 206 ce
M-O is 207 cf
M-P is 208 d0
M-Q is 209 d1
M-R is 210 d2
M-S is 211 d3
M-T is 212 d4
M-U is 213 d5
M-V is 214 d6
M-W is 215 d7
M-X is 216 d8
M-Y is 217 d9
M-Z is 218 da
M-[ is 219 db
M-\ is 220 dc
M-] is 221 dd
M-^ is 222 de
M-_ is 223 df
M-` is 224 e0
M-a is 225 e1
M-b is 226 e2
M-c is 227 e3
M-d is 228 e4
M-e is 229 e5
M-f is 230 e6
M-g is 231 e7
M-h is 232 e8
M-i is 233 e9
M-j is 234 ea
M-k is 235 eb
M-l is 236 ec
M-m is 237 ed
M-n is 238 ee
M-o is 239 ef
M-p is 240 f0
M-q is 241 f1
M-r is 242 f2
M-s is 243 f3
M-t is 244 f4
M-u is 245 f5
M-v is 246 f6
M-w is 247 f7
M-x is 248 f8
M-y is 249 f9
M-z is 250 fa
M-{ is 251 fb
M-| is 252 fc
M-} is 253 fd
M-~ is 254 fe
M-^? is 255 ff
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The man page of cat  says:

-v, --show-nonprinting
    use ^ and M- notation, except for LFD and TAB

What is the M- notation and where is it documented?

Example:

$cat log -A
wrote 262144 bytes from file test.x in 9.853947s (25.979 KiB/s)^M$
^M> ^H^H  ^H^H>

What do ^M and ^H mean?

Body:
I was wondering this too. I checked the source but it seemed easier to create a input file to get the mapping.

I created a test input file with a Perl scrip for( my $i=0 ; $i < 256; $i++ ) {  print ( sprintf( "%c is %d %x\n", $i, $i ,$i ) ); } and then ran it through cat -v

Also if you see M-oM-;M-? at the start of a file it is the UTF-8 byte order mark.

Scroll down through these to get to the M- values:

^@ is 0 0
^A is 1 1
^B is 2 2
^C is 3 3
^D is 4 4
^E is 5 5
^F is 6 6
^G is 7 7
^H is 8 8
(9 is tab)
(10 is NL)
^K is 11 b
^L is 12 c
^M is 13 d
^N is 14 e
^O is 15 f
^P is 16 10
^Q is 17 11
^R is 18 12
^S is 19 13
^T is 20 14
^U is 21 15
^V is 22 16
^W is 23 17
^X is 24 18
^Y is 25 19
^Z is 26 1a
^[ is 27 1b
^\ is 28 1c
^] is 29 1d
^^ is 30 1e
^_ is 31 1f
...printing chars removed...
^? is 127 7f
M-^@ is 128 80
M-^A is 129 81
M-^B is 130 82
M-^C is 131 83
M-^D is 132 84
M-^E is 133 85
M-^F is 134 86
M-^G is 135 87
M-^H is 136 88
M-^I is 137 89
M-^J is 138 8a
M-^K is 139 8b
M-^L is 140 8c
M-^M is 141 8d
M-^N is 142 8e
M-^O is 143 8f
M-^P is 144 90
M-^Q is 145 91
M-^R is 146 92
M-^S is 147 93
M-^T is 148 94
M-^U is 149 95
M-^V is 150 96
M-^W is 151 97
M-^X is 152 98
M-^Y is 153 99
M-^Z is 154 9a
M-^[ is 155 9b
M-^\ is 156 9c
M-^] is 157 9d
M-^^ is 158 9e
M-^_ is 159 9f
M-  is 160 a0
M-! is 161 a1
M-" is 162 a2
M-# is 163 a3
M-$ is 164 a4
M-% is 165 a5
M-& is 166 a6
M-' is 167 a7
M-( is 168 a8
M-) is 169 a9
M-* is 170 aa
M-+ is 171 ab
M-, is 172 ac
M-- is 173 ad
M-. is 174 ae
M-/ is 175 af
M-0 is 176 b0
M-1 is 177 b1
M-2 is 178 b2
M-3 is 179 b3
M-4 is 180 b4
M-5 is 181 b5
M-6 is 182 b6
M-7 is 183 b7
M-8 is 184 b8
M-9 is 185 b9
M-: is 186 ba
M-; is 187 bb
M-< is 188 bc
M-= is 189 bd
M-> is 190 be
M-? is 191 bf
M-@ is 192 c0
M-A is 193 c1
M-B is 194 c2
M-C is 195 c3
M-D is 196 c4
M-E is 197 c5
M-F is 198 c6
M-G is 199 c7
M-H is 200 c8
M-I is 201 c9
M-J is 202 ca
M-K is 203 cb
M-L is 204 cc
M-M is 205 cd
M-N is 206 ce
M-O is 207 cf
M-P is 208 d0
M-Q is 209 d1
M-R is 210 d2
M-S is 211 d3
M-T is 212 d4
M-U is 213 d5
M-V is 214 d6
M-W is 215 d7
M-X is 216 d8
M-Y is 217 d9
M-Z is 218 da
M-[ is 219 db
M-\ is 220 dc
M-] is 221 dd
M-^ is 222 de
M-_ is 223 df
M-` is 224 e0
M-a is 225 e1
M-b is 226 e2
M-c is 227 e3
M-d is 228 e4
M-e is 229 e5
M-f is 230 e6
M-g is 231 e7
M-h is 232 e8
M-i is 233 e9
M-j is 234 ea
M-k is 235 eb
M-l is 236 ec
M-m is 237 ed
M-n is 238 ee
M-o is 239 ef
M-p is 240 f0
M-q is 241 f1
M-r is 242 f2
M-s is 243 f3
M-t is 244 f4
M-u is 245 f5
M-v is 246 f6
M-w is 247 f7
M-x is 248 f8
M-y is 249 f9
M-z is 250 fa
M-{ is 251 fb
M-| is 252 fc
M-} is 253 fd
M-~ is 254 fe
M-^? is 255 ff


问:
Is it possible to get the string inside the enclosing '<' and '>' of a tag using jquery or plain javascript?
If  my question isn't clear,I don't want the outerhtml which returns all the contents inside a node.I don't want those.For example:

  Hello!

    How are you?Hope you are doing well!

```
</div>
</div>
</p>

<p>Now,outerHTML of 'foo' will give the whole string representation of its DOM structure.I just want </p>

```div id="foo" class="something" style="width:80%; display:inline-block"
```

Is it possible to get this without using regex/string matching?

答:
Using javascript element.nodeName and element.attributes to form a string:

var foo = document.getElementById('foo');
console.log(crazyString(foo));

function crazyString(el) {
  var a = [el.nodeName];
  var atts = el.attributes;
  for (var i=0; i < atts.length; i++) {
    a.push(atts[i].name + '="' + atts[i].value + '"');
  }
  return a.join(" ");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="foo" class="something" style="width:80%; display:inline-block">
  Hello!
  <div id="bar" class="something_else">
    How are you?Hope you are doing well!
  </div>
</div></code>```

Body:
If  my question isn't clear,I don't want the outerhtml which returns all the contents inside a node.I don't want those.For example:

  Hello!

    How are you?Hope you are doing well!

Now,outerHTML of 'foo' will give the whole string representation of its DOM structure.I just want

div id="foo" class="something" style="width:80%; display:inline-block"

Is it possible to get this without using regex/string matching?

Body:
Using javascript element.nodeName and element.attributes to form a string:

var foo = document.getElementById('foo');
console.log(crazyString(foo));

function crazyString(el) {
  var a = [el.nodeName];
  var atts = el.attributes;
  for (var i=0; i < atts.length; i++) {
    a.push(atts[i].name + '="' + atts[i].value + '"');
  }
  return a.join(" ");
}

<div id="foo" class="something" style="width:80%; display:inline-block">
  Hello!
  <div id="bar" class="something_else">
    How are you?Hope you are doing well!
  </div>
</div>


问:
Handling exceptions in a ViewModel without a View (in ReactiveUI)
I am currently building an application in C# using ReactiveUI that contains many views/viewmodels. Some of these viewmodels perform a network request at a preset interval. These network requests may fail at any time. I implemented this as follows:

```<code>public ReactiveCommand<Unit, IReactiveList<IJob>> RefreshJobList { get; }
public Interaction<Exception, Unit> RefreshError { get; } = new Interaction<Exception, Unit>();

...

RefreshJobList = ReactiveCommand.CreateFromTask(() => DoNetworkRequest());
RefreshJobList.ThrownExceptions.Subscribe(ex =>
{
    log.Error("Failed to retrieve job list from server.", ex);
    RefreshError.Handle(ex).Subscribe();
});
Observable.Interval(TimeSpan.FromMilliseconds(300)).Select(x => Unit.Default).InvokeCommand(RefreshJobList);
</code>```

In the corresponding views, I handle the exceptions as follows:

```<code>this.WhenActivated(d => d(
    this.ViewModel.RefreshError.RegisterHandler(interaction =>
    {
        MessageBox.Show("Failed to load joblist.", "Error", MessageBoxButton.OK);
        interaction.SetOutput(new Unit());
    })
));
</code>```

This works fine, except when the viewmodel isn't associated with a view. My application uses tabs, and when the user switches to a different tab, the previous view is destroyed. This leaves the viewmodel running, still making requests, without a view. Then, when an error occurs in RefreshJobList, no handlers are associated with RefreshError, ReactiveUI throws an UnhandledInteractionError and my application crashes.

I am not sure how to deal with this cleanly. My first thought would be to pause the ViewModel until a View is attached, which would also save network traffic. However, I can't seem any way to check whether or not a View is attached to the ViewModel. Any ideas?

答:
Why can't you use the WhenActivated extension in your view model to 'stop' / dispose of observables that should no longer be in play when the view is disposed?

I believe you can always catch the exception from the Interaction being handled in the Subscribe, just add an OnError handler.

Body:
I am currently building an application in C# using ReactiveUI that contains many views/viewmodels. Some of these viewmodels perform a network request at a preset interval. These network requests may fail at any time. I implemented this as follows:

public ReactiveCommand<Unit, IReactiveList<IJob>> RefreshJobList { get; }
public Interaction<Exception, Unit> RefreshError { get; } = new Interaction<Exception, Unit>();

...

RefreshJobList = ReactiveCommand.CreateFromTask(() => DoNetworkRequest());
RefreshJobList.ThrownExceptions.Subscribe(ex =>
{
    log.Error("Failed to retrieve job list from server.", ex);
    RefreshError.Handle(ex).Subscribe();
});
Observable.Interval(TimeSpan.FromMilliseconds(300)).Select(x => Unit.Default).InvokeCommand(RefreshJobList);

In the corresponding views, I handle the exceptions as follows:

this.WhenActivated(d => d(
    this.ViewModel.RefreshError.RegisterHandler(interaction =>
    {
        MessageBox.Show("Failed to load joblist.", "Error", MessageBoxButton.OK);
        interaction.SetOutput(new Unit());
    })
));

This works fine, except when the viewmodel isn't associated with a view. My application uses tabs, and when the user switches to a different tab, the previous view is destroyed. This leaves the viewmodel running, still making requests, without a view. Then, when an error occurs in RefreshJobList, no handlers are associated with RefreshError, ReactiveUI throws an UnhandledInteractionError and my application crashes.

I am not sure how to deal with this cleanly. My first thought would be to pause the ViewModel until a View is attached, which would also save network traffic. However, I can't seem any way to check whether or not a View is attached to the ViewModel. Any ideas?


问:
Azure functions with complex c# code
I have complex code in c# with multiple classes(and classes have different functions) and i want to implement it as azure function. The problem is that the architecture is as follows: stream data is coming to function as input and after complex calculation within the class functions, I need to return calculated values as stream again. To be returned values are inside class functions and I am having trouble to find a way to return these to "run" function. Is there any easy way to do it?
Structure is like this

```<code>public static void Run(string myQueueItem, TraceWriter log)
{
 // gets data from service bus per second
 call function 1
}

public class Class1
{
function1(){
 call function2
 }
}

public class Class2
{
function2()
output interested is in here and program creates an output after 30 31 seconds and continues to creates about every 20 second
)}
</code>```

Many thanks

答:
You should take a look at Azure Durable Functions announced recently. Unfortunately I have only read about it and not used it, hence I will not be able to propose how exactly it will solve your problem.

One neat thing I liked about this is that unlike your regular Functions, they are stateful in nature which lets you persist the local state.

Another thing I liked about this is that it is intended for long running tasks which is something you're after.

Looking at your question, I believe Function Chaining pattern is something that could be useful to you.

Title: Azure functions with complex c# code

Body:
I have complex code in c# with multiple classes(and classes have different functions) and i want to implement it as azure function. The problem is that the architecture is as follows: stream data is coming to function as input and after complex calculation within the class functions, I need to return calculated values as stream again. To be returned values are inside class functions and I am having trouble to find a way to return these to "run" function. Is there any easy way to do it?
Structure is like this

public static void Run(string myQueueItem, TraceWriter log)
{
 // gets data from service bus per second
 call function 1
}

public class Class1
{
function1(){
 call function2
 }
}

public class Class2
{
function2()
output interested is in here and program creates an output after 30 31 seconds and continues to creates about every 20 second
)}

Many thanks


问:
Check whether all items of item2 inside a tuple(long,int) is unique
Is there a way to use linq to check whether item2 from a tuple of long,int repeats itself more than once? I know it can be done on list. How to achieve the same in tuple? Can anyone help?</p>

答:
```<code>var item2Set = new HashSet<int>();
bool allUnique = tupleList.All(t => item2Set.Add(t.Item2));
</code>```

or

```<code>bool allUnique = !tupleList.GroupBy(t => t.Item2).Any(g => g.Count() > 1);
</code>```

or

```<code>bool allUnique = tupleList.GroupBy(t => t.Item2).All(g => g.Count() == 1);
</code>```

Body:
var item2Set = new HashSet<int>();
bool allUnique = tupleList.All(t => item2Set.Add(t.Item2));

or

bool allUnique = !tupleList.GroupBy(t => t.Item2).Any(g => g.Count() > 1);

or

bool allUnique = tupleList.GroupBy(t => t.Item2).All(g => g.Count() == 1);


问:
Ideal low pass filter - Simulink
I have the following time-continuous system: input signal -->abs block (in the time domain)-->ideal low pass filter block (in the frequency domain)-->output signal. In simulink I make the abs block with the Fcn block. My problem is to get ideal low pass filter with a 3000Hz band and 1 amplitude (linear scale). How could I get it? Maybe I should use Lowpass filter block? In this case what are the right parameters?

Thank you for your time.

答:
An ideal low-pass filter can be represented as (from https://en.wikipedia.org/wiki/Low-pass_filter):

So I suggest you use the Transfer Fcn block:

If your amplitude/gain is 1, and your cut-off frequency is 3kHz, then the gain K is 1 and the time constant is:

```<code>f = 3000;
tau = 1 / (2*pi*f);
</code>```

and your transfer function is:

```<code>num = 1;
den = [tau 1];
</code>```

Simple!

Title: Ideal low pass filter - Simulink

Body:
An ideal low-pass filter can be represented as (from https://en.wikipedia.org/wiki/Low-pass_filter):

So I suggest you use the Transfer Fcn block:

If your amplitude/gain is 1, and your cut-off frequency is 3kHz, then the gain K is 1 and the time constant is:

f = 3000;
tau = 1 / (2*pi*f);

and your transfer function is:

num = 1;
den = [tau 1];

Simple!


问:
Reduce bash environment variables size
Let's say I have a program that takes a very large number of command line arguments or a very large single command line argument. Let's assume, that my application wants to accept a single command line argument as a string of 65536 symbols (64kB). As everybody knows there is a limit on what amount of bytes one can pass to process with a command line and environment variables.

And here is a little experiment:

```<code>$ set > t
$ ls -lF | grep "\<t\>"
-rw-r--r--  1 sergey sergey 118737 Oct 14 23:45 t
</code>```

And this 118737 bytes is about 115kB. Header file /usr/include/linux/limits.h says that ARG_MAX is 131072 which is exactly 128kB.

Is there a way to reduce environment variables size of user bash session?

答:
I believe the export | wc -c command is not enough if you want to use that route as an approximation. I use bash shell functions. A LOT of them. And I export them to be available in subshells. Those are only discovered with export -f. So in theory you really need the output of both.

However, looking at my machine:

```<code>$  export -p | wc && export -f | wc
    147     479    9309
   6940   17029  150917

$  xargs --show-limits </dev/null
Your environment variables take up 121160 bytes
POSIX upper limit on argument length (this system): 1973944
POSIX smallest allowable upper limit on argument length (all systems): 4096
Maximum length of command we could actually use: 1852784
Size of command buffer we are actually using: 131072
</code>```

Perhaps the output of the export command gives a good look at the ratio between exported variables and functions, but it isn't reflective of the actual space used (9309 + 150917 != 121160).

And that kind of makes sense. Here is the output of one random function in my environment, via export -f:

```<code>usage_init ()
{
    USAGE_OPT_P1="-p pathvar - The envvar to process. Default is";
    USAGE_OPT_P2="             PATH, if -p is not specified.";
    USAGE_OPT_P3="             The '-p' is optional, in which case";
    USAGE_OPT_P4F="             the first ARGUMENT is assumed to be";
    USAGE_OPT_P4O="             the ARGUMENT is assumed to be";
    USAGE_OPT_P5="             the pathvar.";
    USAGE_OPT_S="-s sep - Path element separator. Defaults to ':'.";
    USAGE_OPT_X="-x - Exports 'pathvar'.";
    USAGE_OPT_V="-v - Executes function 'listpath' after assignment.";
    USAGE_OPT_H="-h - Gives usage message.";
    USAGE_OPT_E="-e - 'pathspec' is interpreted as an egrep regexp.";
    USAGE_OPT_N="-n - Add index numbers to the results."
}
declare -fx usage_init
</code>```

Here is the same function plucked out of env

```<code>BASH_FUNC_usage_init%%=() {  USAGE_OPT_P1="-p pathvar - The envvar to process. Default is";
 USAGE_OPT_P2="             PATH, if -p is not specified.";
 USAGE_OPT_P3="             The '-p' is optional, in which case";
 USAGE_OPT_P4F="             the first ARGUMENT is assumed to be";
 USAGE_OPT_P4O="             the ARGUMENT is assumed to be";
 USAGE_OPT_P5="             the pathvar.";
 USAGE_OPT_S="-s sep - Path element separator. Defaults to ':'.";
 USAGE_OPT_X="-x - Exports 'pathvar'.";
 USAGE_OPT_V="-v - Executes function 'listpath' after assignment.";
 USAGE_OPT_H="-h - Gives usage message.";
 USAGE_OPT_E="-e - 'pathspec' is interpreted as an egrep regexp.";
 USAGE_OPT_N="-n - Add index numbers to the results."
}
</code>```

export (and I think type) appear to do some prettying for presentation which inflates the wc -c value.

Title: Reduce bash environment variables size

Body:
Let's say I have a program that takes a very large number of command line arguments or a very large single command line argument. Let's assume, that my application wants to accept a single command line argument as a string of 65536 symbols (64kB). As everybody knows there is a limit on what amount of bytes one can pass to process with a command line and environment variables.

And here is a little experiment:

$ set > t
$ ls -lF | grep "\<t\>"
-rw-r--r--  1 sergey sergey 118737 Oct 14 23:45 t

And this 118737 bytes is about 115kB. Header file /usr/include/linux/limits.h says that ARG_MAX is 131072 which is exactly 128kB.

Is there a way to reduce environment variables size of user bash session?

Body:
I believe the export | wc -c command is not enough if you want to use that route as an approximation. I use bash shell functions. A LOT of them. And I export them to be available in subshells. Those are only discovered with export -f. So in theory you really need the output of both.

However, looking at my machine:

$  export -p | wc && export -f | wc
    147     479    9309
   6940   17029  150917

$  xargs --show-limits </dev/null
Your environment variables take up 121160 bytes
POSIX upper limit on argument length (this system): 1973944
POSIX smallest allowable upper limit on argument length (all systems): 4096
Maximum length of command we could actually use: 1852784
Size of command buffer we are actually using: 131072

Perhaps the output of the export command gives a good look at the ratio between exported variables and functions, but it isn't reflective of the actual space used (9309 + 150917 != 121160).

And that kind of makes sense. Here is the output of one random function in my environment, via export -f:

usage_init ()
{
    USAGE_OPT_P1="-p pathvar - The envvar to process. Default is";
    USAGE_OPT_P2="             PATH, if -p is not specified.";
    USAGE_OPT_P3="             The '-p' is optional, in which case";
    USAGE_OPT_P4F="             the first ARGUMENT is assumed to be";
    USAGE_OPT_P4O="             the ARGUMENT is assumed to be";
    USAGE_OPT_P5="             the pathvar.";
    USAGE_OPT_S="-s sep - Path element separator. Defaults to ':'.";
    USAGE_OPT_X="-x - Exports 'pathvar'.";
    USAGE_OPT_V="-v - Executes function 'listpath' after assignment.";
    USAGE_OPT_H="-h - Gives usage message.";
    USAGE_OPT_E="-e - 'pathspec' is interpreted as an egrep regexp.";
    USAGE_OPT_N="-n - Add index numbers to the results."
}
declare -fx usage_init

Here is the same function plucked out of env

BASH_FUNC_usage_init%%=() {  USAGE_OPT_P1="-p pathvar - The envvar to process. Default is";
 USAGE_OPT_P2="             PATH, if -p is not specified.";
 USAGE_OPT_P3="             The '-p' is optional, in which case";
 USAGE_OPT_P4F="             the first ARGUMENT is assumed to be";
 USAGE_OPT_P4O="             the ARGUMENT is assumed to be";
 USAGE_OPT_P5="             the pathvar.";
 USAGE_OPT_S="-s sep - Path element separator. Defaults to ':'.";
 USAGE_OPT_X="-x - Exports 'pathvar'.";
 USAGE_OPT_V="-v - Executes function 'listpath' after assignment.";
 USAGE_OPT_H="-h - Gives usage message.";
 USAGE_OPT_E="-e - 'pathspec' is interpreted as an egrep regexp.";
 USAGE_OPT_N="-n - Add index numbers to the results."
}

export (and I think type) appear to do some prettying for presentation which inflates the wc -c value.


问:
Visual Studio installer does not launch
I've downloaded Visual Studio Community 2017 so I can program in Unity 5 and I tried to install it. When I launch it something loads and then nothing happens after that. I've looked at the task manager but the installer was not launched.

I've formatted my PC 3 days ago, I was using the same thins as now. Windows 10 on the same PC. The only change is that I only have 1 Partition now on the Disk.
I was already using Visuals Studio with Unity 5 and it worked perfectly.

Can somebody help me?
Thanks.
I'm sorry if I speak bad English, I'm from Germany.

答:
Try checking if you have enough space.
Check if you have the required to run it.
And then launch as an administrator.</p>

Title: Visual Studio installer does not launch


问:
Flow control in JavaScript
Is it possible to write this flow control in JavaScript?</p>

```<code>MyLib.get = function() { /* do something */ next(); };
MyLib.save = function() { /* do something */ next(); };
MyLib.alert = function() { /* do something */ next(); };

MyLib.flow([
  MyLib.get(),
  MyLib.save(),
  MyLib.alert()
], function() {
  // all functions were executed
});
</code>```

答:
This looks like continuation-passing style. However, normally in that style, each function takes a next function as an argument, like this:

```<code>MyLib.get = function(next) { /* do something */ next(); };
MyLib.save = function(next) { /* do something */ next(); };
MyLib.alert = function(next) { /* do something */ next(); };
</code>```

and as Pointy notes, you would normally pass the functions themselves, without having already called them:

```<code>MyLib.flow([
  MyLib.get,
  MyLib.save,
  MyLib.alert
], function() {
  // all functions were executed
});
</code>```

With those changes, the code below might work.

Now, it's by no means obvious to the uninitiated exactly how continuation-passing style works just by looking at the code. I don't think I can make it clear in a single answer. But I'll try.

In this style, even a do-nothing function would not be totally empty, but would have to call next:

```<code>MyLib.do_nothing = function(next) { /* don't do something */ next(); };
</code>```

One important building block is the ability to take two functions written in this style and chain them together:

```<code>// This function takes two CPS functions, f1 and f2, as arguments.
// It returns a single CPS function that calls f1, then f2, then next().
MyLib._compose2 = function (f1, f2) {
    return function(next) {
        return f1(function () { return f2(next); });
    };
};
</code>```

This is the hardest bit to understand, I think.

Once you have that, you can use it to glue together any number of functions:

```<code>MyLib._composeAll = function (arr) {       // Easy!
    var result = do_nothing;               // Start with the "empty" function,
    for (var i = 0; i < arr.length; i++)   // and one by one,
        result = MyLib._compose2(result, arr[i]);  // add each element of arr.
    return result;
};
</code>```

And once you have that, flow is not too hard to write:

```<code>MyLib.flow = function(items, next) {
    var f = MyLib._composeAll(items);
    f(next);
};
</code>```

Fixing all the bugs in that code is left as an exercise. ;)

Title: Flow control in JavaScript

Body:
Is it possible to write this flow control in JavaScript?

MyLib.get = function() { /* do something */ next(); };
MyLib.save = function() { /* do something */ next(); };
MyLib.alert = function() { /* do something */ next(); };

MyLib.flow([
  MyLib.get(),
  MyLib.save(),
  MyLib.alert()
], function() {
  // all functions were executed
});

Body:
This looks like continuation-passing style. However, normally in that style, each function takes a next function as an argument, like this:

MyLib.get = function(next) { /* do something */ next(); };
MyLib.save = function(next) { /* do something */ next(); };
MyLib.alert = function(next) { /* do something */ next(); };

and as Pointy notes, you would normally pass the functions themselves, without having already called them:

MyLib.flow([
  MyLib.get,
  MyLib.save,
  MyLib.alert
], function() {
  // all functions were executed
});

With those changes, the code below might work.

Now, it's by no means obvious to the uninitiated exactly how continuation-passing style works just by looking at the code. I don't think I can make it clear in a single answer. But I'll try.

In this style, even a do-nothing function would not be totally empty, but would have to call next:

MyLib.do_nothing = function(next) { /* don't do something */ next(); };

One important building block is the ability to take two functions written in this style and chain them together:

// This function takes two CPS functions, f1 and f2, as arguments.
// It returns a single CPS function that calls f1, then f2, then next().
MyLib._compose2 = function (f1, f2) {
    return function(next) {
        return f1(function () { return f2(next); });
    };
};

This is the hardest bit to understand, I think.

Once you have that, you can use it to glue together any number of functions:

MyLib._composeAll = function (arr) {       // Easy!
    var result = do_nothing;               // Start with the "empty" function,
    for (var i = 0; i < arr.length; i++)   // and one by one,
        result = MyLib._compose2(result, arr[i]);  // add each element of arr.
    return result;
};

And once you have that, flow is not too hard to write:

MyLib.flow = function(items, next) {
    var f = MyLib._composeAll(items);
    f(next);
};

Fixing all the bugs in that code is left as an exercise. ;)