问:
Subsetting a dataset into multiples subsets in R
I have a data that looks something like this:

```<code>structure(list(ID = structure(c(1L, 2L, 2L, 3L, 4L, 5L, 6L, 6L,
6L), .Label = c("a", "b", "c", "d", "e", "f"), class = "factor"),
    Value = c(10L, 13L, 12L, 43L, 23L, 66L, 78L, 42L, 19L)), .Names = c("ID",
"Value"), class = "data.frame", row.names = c(NA, -9L))
</code>```

I would like to divide this dataset into multiple datasets on the basis of the ID values, i.e. one dataset that contains only ID = a, another that contains only ID = b, and so on.

How do I do this subsetting automatically in R? I understand that if the number of values in ID is less, we could just do it manually, but in case there are a lot of values under ID, there has to be a smarter way of doing this.

答:
You can use the split function.

```<code>df <- structure(list(ID = structure(c(1L, 2L, 2L, 3L, 4L, 5L, 6L, 6L,
6L), .Label = c("a", "b", "c", "d", "e", "f"), class = "factor"),
    Value = c(10L, 13L, 12L, 43L, 23L, 66L, 78L, 42L, 19L)), .Names = c("ID",
"Value"), class = "data.frame", row.names = c(NA, -9L))

> df
  ID Value
1  a    10
2  b    13
3  b    12
4  c    43
5  d    23
6  e    66
7  f    78
8  f    42
9  f    19

listed_df <- split(df, df$ID)

> listed_df
$a
  ID Value
1  a    10

$b
  ID Value
2  b    13
3  b    12

$c
  ID Value
4  c    43

$d
  ID Value
5  d    23

$e
  ID Value
6  e    66

$f
  ID Value
7  f    78
8  f    42
9  f    19
</code>```

To call on one of these just use index it with $.

```<code>sum(listed_df$f$Value)
</code>```

You can also lapply a function across each of the dataframes within the list. If you wanted to sum up each Value or something you could do..

```<code>lapply(df_list, function(x) sum(x$Value))
</code>```

You can also do this just by grouping the original dataframe by ID and then perform summarise operations on it from there.

Body:
I have a data that looks something like this:

structure(list(ID = structure(c(1L, 2L, 2L, 3L, 4L, 5L, 6L, 6L,
6L), .Label = c("a", "b", "c", "d", "e", "f"), class = "factor"),
    Value = c(10L, 13L, 12L, 43L, 23L, 66L, 78L, 42L, 19L)), .Names = c("ID",
"Value"), class = "data.frame", row.names = c(NA, -9L))

I would like to divide this dataset into multiple datasets on the basis of the ID values, i.e. one dataset that contains only ID = a, another that contains only ID = b, and so on.

How do I do this subsetting automatically in R? I understand that if the number of values in ID is less, we could just do it manually, but in case there are a lot of values under ID, there has to be a smarter way of doing this.

Body:
You can use the split function.

df <- structure(list(ID = structure(c(1L, 2L, 2L, 3L, 4L, 5L, 6L, 6L,
6L), .Label = c("a", "b", "c", "d", "e", "f"), class = "factor"),
    Value = c(10L, 13L, 12L, 43L, 23L, 66L, 78L, 42L, 19L)), .Names = c("ID",
"Value"), class = "data.frame", row.names = c(NA, -9L))

> df
  ID Value
1  a    10
2  b    13
3  b    12
4  c    43
5  d    23
6  e    66
7  f    78
8  f    42
9  f    19

listed_df <- split(df, df$ID)

> listed_df
$a
  ID Value
1  a    10

$b
  ID Value
2  b    13
3  b    12

$c
  ID Value
4  c    43

$d
  ID Value
5  d    23

$e
  ID Value
6  e    66

$f
  ID Value
7  f    78
8  f    42
9  f    19

To call on one of these just use index it with $.

sum(listed_df$f$Value)

You can also lapply a function across each of the dataframes within the list. If you wanted to sum up each Value or something you could do..

lapply(df_list, function(x) sum(x$Value))

You can also do this just by grouping the original dataframe by ID and then perform summarise operations on it from there.


来源: stackexchange

问:
Request.Headers["Referer"] does not exist
I have a solution with two ASP.NET Core MVC projects. One project (Client) is making a request to the other (Server) using HttpClient. When the action in Server receives the request, I want to get the URL of the thing that sent it. Every article I have read purports Request.Headers["Referer"] as the solution, but in my case Headers does not contain a "referer" key (or "referrer").

When receiving the request in Server, how should I find the URL of the Client that sent it?

答:
If you're using HttpClient, then it is up to the site making the request to add that header. It isn't added automatically in this case. So: change the code - or request that the code is changed - so as to add the header and value that you expect. If you are proxying through a request, you might get the value from the current request's Referer header, and add that.

Even in the general case of a browser making the request as part of a normal page cycle, you can't rely on it: the Referer header is often deliberately not sent; depending on the browser version, configuration, whether you're going between different domains, whether it is HTTPS or not,  and rel markers on a href=... such as "noreferrer".

ContentLicense: CC BY-SA 3.0

Body:
If you're using HttpClient, then it is up to the site making the request to add that header. It isn't added automatically in this case. So: change the code - or request that the code is changed - so as to add the header and value that you expect. If you are proxying through a request, you might get the value from the current request's Referer header, and add that.

Even in the general case of a browser making the request as part of a normal page cycle, you can't rely on it: the Referer header is often deliberately not sent; depending on the browser version, configuration, whether you're going between different domains, whether it is HTTPS or not,  and rel markers on a <a href=... such as "noreferrer".


问:
Can somebody explain and solve my Value Error when reading in from a text file
For some reason my code(following) has brought up a Value Error which I cannot understand. Please evaluate my code too. You can find the project I am trying to do at
http://www.ocr.org.uk/Images/226767-unit-j276-03-programming-project-task-1-sample-non-exam-assessment.pdf

```<code>fileid = "details for nea.txt"
ID = []
surname = []
forename = []
dob = []
addr = []
addrT = []
addrTh = []
addrF = []
addrFi = []
homNum = []
gend = []
tutor = []
schoolEm = []

def Read():
    file = open(fileid, "r")
    Record = file.readline()
    for line in Record:
        line = line.strip()
        A,B,C,D,E,F,G,H,I,J,K,L,M = line.split(',')
        ID.append(A)
        surname.append(B)
        forename.append(C)
        dob.append(D)
        addr.append(E)
        addrT.append(F)
        addrTh.append(G)
        addrF.append(H)
        addrFi.append(I)
        homNum.append(J)
        gend.append(K)
        tutor.append(L)
        schoolEm.append(M)
    file.close()

def Save():
    Record = []
    file = open(fileid,"w")
    for i in range(len(ID)):
        Record.append(ID[i] +","+surname[i]+","+forename[i]+","+dob[i]+","+addr[i]+","+addrT[i]+","+addrTh[i]+","+addrF[i]+","+addrFi[i]+","+homNum[i]+","+gend[i]+","+tutor[i]+","+schoolEm[i]+"\n")
    file.writelines(Record)
    file.close()
Read()
print(ID)
print(surname)
</code>```

The Text File I used goes as following:

```<code>  01,abe,fat,01/02/02,5,Stoney Lane,Stur,Dorset,DR101LM,0123,M,C,email@sc. The lists titled addr, addrT represent the different lines of address.
</code>```

答: put last three lines inside main. Value error should go away

Body:
For some reason my code(following) has brought up a Value Error which I cannot understand. Please evaluate my code too. You can find the project I am trying to do at
http://www.ocr.org.uk/Images/226767-unit-j276-03-programming-project-task-1-sample-non-exam-assessment.pdf

fileid = "details for nea.txt"
ID = []
surname = []
forename = []
dob = []
addr = []
addrT = []
addrTh = []
addrF = []
addrFi = []
homNum = []
gend = []
tutor = []
schoolEm = []

def Read():
    file = open(fileid, "r")
    Record = file.readline()
    for line in Record:
        line = line.strip()
        A,B,C,D,E,F,G,H,I,J,K,L,M = line.split(',')
        ID.append(A)
        surname.append(B)
        forename.append(C)
        dob.append(D)
        addr.append(E)
        addrT.append(F)
        addrTh.append(G)
        addrF.append(H)
        addrFi.append(I)
        homNum.append(J)
        gend.append(K)
        tutor.append(L)
        schoolEm.append(M)
    file.close()

def Save():
    Record = []
    file = open(fileid,"w")
    for i in range(len(ID)):
        Record.append(ID[i] +","+surname[i]+","+forename[i]+","+dob[i]+","+addr[i]+","+addrT[i]+","+addrTh[i]+","+addrF[i]+","+addrFi[i]+","+homNum[i]+","+gend[i]+","+tutor[i]+","+schoolEm[i]+"\n")
    file.writelines(Record)
    file.close()
Read()
print(ID)
print(surname)

The Text File I used goes as following:

  01,abe,fat,01/02/02,5,Stoney Lane,Stur,Dorset,DR101LM,0123,M,C,email@sc. The lists titled addr, addrT represent the different lines of address.


问:
column "scopes" does not exist when using Loopback 3.8.0
I hit a weird problem where it said column "scopes" does not exist.  Here is the log I encountered in server but not in local enviroment:

```<code>Unhandled error for request GET /api/continents?access_token=aaaaaaaaaaabbbbbbbbbbbbbbbbL1AwzSoH8eHXwPdjzQATRXqto3lngEokVxR2j: error: column "scopes" does not exist
2017-05-05T04:35:06.642201+00:00 app[web.1]:     at Connection.parseE (/app/node_modules/pg/lib/connection.js:569:11)
2017-05-05T04:35:06.642202+00:00 app[web.1]:     at Connection.parseMessage (/app/node_modules/pg/lib/connection.js:396:17)
2017-05-05T04:35:06.642203+00:00 app[web.1]:     at TLSSocket.<anonymous> (/app/node_modules/pg/lib/connection.js:132:22)
2017-05-05T04:35:06.642204+00:00 app[web.1]:     at emitOne (events.js:96:13)
2017-05-05T04:35:06.642209+00:00 app[web.1]:     at TLSSocket.emit (events.js:188:7)
2017-05-05T04:35:06.642210+00:00 app[web.1]:     at readableAddChunk (_stream_readable.js:176:18)
2017-05-05T04:35:06.642210+00:00 app[web.1]:     at TLSSocket.Readable.push (_stream_readable.js:134:10)
2017-05-05T04:35:06.642211+00:00 app[web.1]:     at TLSWrap.onread (net.js:547:20)
</code>```

All APIs involving access token failed for same reason.  If access token is not set, the APIs work as expected (if public, I got data; if authentication required, I got 401/403).

I tried local - it works, I tried heroku local - it works too.  After a long testing, I found that the differences (and verified) is both my local and heroku local are running loopback version 3.4.0 while my servers are running 3.8.0.

After I enforce the server to use 3.4.0, it is normal.

Digging into /node_modules/loopback/common/models/access-token.json, here are the differences between 3.4.0 and 3.8.0:

Loopback 3.4.0:

```<code>"name": "AccessToken",
"properties": {
  "id": { "type": "string", "id": true },
  "ttl": { "type": "number", "ttl": true, "default": 1209600, "description": "time to live in seconds (2 weeks by default)" },
  "created": { "type": "Date", "defaultFn": "now" }
},
</code>```

Loopback 3.8.0:

```<code>"name": "AccessToken",
"properties": {
  "id": { "type": "string", "id": true },
  "ttl": { "type": "number", "ttl": true, "default": 1209600, "description": "time to live in seconds (2 weeks by default)" },
  "scopes": {
    "type": ["string"],
    "description": "Array of scopes granted to this access token."
  },
  "created": { "type": "Date", "defaultFn": "now" }
},
</code>```

Since I didn't checkin the node_modules, does anyone know how can I fix the issue?

答:
I faced the same trouble moving from lb2.x to lb3.17.0

just did an alter table :
ALTER TABLE accesstoken ADD scopes TEXT;

Body:
I hit a weird problem where it said column "scopes" does not exist.  Here is the log I encountered in server but not in local enviroment:

Unhandled error for request GET /api/continents?access_token=aaaaaaaaaaabbbbbbbbbbbbbbbbL1AwzSoH8eHXwPdjzQATRXqto3lngEokVxR2j: error: column "scopes" does not exist
2017-05-05T04:35:06.642201+00:00 app[web.1]:     at Connection.parseE (/app/node_modules/pg/lib/connection.js:569:11)
2017-05-05T04:35:06.642202+00:00 app[web.1]:     at Connection.parseMessage (/app/node_modules/pg/lib/connection.js:396:17)
2017-05-05T04:35:06.642203+00:00 app[web.1]:     at TLSSocket.<anonymous> (/app/node_modules/pg/lib/connection.js:132:22)
2017-05-05T04:35:06.642204+00:00 app[web.1]:     at emitOne (events.js:96:13)
2017-05-05T04:35:06.642209+00:00 app[web.1]:     at TLSSocket.emit (events.js:188:7)
2017-05-05T04:35:06.642210+00:00 app[web.1]:     at readableAddChunk (_stream_readable.js:176:18)
2017-05-05T04:35:06.642210+00:00 app[web.1]:     at TLSSocket.Readable.push (_stream_readable.js:134:10)
2017-05-05T04:35:06.642211+00:00 app[web.1]:     at TLSWrap.onread (net.js:547:20)

All APIs involving access token failed for same reason.  If access token is not set, the APIs work as expected (if public, I got data; if authentication required, I got 401/403).

I tried local - it works, I tried heroku local - it works too.  After a long testing, I found that the differences (and verified) is both my local and heroku local are running loopback version 3.4.0 while my servers are running 3.8.0.

After I enforce the server to use 3.4.0, it is normal.

Digging into /node_modules/loopback/common/models/access-token.json, here are the differences between 3.4.0 and 3.8.0:

Loopback 3.4.0:

"name": "AccessToken",
"properties": {
  "id": { "type": "string", "id": true },
  "ttl": { "type": "number", "ttl": true, "default": 1209600, "description": "time to live in seconds (2 weeks by default)" },
  "created": { "type": "Date", "defaultFn": "now" }
},

Loopback 3.8.0:

"name": "AccessToken",
"properties": {
  "id": { "type": "string", "id": true },
  "ttl": { "type": "number", "ttl": true, "default": 1209600, "description": "time to live in seconds (2 weeks by default)" },
  "scopes": {
    "type": ["string"],
    "description": "Array of scopes granted to this access token."
  },
  "created": { "type": "Date", "defaultFn": "now" }
},

Since I didn't checkin the node_modules, does anyone know how can I fix the issue?


问:
How to send push notification on button click
I've create push notification for my android app, it's work when I try to send it from firebase console. Now what I want is make a push notification when user click on register then show the notification for other users.

I've search in google but didn't find one of the example. The goals is to notif other user that there are new user register in my app.

Thanks for help

```<code>public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMessagingService";
    public static final int ID_SMALL_NOTIFICATION = 235;
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // ...

        // TODO(developer): Handle FCM messages here.

        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            sendNotification("Hi ini isinya");
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG,"Message Notification Title" + remoteMessage.getNotification().getTitle());
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
    }

    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, ID_SMALL_NOTIFICATION, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String channelId = "fcm_default_channel";
        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.icon)
                        .setContentTitle("FCM Message")
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(ID_SMALL_NOTIFICATION, notificationBuilder.build());
    }

}
</code>```

答:
You want to send a push when one user clicks to register to everyone else who have already registered, right?.
You need to make a HTTP POST request to this address:

```<code>https://fcm.googleapis.com/fcm/send
</code>```

With a header called "Authorization" with value like this "key=AIza...".

So in the body of the request you send a JSON like this.

```<code>{
  "to": "/topics/foo-bar",
  "data": {
    "message": "This is a Firebase Cloud Messaging Topic Message!",
   }
}
</code>```

And then you need to create a topic and subscribe the device to the same topic.

```<code>FirebaseMessaging.getInstance().subscribeToTopic("foo-bar");
</code>```

That should work just fine.

Body:
I've create push notification for my android app, it's work when I try to send it from firebase console. Now what I want is make a push notification when user click on register then show the notification for other users.

I've search in google but didn't find one of the example. The goals is to notif other user that there are new user register in my app.

Thanks for help

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMessagingService";
    public static final int ID_SMALL_NOTIFICATION = 235;
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // ...

        // TODO(developer): Handle FCM messages here.

        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            sendNotification("Hi ini isinya");
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG,"Message Notification Title" + remoteMessage.getNotification().getTitle());
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
    }

    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, ID_SMALL_NOTIFICATION, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String channelId = "fcm_default_channel";
        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.icon)
                        .setContentTitle("FCM Message")
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(ID_SMALL_NOTIFICATION, notificationBuilder.build());
    }

}

Body:
You want to send a push when one user clicks to register to everyone else who have already registered, right?.
You need to make a HTTP POST request to this address:

https://fcm.googleapis.com/fcm/send

With a header called "Authorization" with value like this "key=AIza...".

So in the body of the request you send a JSON like this.

{
  "to": "/topics/foo-bar",
  "data": {
    "message": "This is a Firebase Cloud Messaging Topic Message!",
   }
}

And then you need to create a topic and subscribe the device to the same topic.

FirebaseMessaging.getInstance().subscribeToTopic("foo-bar");

That should work just fine.


问:
Python - Windows - Exiting Child Process when "unrelated" parent dies/crashes
After some research there was no definitive answer as to how to have a child process understand that the parent process has died/crashed/exited under Windows which can make the child process run unattended. There are some proposals as in:

Jobs: Python: how to kill child process(es) when parent dies?

Psutil: subprocess: deleting child processes in Windows

Multiprocessing: Kill Child Process if Parent is killed in Python

Always involving a known parent which has started a child. But there are cases in which the child doesn't know it is a child, because it is not conceived as a child and the parent makes no effort to kill the children.

Furthermore, there is no control of the parent. Practical case:

Cygwin running under Windows

Windows Python 1st in the path

Python executable installed via setuptools entry_points facility.

As mentioned above the Python to be executed is the Windows one. The setuptools-generated executable will find it and execute it as subprocess with the asocciated script.

Because one is running under Cygwin the following may fail:

Pressing Ctrl-c will kill the parent (the stub setuptools executable)

But will leave the child running (to be found in the process list as python.exe)

In this case and as mentioned above, it isn't possible to control the parent and the child doesn't know it's a child (because it may also be directly executed as a Python script)

答:
The solution is to do as follows

```<code>import sys

def win_wait_for_parent(raise_exceptions=False):
    if not sys.platform == 'win32':
        return True

    # When started under cygwin, the parent process will die leaving a child
    # hanging around. The process has to be waited upon
    import ctypes
    from ctypes.wintypes import DWORD, BOOL, HANDLE
    import os
    import threading

    INFINITE = -1
    SYNCHRONIZE = 0x00100000

    kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

    kernel32.OpenProcess.argtypes = (DWORD, BOOL, DWORD)
    kernel32.OpenProcess.restype = HANDLE

    kernel32.WaitForSingleObject.argtypes = (HANDLE, DWORD)
    kernel32.WaitForSingleObject.restype = DWORD

    phandle = kernel32.OpenProcess(SYNCHRONIZE, 0, os.getppid())

    def check_parent():
        # Get a token with right access to parent and wait for it to be
        # signaled (die). Exit ourselves then
            kernel32.WaitForSingleObject(phandle, INFINITE)
            os._exit(0)

    if not phandle:
        if raise_exceptions:
            raise ctypes.WinError(ctypes.get_last_error())

        return False

    threading.Thread(target=check_parent).start()
    return True
</code>```

which runs in a separate thread if the PID of the process is not the same as the PID of the parent waiting for the parent to be signaled (death). This works under Python 3.3, where os.getppid() does actually returnt the PID of the parent under window

It requires no modification of the parent and the child doesn't need to be coded in advance as a child, because a check is done as to where the thread has to run or no.

-- refactored as a function and added improvements from comments

Body:
The solution is to do as follows

import sys

def win_wait_for_parent(raise_exceptions=False):
    if not sys.platform == 'win32':
        return True

    # When started under cygwin, the parent process will die leaving a child
    # hanging around. The process has to be waited upon
    import ctypes
    from ctypes.wintypes import DWORD, BOOL, HANDLE
    import os
    import threading

    INFINITE = -1
    SYNCHRONIZE = 0x00100000

    kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

    kernel32.OpenProcess.argtypes = (DWORD, BOOL, DWORD)
    kernel32.OpenProcess.restype = HANDLE

    kernel32.WaitForSingleObject.argtypes = (HANDLE, DWORD)
    kernel32.WaitForSingleObject.restype = DWORD

    phandle = kernel32.OpenProcess(SYNCHRONIZE, 0, os.getppid())

    def check_parent():
        # Get a token with right access to parent and wait for it to be
        # signaled (die). Exit ourselves then
            kernel32.WaitForSingleObject(phandle, INFINITE)
            os._exit(0)

    if not phandle:
        if raise_exceptions:
            raise ctypes.WinError(ctypes.get_last_error())

        return False

    threading.Thread(target=check_parent).start()
    return True

which runs in a separate thread if the PID of the process is not the same as the PID of the parent waiting for the parent to be signaled (death). This works under Python 3.3, where os.getppid() does actually returnt the PID of the parent under window

It requires no modification of the parent and the child doesn't need to be coded in advance as a child, because a check is done as to where the thread has to run or no.

-- refactored as a function and added improvements from comments


问:
Bluetooth Beginner, Need Advice
So I'm hopelessly lost  right now. I found an attractive bluetooth chip from Nordic Semiconductor (the NRF52840) that I want to use for a couple project ideas I have. Now I have an HC-05 module for my arduino, so I'm not entirely lost on programming a bluetooth module perse, but I really need advice on how I can make my own. I want to make a bluetooth module that works exactly like the HC-05 but on a much smaller scale. I'm talking fitbit small. I'm not making a smartwatch or fitbit, but that's relatively the size I would need it to be.

So bottom line to whoever got lost in that mumbling explanation of my hopelessness, I need some advice on how to develop my own Bluetooth module PCB. The onboard chip will be the aforementioned NRF52480. Thank you to anybody who helps!!

答:
Given that you are endeavoring in a very complex task, I would recommend you to start from the reference designs provided by the chip manufacturer. They are very valuable, especially when dealing with RF.

See here and here, for example. About RF design, this talk may be interesting for you as well.

Title: Bluetooth Beginner, Need Advice


问:
Move MongoDB data from Staging server to Production
I have 500,000 documents inside a collection on a staging server, I need to move these documents to the production server.

What is the best way to move this data, can I let mongodb replicate it from staging to production, do I move the data files or do I do an export and re-import?

答:
you can also run a db.copyDatabase command from the console or in your app.

http://docs.mongodb.org/manual/tutorial/copy-databases-between-instances/


问:
Clang ambiguity with custom conversion operator
I've been developing a kind of adapter class, when I encountered a problem under clang. When both conversion operators for lvalue-reference and rvalue reference are defined you get an ambiguity compilation error trying to move from your class (when such code should be fine, as

```<code>operator const T& () const&
</code>```

is allowed only for lvalues AFAIK). I've reproduced error with simple example:

```<code>#include <string>

class StringDecorator
{
public:
  StringDecorator()
  : m_string( "String data here" )
  {}

  operator const std::string& () const& // lvalue only
  {
    return m_string;
  }

  operator std::string&& () && // rvalue only
  {
    return std::move( m_string );
  }

private:
    std::string m_string;
};

void func( const std::string& ) {}
void func( std::string&& ) {}

int main(int argc, char** argv)
{
  StringDecorator my_string;

  func( my_string ); // fine, operator std::string&& not allowed
  func( std::move( my_string ) ); // error "ambiguous function call"
}
</code>```

Compiles fine on gcc 4.9+, fails on any clang version.
So the question: is there any workaround? Is my understanding of const& function modifier right?

P.S.: To clarify - the question is about fixing StringDecorator class itself (or finding the workaround for such class as if were a library code). Please refrain providing answers that call operator T&&() directly or specify conversion type explicitly.

答:
clang++ is more accurate. Both func overloads are not exact matches for StringDecorator const& or StringDecorator&&. Thus my_string can not be moved. The compiler can not choose between possible transforms StringDecorator&& --> std::string&& --> func(std::string&&) and StringDecorator&& -> StringDecorator& --> std::string& --> func(const std::string&). In other words the compiler can not determine on what step it should apply cast operator.

I do not have g++ installed to check my assumption. I guess it goes to the second way, since my_string can not be moved, it applies the cast operator const& to StringDecorator&. You can check it if you add debug output into bodies of cast operators.

Body:
I've been developing a kind of adapter class, when I encountered a problem under clang. When both conversion operators for lvalue-reference and rvalue reference are defined you get an ambiguity compilation error trying to move from your class (when such code should be fine, as

operator const T& () const&

is allowed only for lvalues AFAIK). I've reproduced error with simple example:

#include <string>

class StringDecorator
{
public:
  StringDecorator()
  : m_string( "String data here" )
  {}

  operator const std::string& () const& // lvalue only
  {
    return m_string;
  }

  operator std::string&& () && // rvalue only
  {
    return std::move( m_string );
  }

private:
    std::string m_string;
};

void func( const std::string& ) {}
void func( std::string&& ) {}

int main(int argc, char** argv)
{
  StringDecorator my_string;

  func( my_string ); // fine, operator std::string&& not allowed
  func( std::move( my_string ) ); // error "ambiguous function call"
}

Compiles fine on gcc 4.9+, fails on any clang version.
So the question: is there any workaround? Is my understanding of const& function modifier right?

P.S.: To clarify - the question is about fixing StringDecorator class itself (or finding the workaround for such class as if were a library code). Please refrain providing answers that call operator T&&() directly or specify conversion type explicitly.


问:
Converting PHP array to a single JSON object using js
I have a php array(zero indexed) which I am sending to front end directly by echoing its json_encode format.

I want the JSON object to look like

```<code>{
    'A': null,
    'B': null,
    'C': null
}
</code>```

But when I tried console.log i.e.,

```<code>console.log(<?php echo json_encode($array); ?>)
</code>```

its printing js array

Also when I try print_r($array) in backend it prints

```<code>[array] => Array
    (
        [0] => A
        [1] => B
        [2] => C

    )
</code>```

Thanks in advance

答:
Why not just make your PHP array an array of ['A' => null, 'B' => null...]

Otherwise, your other option would be:

```<code>   $newArray = array_fill_keys($tags, null);
   json_encode($newArray);
</code>```

This would take each array element in $tags, and set it as your index in newArray with a value of null.

Based on your code, you would have:

```<code><?php $newArray = array_fill_keys($tags, null);
$json = json_encode($newArray); ?>
console.log(JSON.parse(<?= $json; ?>));
</code>```

Body:
I have a php array(zero indexed) which I am sending to front end directly by echoing its json_encode format.

I want the JSON object to look like

{
    'A': null,
    'B': null,
    'C': null
}

But when I tried console.log i.e.,

console.log(<?php echo json_encode($array); ?>)

its printing js array

Also when I try print_r($array) in backend it prints

[array] => Array
    (
        [0] => A
        [1] => B
        [2] => C

    )

Thanks in advance

Body:
Why not just make your PHP array an array of ['A' => null, 'B' => null...]

Otherwise, your other option would be:

   $newArray = array_fill_keys($tags, null);
   json_encode($newArray);

This would take each array element in $tags, and set it as your index in newArray with a value of null.

Based on your code, you would have:

<?php $newArray = array_fill_keys($tags, null);
$json = json_encode($newArray); ?>
console.log(JSON.parse(<?= $json; ?>));


答:
This is not tested, but may give you an idea. Join to all rows for the product in the last 7 days. Count the distinct prices. If the count is 1, then the price has not changed.</p>

```<code>SELECT p1.prodId, p1.priceDate, MAX(p1.price) AS price,
  CASE COUNT(DISTINCT p2.price) WHEN 1 THEN 'N' ELSE 'Y' END AS chg
FROM MyTable AS p1
LEFT OUTER JOIN MyTable AS p2
 ON p1.prodId = p2.prodId
 AND p2.priceDate BETWEEN p1.priceDate - INTERVAL 7 DAY AND p1.priceDate
GROUP BY p1.prodId, p1.priceDate
</code>```

Title: MySQL: price changed within last 7 days

Body:
I have the following data (products with its prices and dates of price):

prodId priceDate  price
======+==========+=====
    1 |2017-11-24|  600
    1 |2017-11-21|  600
    1 |2017-11-18|  600
    1 |2017-11-15|  500
    1 |2017-11-05|  400
    1 |2017-11-03|  400
    2 |2017-11-11|  300

I need an indicator (column chg) which will show if product price had been changed within previous 7 days.

prodId priceDate  price chg
======+==========+=====+===
    1 |2017-11-24|  600| N
    1 |2017-11-21|  600| Y
    1 |2017-11-18|  600| Y
    1 |2017-11-15|  500| N
    1 |2017-11-05|  400| N
    1 |2017-11-03|  400| N
    2 |2017-11-14|  300| N

How this SQL query should look like?

Body:
This is not tested, but may give you an idea. Join to all rows for the product in the last 7 days. Count the distinct prices. If the count is 1, then the price has not changed.

SELECT p1.prodId, p1.priceDate, MAX(p1.price) AS price,
  CASE COUNT(DISTINCT p2.price) WHEN 1 THEN 'N' ELSE 'Y' END AS chg
FROM MyTable AS p1
LEFT OUTER JOIN MyTable AS p2
 ON p1.prodId = p2.prodId
 AND p2.priceDate BETWEEN p1.priceDate - INTERVAL 7 DAY AND p1.priceDate
GROUP BY p1.prodId, p1.priceDate


问:
What image gallery? [iPhone]

Hey guys,
checkout this. How can I do something similar? I mean a scrollview with 9x9 images.
Also, how can I put a custom loading image??

Ty.

答:
Allocate and init a UIScrollView, add it to the viewcontroller's view, and then create UIImageViews, set their respective images, and add the image views to the scroll view.

Specifying launch images - get a pic, rename it to Default.png (also might want to get a 2x sized one - call it Default@2x.png) and copy it to the resources folder.

ContentLicense: CC BY-SA 2.5

Title: What image gallery? [iPhone]


问:
Count unique ids in a rolling time frame
I have a simple table as bellow with lots of IDs and dates.

```<code>ID      Date
10R46   2014-11-23
10R46   2016-04-11
100R9   2016-12-21
10R91   2013-05-03
...     ...
</code>```

I want to formulate a  query which counts the unique IDs for a rolling time frame of dates, for example ten days. Meaning that for each date it should give me the number of unique IDs between that date and 10 days back. Result should look something like this.

```<code>UniqueTenDays    Date
200              2014-11-23
324              2014-11-24
522              2014-11-25
532              2014-11-26
...              ...
</code>```

Something along the lines of the bellow but I realise I need to apply the WHERE clause and count the IDs for each Date somehow.

```<code>SELECT Date, COUNT(DISTINCT ID)
FROM T
WHERE Date BETWEEN DATE_SUB(Date, INTERVAL 10 DAY) AND Date
GROUP BY Date
ORDER BY Date
</code>```

Thanks in advance.

答:
Below is for BigQuery Standard SQL   </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
WITH temp1 AS (
  SELECT dt, STRING_AGG(DISTINCT id) AS users
  FROM `project.dataset.yourtable`
  GROUP BY dt
), temp2 AS (
  SELECT
    dt,
    STRING_AGG(users) OVER(ORDER BY UNIX_DATE(dt) RANGE BETWEEN 10 PRECEDING AND CURRENT ROW) users
  FROM temp1
)
SELECT dt,
  (SELECT COUNT(DISTINCT id) FROM UNNEST(SPLIT(users)) AS id) UniqueTenDays
FROM temp2
</code>```

<p>you can test / play with it using dummy data as below   </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
WITH `project.dataset.yourtable` AS (
  SELECT '10R46' id,  DATE '2014-11-23' dt UNION ALL
  SELECT '10R46',     DATE '2016-04-11' UNION ALL
  SELECT '10R46',     DATE '2016-04-12' UNION ALL
  SELECT '10R47',     DATE '2016-04-13' UNION ALL
  SELECT '10R48',     DATE '2016-04-14' UNION ALL
  SELECT '100R9',     DATE '2016-12-21' UNION ALL
  SELECT '10R91',     DATE '2013-05-03'
), temp1 AS (
  SELECT dt, STRING_AGG(DISTINCT id) AS users
  FROM `project.dataset.yourtable`
  GROUP BY dt
), temp2 AS (
  SELECT
    dt,
    STRING_AGG(users) OVER(ORDER BY UNIX_DATE(dt) RANGE BETWEEN 10 PRECEDING AND CURRENT ROW) users
  FROM temp1
)
SELECT dt,
  (SELECT COUNT(DISTINCT id) FROM UNNEST(SPLIT(users)) AS id) UniqueTenDays
FROM temp2
</code>```

Body:
I have a simple table as bellow with lots of IDs and dates.

ID      Date
10R46   2014-11-23
10R46   2016-04-11
100R9   2016-12-21
10R91   2013-05-03
...     ...

I want to formulate a  query which counts the unique IDs for a rolling time frame of dates, for example ten days. Meaning that for each date it should give me the number of unique IDs between that date and 10 days back. Result should look something like this.

UniqueTenDays    Date
200              2014-11-23
324              2014-11-24
522              2014-11-25
532              2014-11-26
...              ...

Something along the lines of the bellow but I realise I need to apply the WHERE clause and count the IDs for each Date somehow.

SELECT Date, COUNT(DISTINCT ID)
FROM T
WHERE Date BETWEEN DATE_SUB(Date, INTERVAL 10 DAY) AND Date
GROUP BY Date
ORDER BY Date

Thanks in advance.

Body:
Below is for BigQuery Standard SQL

#standardSQL
WITH temp1 AS (
  SELECT dt, STRING_AGG(DISTINCT id) AS users
  FROM `project.dataset.yourtable`
  GROUP BY dt
), temp2 AS (
  SELECT
    dt,
    STRING_AGG(users) OVER(ORDER BY UNIX_DATE(dt) RANGE BETWEEN 10 PRECEDING AND CURRENT ROW) users
  FROM temp1
)
SELECT dt,
  (SELECT COUNT(DISTINCT id) FROM UNNEST(SPLIT(users)) AS id) UniqueTenDays
FROM temp2

you can test / play with it using dummy data as below

#standardSQL
WITH `project.dataset.yourtable` AS (
  SELECT '10R46' id,  DATE '2014-11-23' dt UNION ALL
  SELECT '10R46',     DATE '2016-04-11' UNION ALL
  SELECT '10R46',     DATE '2016-04-12' UNION ALL
  SELECT '10R47',     DATE '2016-04-13' UNION ALL
  SELECT '10R48',     DATE '2016-04-14' UNION ALL
  SELECT '100R9',     DATE '2016-12-21' UNION ALL
  SELECT '10R91',     DATE '2013-05-03'
), temp1 AS (
  SELECT dt, STRING_AGG(DISTINCT id) AS users
  FROM `project.dataset.yourtable`
  GROUP BY dt
), temp2 AS (
  SELECT
    dt,
    STRING_AGG(users) OVER(ORDER BY UNIX_DATE(dt) RANGE BETWEEN 10 PRECEDING AND CURRENT ROW) users
  FROM temp1
)
SELECT dt,
  (SELECT COUNT(DISTINCT id) FROM UNNEST(SPLIT(users)) AS id) UniqueTenDays
FROM temp2


问:
How to read .mod files using Python
I have a file with extension .mod.
That file contains fields and data under each field, just like every csv files do.
I need to read this .mod file using Python.

Please suggest me a way out in Python using Pandas or any other package that could help me with this.

Thanks!

答:
On Windows 10, using Python 3.6, I could successfully open the file and read the first line:</p>

```<code>with open('09nested.mod') as f:
    print(f.readlines()[0])

// File: 09nested.mod

>>>
</code>```

Title: How to read .mod files using Python

Body:
On Windows 10, using Python 3.6, I could successfully open the file and read the first line:

with open('09nested.mod') as f:
    print(f.readlines()[0])

// File: 09nested.mod

>>>


问:
How to efficiently alias a float as both a named member and an element of an array?
I am implementing a particle-based fluid simulation. To represent vectors such as velocity, acceleration etc I have defined a class that looks like this

```<code>class Vec3f {
public:
    float x, y, z;

    // ... bunch of constructors, operators and utility functions
}
</code>```

I'm using the library nanoflann for kd-tree searches. To accommodate for arbitrary class designs, nanoflann requires a user-defined adaptor class that the kd-tree class then queries to get info about the particle dataset. One function that the adaptor has to offer, as described in the nanoflann documentation is the following.

```<code>// Must return the dim'th component of the idx'th point in the class:
inline T kdtree_get_pt(const size_t idx, int dim) const { ... }
</code>```

The problem is that this interface does not work seamlessly with the x, y, z representation. Naively, it would need to do something like this

```<code>inline float kdtree_get_pt(const size_t idx, int dim) const {
    switch(dim) {
    case 0:
        return particlearray[idx].x;
    case 1:
        return particlearray[idx].y;
    case 2:
        return particlearray[idx].z;
    }
}
</code>```

Building and querying the kd-tree consumes a significant portion of my app's runtime and kd_tree_get_pt gets queried multiple times in the process so I need it to be optimized. The following solution should be faster.

```<code>class Vec3f {
public:
    float values[3];
    // ...
}

// Then inside the adaptor class
inline float kdtree_get_pt(const size_t idx, int dim) const {
    return particlearrray[idx].values[dim];
}
</code>```

However, I much prefer the x, y, z interface for my equations. Now that the problem is clear, my question is how can I keep the x, y, z notation for my equations without making kdtree_get_pt suboptimal.

Solutions I have considered:

Vec3f has member float values[3] and getters in the form of float& x(). The function call should be optimized away completely so this almost works but I do not want to have to add the parentheses in my equations if I can avoid it. eg I want to be able to write vec1.x - vec2.x instead of vec1.x() - vec2.x(). As far as I know, C++ does not offer a way to "disguise" a function call as a member variable, excluding preprocessor macros which I do not consider a safe solution.

Vec3f has members float values[3] and float& x, y, z where the latter are initialized to point to the corresponding floats in the array. I thought they would be optimized away as they are known at compile time and obviously cannot change value after initialization, but even with optimizations on, MSVC++ seems to actually store the float&s as can be seen by sizeof(Vec3f) growing by 12 bytes after their addition. This doubles the storage size of my dataset which raises a concern for cache misses when working with arbitrarily large datasets.

kdtree_get_pt uses float& values[3] to point to x, y, z. This might eliminate the branching cost, but I don't believe the extra level of indirection, nor the need to initialize all 3 references can be optimized away so it is presumably slower than the return particlearrray[idx][dim]` version.

kdtree_get_pt uses reinterpret_cast or pointer magic to directly point into Vec3f's members. Given a Vec3f object's address, I believe x, y, z are guaranteed to be stored in that order with the first one stored at the same address as the one given by the & operator on the Vec3f object, but even so I'm confused as to whether there exists a well-defined way to observe them.

答:
There is known technique for mixing up access via x, y, z and array indices using union of identical data types. Resolves problem with UB, sizeof() is 12 bytes, access time is as fast as it can be, one could use SIMD vector in very similar fashion. Code below tested with VS2017

```<code>#include <iostream>
#include <type_traits>

template <int Size> struct VectorBase {
    float _data[Size];

    float operator[](int Index) {
        return _data[Index];
    }
};

template <typename VectorType, int Index> struct ScalarAccessor {
    VectorType _v;

    operator float() const {
        return _v._data[Index];
    }

    float operator = (float x) {
        _v._data[Index] = x;
        return *this;
    }
};

union uuu {
        VectorBase<3>                    xyz;
        ScalarAccessor<VectorBase<3>, 0> x;
        ScalarAccessor<VectorBase<3>, 1> y;
        ScalarAccessor<VectorBase<3>, 2> z;
};

template <int Size> struct Vector {
    union
    {
        VectorBase<3>                    xyz;
        ScalarAccessor<VectorBase<3>, 0> x;
        ScalarAccessor<VectorBase<3>, 1> y;
        ScalarAccessor<VectorBase<3>, 2> z;
    };

    float operator[](int Index) {
        return xyz[Index];
    }
};

using Vec3f = Vector<3>;

int main() {
    Vec3f a;

    a.x = 1.0f;
    a.y = a.x + 3.0f;
    a.z = a.x * 3.0f;

    std::cout << sizeof(a) << "\n";
    std::cout << a.x << " " << a.y << " " << a.z << "\n";
    std::cout << a[0] << " " << a[1] << " " << a[2] << "\n";

    std::cout << std::is_standard_layout<VectorBase<3>>::value << "\n";
    std::cout << std::is_standard_layout<ScalarAccessor<VectorBase<3>, 0>>::value << "\n";
    std::cout << std::is_standard_layout<ScalarAccessor<VectorBase<3>, 1>>::value << "\n";
    std::cout << std::is_standard_layout<ScalarAccessor<VectorBase<3>, 2>>::value << "\n";
    std::cout << std::is_standard_layout<Vec3f>::value << "\n";
    std::cout << std::is_standard_layout<uuu>::value << "\n";

    return 0;
}
</code>```

UPDATE

Here some C++ standard reading

I'm relying on the definition of standard-layout type 12.7 Classes

A class S is a standard-layout class if it:
  (7.1) — has no non-static data members of type non-standard-layout class (or array of such
  types) or reference,
  (7.2) — has no virtual functions (13.3) and no virtual base classes (13.1),
  (7.3) — has the same access control (Clause 14) for all non-static data members,
  (7.4) — has no non-standard-layout base classes, (7.5) — has at most one base class subobject of any given type
  ...

It is easy to check if all proposed classes are standard-layout - I've changed the code to check for that.

They are all layout-compatible, I believe

Also If a standard-layout class object has any non-static data members, its address is the same as the address of its first non-static data member.

Union is a standard-layout class as well, so we have classes aligned in union with only data member being array of the same type and size, and looks like standard requires it to be byte-by-byte compatible

Body:
I am implementing a particle-based fluid simulation. To represent vectors such as velocity, acceleration etc I have defined a class that looks like this

class Vec3f {
public:
    float x, y, z;

    // ... bunch of constructors, operators and utility functions
}

I'm using the library nanoflann for kd-tree searches. To accommodate for arbitrary class designs, nanoflann requires a user-defined adaptor class that the kd-tree class then queries to get info about the particle dataset. One function that the adaptor has to offer, as described in the nanoflann documentation is the following.

// Must return the dim'th component of the idx'th point in the class:
inline T kdtree_get_pt(const size_t idx, int dim) const { ... }

The problem is that this interface does not work seamlessly with the x, y, z representation. Naively, it would need to do something like this

inline float kdtree_get_pt(const size_t idx, int dim) const {
    switch(dim) {
    case 0:
        return particlearray[idx].x;
    case 1:
        return particlearray[idx].y;
    case 2:
        return particlearray[idx].z;
    }
}

Building and querying the kd-tree consumes a significant portion of my app's runtime and kd_tree_get_pt gets queried multiple times in the process so I need it to be optimized. The following solution should be faster.

class Vec3f {
public:
    float values[3];
    // ...
}

// Then inside the adaptor class
inline float kdtree_get_pt(const size_t idx, int dim) const {
    return particlearrray[idx].values[dim];
}

However, I much prefer the x, y, z interface for my equations. Now that the problem is clear, my question is how can I keep the x, y, z notation for my equations without making kdtree_get_pt suboptimal.

Solutions I have considered:

Vec3f has member float values[3] and getters in the form of float& x(). The function call should be optimized away completely so this almost works but I do not want to have to add the parentheses in my equations if I can avoid it. eg I want to be able to write vec1.x - vec2.x instead of vec1.x() - vec2.x(). As far as I know, C++ does not offer a way to "disguise" a function call as a member variable, excluding preprocessor macros which I do not consider a safe solution.

Vec3f has members float values[3] and float& x, y, z where the latter are initialized to point to the corresponding floats in the array. I thought they would be optimized away as they are known at compile time and obviously cannot change value after initialization, but even with optimizations on, MSVC++ seems to actually store the float&s as can be seen by sizeof(Vec3f) growing by 12 bytes after their addition. This doubles the storage size of my dataset which raises a concern for cache misses when working with arbitrarily large datasets.

kdtree_get_pt uses float& values[3] to point to x, y, z. This might eliminate the branching cost, but I don't believe the extra level of indirection, nor the need to initialize all 3 references can be optimized away so it is presumably slower than the return particlearrray[idx][dim]` version.

kdtree_get_pt uses reinterpret_cast or pointer magic to directly point into Vec3f's members. Given a Vec3f object's address, I believe x, y, z are guaranteed to be stored in that order with the first one stored at the same address as the one given by the & operator on the Vec3f object, but even so I'm confused as to whether there exists a well-defined way to observe them.

Body:
There is known technique for mixing up access via x, y, z and array indices using union of identical data types. Resolves problem with UB, sizeof() is 12 bytes, access time is as fast as it can be, one could use SIMD vector in very similar fashion. Code below tested with VS2017

#include <iostream>
#include <type_traits>

template <int Size> struct VectorBase {
    float _data[Size];

    float operator[](int Index) {
        return _data[Index];
    }
};

template <typename VectorType, int Index> struct ScalarAccessor {
    VectorType _v;

    operator float() const {
        return _v._data[Index];
    }

    float operator = (float x) {
        _v._data[Index] = x;
        return *this;
    }
};

union uuu {
        VectorBase<3>                    xyz;
        ScalarAccessor<VectorBase<3>, 0> x;
        ScalarAccessor<VectorBase<3>, 1> y;
        ScalarAccessor<VectorBase<3>, 2> z;
};

template <int Size> struct Vector {
    union
    {
        VectorBase<3>                    xyz;
        ScalarAccessor<VectorBase<3>, 0> x;
        ScalarAccessor<VectorBase<3>, 1> y;
        ScalarAccessor<VectorBase<3>, 2> z;
    };

    float operator[](int Index) {
        return xyz[Index];
    }
};

using Vec3f = Vector<3>;

int main() {
    Vec3f a;

    a.x = 1.0f;
    a.y = a.x + 3.0f;
    a.z = a.x * 3.0f;

    std::cout << sizeof(a) << "\n";
    std::cout << a.x << " " << a.y << " " << a.z << "\n";
    std::cout << a[0] << " " << a[1] << " " << a[2] << "\n";

    std::cout << std::is_standard_layout<VectorBase<3>>::value << "\n";
    std::cout << std::is_standard_layout<ScalarAccessor<VectorBase<3>, 0>>::value << "\n";
    std::cout << std::is_standard_layout<ScalarAccessor<VectorBase<3>, 1>>::value << "\n";
    std::cout << std::is_standard_layout<ScalarAccessor<VectorBase<3>, 2>>::value << "\n";
    std::cout << std::is_standard_layout<Vec3f>::value << "\n";
    std::cout << std::is_standard_layout<uuu>::value << "\n";

    return 0;
}

UPDATE

Here some C++ standard reading

I'm relying on the definition of standard-layout type 12.7 Classes

A class S is a standard-layout class if it:
  (7.1) — has no non-static data members of type non-standard-layout class (or array of such
  types) or reference,
  (7.2) — has no virtual functions (13.3) and no virtual base classes (13.1),
  (7.3) — has the same access control (Clause 14) for all non-static data members,
  (7.4) — has no non-standard-layout base classes, (7.5) — has at most one base class subobject of any given type
  ...

It is easy to check if all proposed classes are standard-layout - I've changed the code to check for that.

They are all layout-compatible, I believe

Also If a standard-layout class object has any non-static data members, its address is the same as the address of its first non-static data member.

Union is a standard-layout class as well, so we have classes aligned in union with only data member being array of the same type and size, and looks like standard requires it to be byte-by-byte compatible


问:
sqlite3-ruby gem: Failed to build gem native extension
Update: Check out this follow-up question: Gem Update on Windows - is it broken?

On Windows, when I do this:

```<code>gem install sqlite3-ruby
</code>```

I get the following error:

```<code>Building native extensions.  This could take a while...
ERROR:  Error installing sqlite3-ruby:
        ERROR: Failed to build gem native extension.

c:/ruby/bin/ruby.exe extconf.rb install sqlite3-ruby --platform Win32
checking for fdatasync() in rt.lib... no
checking for sqlite3.h... no

nmake
'nmake' is not recognized as an internal or external command,
operable program or batch file.

Gem files will remain installed in c:/ruby/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4 for inspection.
Results logged to c:/ruby/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4/ext/sqlite3_api/gem_make.out
</code>```

Same thing happens with the hpricot gem. I seem to remember these gems installed just fine on < 1.0 gems, but now I'm on 1.2.0, things have gone screwy.

I have also tried this:

```<code>gem install sqlite3-ruby --platform Win32
</code>```

Needless to say, this doesn't work either (same error)

Does anyone know what is going on here and how to fix this?

Update: Check out this follow-up question: Gem Update on Windows - is it broken?

答:
I had the same problem on Ubuntu, this solved the problem for me:

http://newsgroups.derkeiler.com/Archive/Comp/comp.lang.ruby/2008-08/msg00339.html

OwnerDisplayName: charlesroper

Body:
Update: Check out this follow-up question: Gem Update on Windows - is it broken?

On Windows, when I do this:

gem install sqlite3-ruby

I get the following error:

Building native extensions.  This could take a while...
ERROR:  Error installing sqlite3-ruby:
        ERROR: Failed to build gem native extension.

c:/ruby/bin/ruby.exe extconf.rb install sqlite3-ruby --platform Win32
checking for fdatasync() in rt.lib... no
checking for sqlite3.h... no

nmake
'nmake' is not recognized as an internal or external command,
operable program or batch file.

Gem files will remain installed in c:/ruby/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4 for inspection.
Results logged to c:/ruby/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4/ext/sqlite3_api/gem_make.out

Same thing happens with the hpricot gem. I seem to remember these gems installed just fine on < 1.0 gems, but now I'm on 1.2.0, things have gone screwy.

I have also tried this:

gem install sqlite3-ruby --platform Win32

Needless to say, this doesn't work either (same error)

Does anyone know what is going on here and how to fix this?

Update: Check out this follow-up question: Gem Update on Windows - is it broken?

LastEditorDisplayName: Charles Roper

OwnerDisplayName: Mercurious


问:
Using Joined-Tables to exclude certain records
I have a SQL Server 2005 table (#1) that list employee names, and various info about each of them.

I have a second table (#2) that lists some of the employees that I wish to exclude from my results.
(The employee names could appear in either of 2 columns: A and B.)

Can I use joined-tables to EXCLUDE?

List all employees named Fred in table #1... but exclude a certain employee listed in table #2.
If Fred Smith is listed in table #2 (in either of 2 fields), don't list him in my results.
(but list all other Fred records from table #1)

```<code>SELECT *
FROM table1 AS t1, table2 AS t2
WHERE ('Fred Smith' <> t2.employeeA) AND ('Fred Smith' <> t2.employeeB)
</code>```

(Actually I can't get it to work regardless of whether I use joined-tables, or not.)

答:
There are various ways to write this, but the best performing one (normally, data distribution can change this) is normally the existence test. It is also easy to understand the exact intention as written.

```<code>select * from table1 t1
where not exists (
    select * from table2 t2
    where t2.employeeA = t1.employee
       or t2.employeeB = t1.employee)
</code>```

You can always try another way as well to see which works better for you

```<code>select t1.*
from table1 t1
left join table2 t2 on
  t2.employeeA = t1.employee or t2.employeeB = t1.employee
where t2.id is null   -- check that the join failed by testing against the PK of t2
</code>```

Body:
I have a SQL Server 2005 table (#1) that list employee names, and various info about each of them.

I have a second table (#2) that lists some of the employees that I wish to exclude from my results.
(The employee names could appear in either of 2 columns: A and B.)

Can I use joined-tables to EXCLUDE?

List all employees named Fred in table #1... but exclude a certain employee listed in table #2.
If Fred Smith is listed in table #2 (in either of 2 fields), don't list him in my results.
(but list all other Fred records from table #1)

SELECT *
FROM table1 AS t1, table2 AS t2
WHERE ('Fred Smith' <> t2.employeeA) AND ('Fred Smith' <> t2.employeeB)

(Actually I can't get it to work regardless of whether I use joined-tables, or not.)

Body:
There are various ways to write this, but the best performing one (normally, data distribution can change this) is normally the existence test. It is also easy to understand the exact intention as written.

select * from table1 t1
where not exists (
    select * from table2 t2
    where t2.employeeA = t1.employee
       or t2.employeeB = t1.employee)

You can always try another way as well to see which works better for you

select t1.*
from table1 t1
left join table2 t2 on
  t2.employeeA = t1.employee or t2.employeeB = t1.employee
where t2.id is null   -- check that the join failed by testing against the PK of t2


问:
How do I create a function that increments the value of a global value?
I am currently trying to perform some simple actions on a variable that I've given the value of zero. First of all, I am declaring a variable and giving it a value (0). Secondly, I am creating a function which is supposed to increment the value of my variable when the function is invoked. This is my code:

```<code>var orderCount = 0;

function takeOrder(orderCount) {
return orderCount++;
}

takeOrder(orderCount);
takeOrder(orderCount);

alert(orderCount);
</code>```

The exptected result of the code snippet above would be "2", since the function is invoked twice and the number 0 therefore should be incremented twice.

I have also tried incrementing the variable "orderCount" with the following code instead of the one posted above:

```<code>function takeOrder(orderCount) {
return orderCount + 1;
}
</code>```

Neither works. What am I doing wrong?

答:
Remove orderCount from your parameter list, and don't include it as an argument when calling the function. By specifying it as a parameter, you're shadowing (hiding) the global variable that takeOrder closes over.

var orderCount = 0;

function takeOrder() {
//                 ^----- don't include `orderCount` as a parameter
    return orderCount++;
}

takeOrder(); // <== don't specify it when calling the
takeOrder(); // <== function (though it would just be ignored)

alert(orderCount);```

Body:
I am currently trying to perform some simple actions on a variable that I've given the value of zero. First of all, I am declaring a variable and giving it a value (0). Secondly, I am creating a function which is supposed to increment the value of my variable when the function is invoked. This is my code:

var orderCount = 0;

function takeOrder(orderCount) {
return orderCount++;
}

takeOrder(orderCount);
takeOrder(orderCount);

alert(orderCount);

The exptected result of the code snippet above would be "2", since the function is invoked twice and the number 0 therefore should be incremented twice.

I have also tried incrementing the variable "orderCount" with the following code instead of the one posted above:

function takeOrder(orderCount) {
return orderCount + 1;
}

Neither works. What am I doing wrong?


问:
How to get result of multiple records into map int JDBC Template?
I am using queryForList to get an arrayList of the result set, like the following example :

```<code>List<Student> studentsList = null;
String sql = "SELECT * FROM [student]";
try {
    studentsList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Student.class));
} catch (EmptyResultDataAccessException e) {
}
return (ArrayList<Student>) studentsList;
</code>```

Now I want to get the result of this list into a map of key and object directly from the query.

Any ideas?

答:
It's not possible for you to obtain your Map from the query as such. You will need to manipulate your List returned from jdbcTemplate.query so that it gives you the Map you require with each key being the id of the student:

```<code>Map<Integer, Student> studentMap = new HashMap<Integer, Student>();
for (Student student : studentsList) {
    studentMap.put(student.getId(), student);
}
</code>```

If you're using java 8 you can use a Collector:

```<code>Map<Integer, Student> result = studentsList.stream().collect(Collectors.toMap(Student::getId, Function.identity()));
</code>```

Body:
I am using queryForList to get an arrayList of the result set, like the following example :

List<Student> studentsList = null;
String sql = "SELECT * FROM [student]";
try {
    studentsList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Student.class));
} catch (EmptyResultDataAccessException e) {
}
return (ArrayList<Student>) studentsList;

Now I want to get the result of this list into a map of key and object directly from the query.

Any ideas?

Body:
It's not possible for you to obtain your Map from the query as such. You will need to manipulate your List returned from jdbcTemplate.query so that it gives you the Map you require with each key being the id of the student:

Map<Integer, Student> studentMap = new HashMap<Integer, Student>();
for (Student student : studentsList) {
    studentMap.put(student.getId(), student);
}

If you're using java 8 you can use a Collector:

Map<Integer, Student> result = studentsList.stream().collect(Collectors.toMap(Student::getId, Function.identity()));


问:
Query and regex find data

Hello guys! I try to accomplish the following.
I have a string which is a query string like:

```<code>let query = "?course_subject=Robotica&course_type=%20C&course_location=%20VIV7&course_teacher=%20Pozna_C_R&course_start_hour=14:00%20&course_end_hour=%2015:50"
</code>```

Which I get with:window.location.search

What I try to get back is all the pairs name - value in an array like:

```<code>output_array = [["course_subject","Robotia"],["course_type","C"]]
</code>```

And so on.
But I can not figure out how to write the code using regex.
Can someone help me with the code?
I mention that I do not know the query string which it will come, so I can not search using a name,like:course_subject or course_type

答:
```<code>let query = "?course_subject=Robotica&course_type=%20C&course_location=%20VIV7&course_teacher=%20Pozna_C_R&course_start_hour=14:00%20&course_end_hour=%2015:50"
var output_array=[];
    decodeURI(query.slice(1)).split("&").forEach(function (item) {
        output_array.push(item.split("="));
    });
</code>```

should do the job.
slice(1) is for getting rid of ? at the start.

Title: Query and regex find data

Body:
Hello guys! I try to accomplish the following.
I have a string which is a query string like:

let query = "?course_subject=Robotica&course_type=%20C&course_location=%20VIV7&course_teacher=%20Pozna_C_R&course_start_hour=14:00%20&course_end_hour=%2015:50"

Which I get with:window.location.search

What I try to get back is all the pairs name - value in an array like:

output_array = [["course_subject","Robotia"],["course_type","C"]]

And so on.
But I can not figure out how to write the code using regex.
Can someone help me with the code?
I mention that I do not know the query string which it will come, so I can not search using a name,like:course_subject or course_type

Body:
let query = "?course_subject=Robotica&course_type=%20C&course_location=%20VIV7&course_teacher=%20Pozna_C_R&course_start_hour=14:00%20&course_end_hour=%2015:50"
var output_array=[];
    decodeURI(query.slice(1)).split("&").forEach(function (item) {
        output_array.push(item.split("="));
    });

should do the job.
slice(1) is for getting rid of ? at the start.


问:
How to convert these character fields to time stamp in hive
I have these  character fields actv_date and actv_time in a hive table

```<code>    ap_actv_date
          171205 (YYMMDD)
    ap_actv_time
         1954359 (HHMMSSF)
</code>```

 I want the output to be a time stamp field of format  YYYY-MM-DD HH:MM:SS.f

答:
Use this.</p>

```<code>from_unixtime(unix_timestamp(concat(ap_actv_date,ap_actv_time), 'YYMMDDHHMMSSF'))
</code>```

Body:
I have these  character fields actv_date and actv_time in a hive table

    ap_actv_date
          171205 (YYMMDD)
    ap_actv_time
         1954359 (HHMMSSF)

 I want the output to be a time stamp field of format  YYYY-MM-DD HH:MM:SS.f

Body:
Use this.

from_unixtime(unix_timestamp(concat(ap_actv_date,ap_actv_time), 'YYMMDDHHMMSSF'))


问:
Jenkins git plugin, polling certain paths
I have a jenkins job for a maven multi module project with this structure:

Module A

Module B

desktop_App

common

...

I want to execute the job that deploy the desktop_app only when changes are pushed to certain path. With git plugin it's supossed to do that but I put relative path on the white list field but scm ignore all commits

Git Polling Log

...

...

Ignored commit 7a5aafc79ffe142a63b8a65ed183068fcc1d42fa: No paths
  matched included region whitelist

How works this plugin?

答:
Have you tried changing the regex to:

desktop_app/.*

common/.*

This might be your problem.


问:
How to merge two optional arrays in javascript
How would you merge two optional arrays in Javascript these days? This is the best I got so far:

```<code>const trades = this.position.trades; // trades or maintenance can be undefined
const maintenance = this.position.maintenance;
const principals = [... trades ? trades : [], ... maintenance ? maintenance : []];
</code>```

Looking for elegant solutions while dealing with the fact that either array can be undefined (aka optional). Thanks!

PS: I'm using Typescript 2.6 / ES6

答:
You can do something like this. || this will return [] if the first operand is falsy.

```<code>const trades = this.position.trades || [];
const maintenance = this.position.maintenance || [];
const principals = [...trades, ...maintenance];
</code>```

Or instead of the spread operator just use Array#concat

```<code>const trades = this.position.trades || [];
const maintenance = this.position.maintenance || [];
const principals = trades.concat(maintenance);
</code>```

Body:
How would you merge two optional arrays in Javascript these days? This is the best I got so far:

const trades = this.position.trades; // trades or maintenance can be undefined
const maintenance = this.position.maintenance;
const principals = [... trades ? trades : [], ... maintenance ? maintenance : []];

Looking for elegant solutions while dealing with the fact that either array can be undefined (aka optional). Thanks!

PS: I'm using Typescript 2.6 / ES6

Body:
You can do something like this. || this will return [] if the first operand is falsy.

const trades = this.position.trades || [];
const maintenance = this.position.maintenance || [];
const principals = [...trades, ...maintenance];

Or instead of the spread operator just use Array#concat

const trades = this.position.trades || [];
const maintenance = this.position.maintenance || [];
const principals = trades.concat(maintenance);


问:
How does this function traverse Binary Tree?
I am working on a coding challenge. I found a solution, but I did not understand a part of the solution.

The prompt is

```<code>Given a binary tree, find the leftmost value in the last row of the tree.

Input:

        1
       / \
      2   3
     /   / \
    4   5   6
       /
      7

Output:
7
</code>```

Tree is defined:

```<code>/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
</code>```

This function works (I did not come up with it):

```<code>var findBottomLeftValue = function(root) {
    var result = root.val;
    var resultHeight = 0;
    (function recurse (node, height) {
        if (node === null) {
            return;
        }
        if (node.left !== null) {
            recurse(node.left, height + 1);
        }
        if (height > resultHeight) {
            result = node.val;
            resultHeight = height;
        }
        if (node.right !== null) {
            recurse(node.right, height + 1);
        }
    })(root, 1);
    return result;
};
</code>```

I understand most of the line, but frankly, this is my first time seeing IIFE inside another function, so maybe that threw me off a little.

What I don't understand is, let's say we start with root 1 (using example above), it starts off with node being 1. Since node.left !== null, node is now 2, since node.left !== null, it goes down to 4. node.left is now null, it goes to the next line, which updates height and resultHeight. Then next line, node.right is null, and function ends. In my understanding, it never went to check nodes 3, 5, etc. But the function clearly shows the right answer.

Where on the solution did it check for nodes 3, 5, 6, and 7?

答:
If you imagine what is happening as a stack,it's much easier to understand.

It starts on the node with value 1. When it checks the left node,it's left on hold as the first item of the stack(to be called again when it's the topmost item of the stack again)

It would look something like this when it starts on the second iteration:

```<code>2
---
1
</code>```

Then,it would keep executing and adding to the stack until it check that the node 4 has no left or right node.

At this moment,it would look like this:

```<code>4
---
2
---
1
</code>```

Then,since there's nothing else to do on the node with value 4,it gets removed out of the stack,and then it executes the next topmost of the stack from where it left off:checking the right node of it.

I hope this helped you visualise and understand what really happens because that really helped me and some college coleagues to understand binary trees.

Body:
I am working on a coding challenge. I found a solution, but I did not understand a part of the solution.

The prompt is

Given a binary tree, find the leftmost value in the last row of the tree.

Input:

        1
       / \
      2   3
     /   / \
    4   5   6
       /
      7

Output:
7

Tree is defined:

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */

This function works (I did not come up with it):

var findBottomLeftValue = function(root) {
    var result = root.val;
    var resultHeight = 0;
    (function recurse (node, height) {
        if (node === null) {
            return;
        }
        if (node.left !== null) {
            recurse(node.left, height + 1);
        }
        if (height > resultHeight) {
            result = node.val;
            resultHeight = height;
        }
        if (node.right !== null) {
            recurse(node.right, height + 1);
        }
    })(root, 1);
    return result;
};

I understand most of the line, but frankly, this is my first time seeing IIFE inside another function, so maybe that threw me off a little.

What I don't understand is, let's say we start with root 1 (using example above), it starts off with node being 1. Since node.left !== null, node is now 2, since node.left !== null, it goes down to 4. node.left is now null, it goes to the next line, which updates height and resultHeight. Then next line, node.right is null, and function ends. In my understanding, it never went to check nodes 3, 5, etc. But the function clearly shows the right answer.

Where on the solution did it check for nodes 3, 5, 6, and 7?

Body:
If you imagine what is happening as a stack,it's much easier to understand.

It starts on the node with value 1. When it checks the left node,it's left on hold as the first item of the stack(to be called again when it's the topmost item of the stack again)

It would look something like this when it starts on the second iteration:

2
---
1

Then,it would keep executing and adding to the stack until it check that the node 4 has no left or right node.

At this moment,it would look like this:

4
---
2
---
1

Then,since there's nothing else to do on the node with value 4,it gets removed out of the stack,and then it executes the next topmost of the stack from where it left off:checking the right node of it.

I hope this helped you visualise and understand what really happens because that really helped me and some college coleagues to understand binary trees.


答:
Couple of facts:

Parameter of the function acts like a function-scoped variable. You
can re-assign it, increment it etc. All these changes are gone once function finishes its execution.

Local variables named the same as "global" ones hide the latter
inside function body and therefore make all in-function changes isolated from the outside world.

Changing the parameter name will not help either, because the value of the global variable will be placed on the function call stack. In fact, passing any variable is not helpful at all.

Typical solution is to not use parameters at all and make your function change variable in the outside scope directly.

It is, however, possible to emulate passing a "reference" to a variable. If you really want your function to not know the global variable name:

var order = { count: 0 };
var anotherOrder = { count: 0 };

function takeOrder(order) {
    order.count++;
}

takeOrder(order);
takeOrder(order);
takeOrder(anotherOrder);

console.log("Order:"+order.count);
console.log("Another order:"+anotherOrder.count);```

Title: How do I create a function that increments the value of a global value?


答:
Simply call the function without passing the parameter

var orderCount = 0;

function takeOrder() {
  return orderCount++;
}

takeOrder();
takeOrder();

alert(orderCount);```


答:
You can use the || operator in conjunction with the spread operator which you already use:

```<code>const principals = [...this.position.trades || [], ...this.position.maintenance || []];
</code>```

Title: How to merge two optional arrays in javascript

Body:
You can use the || operator in conjunction with the spread operator which you already use:

const principals = [...this.position.trades || [], ...this.position.maintenance || []];


问:
How to get a certificate from a CA?
I need to get a certificate from a certificate authority with .crt extension.
I used openssl commands but it generates a self-signed certificate which is not suitable for my use.

$ openssl genrsa -out client.key 4096
$ openssl req -new -x509 -text -key client.key -out client.cert
```

How can I obtain a certificate form a CA in Ubuntu 16.04? I need .key and .crt files.

答:
These are the steps you would need to do to get a certificate signed by a CA.

Generate a Asymmetric Key Pair.

openssl genrsa -out localhost.key 2048

Generate a PKCS#10 (Certificate Signing Request) from the Key Pair.

openssl req -new -sha256 -key localhost.key -out localhost.csr

Send the above generated request to the CA (different CA's have different ways of receiving your request).

CA replies with a PKCS#7 (Certificate Chain) or just the signed certificate (you will usually get the entire certificate chain, but if you just got only the peer certificate, you can check with them where you can get the CA certificate chain to construct the chain yourself).

You can convert the above received PKCS#7 to PEM format

openssl pkcs7 -in localhost.p7r -inform DER -out localhost.pem
  -print_certs

Associate the above PEM certificate chain to the private key you generated in the step 1.

openssl pkcs12 -export -inkey localhost.key -in localhost.pem -name
  sslCertificate -out localhost.pfx

You now have a PKCS#12 keystore that you can use to secure your server.

So to answer you question, this is how you could proceed with step 3.

There are many well known Certificate Authorities out there (GeoTrust, Entrust, Verisign, GoDaddy, Comodo, etc, ...). Each CA could be different on their pricing depending on what kind of certificate you are requesting. You can visit their official web page(s) to know more about what they have to offer. Once you have decided which CA to go with, you use their service to request a certificate to be signed (usually online on their site).

ContentLicense: CC BY-SA 4.0

Title: How to get a certificate from a CA?

Body:
I need to get a certificate from a certificate authority with .crt extension.
I used openssl commands but it generates a self-signed certificate which is not suitable for my use.

$ openssl genrsa -out client.key 4096
$ openssl req -new -x509 -text -key client.key -out client.cert

How can I obtain a certificate form a CA in Ubuntu 16.04? I need .key and .crt files.


问:
Relative URLs in AJAX requests
Why does Javascript treat relative URLs differently than standard HTML? Think of the following URL (or just browse to it): http://en.wikipedia.org/wiki/Rome.
Open a Firebug console (or another Javascript console) and enter the following:

```<code>var x = new XMLHttpRequest();
x.open("GET", "foo", true);
x.send("bar");
</code>```

Under my system the request is sent to "http://en.wikipedia.org/wiki/foo". The "Rome" in the URL is simply ignored. The same request with a trailing slash in the URL ("http://en.wikipedia.org/wiki/Rome/") appends the "foo" to the full URL.

This seems to make it pretty hard to encode the correct URLs in Javascript. Are there any Javascript libraries that help to overcome this problem?

(I asked a similiar question before, but more jQuery specific, where this also happens. I hope I get a better answer with this somewhat more library independent question.)

答:
(updated to make it more readable)

This is how relative paths is supposed to work.

Pretend that the current address is this:

Absolute: protocol://some.domain.name/dir1/dir2/filename

If you specify only a new filename "foo", you get the same protocol, host and dirs, only the file name is changed:

Relative: foo

Absolute: protocol://some.domain.name/dir1/dir2/foo

If you specify a whole path "/dir3/filename2" you get the same protocol and hostname but with another path:

Relative: /dir3/filename2

Absolute: protocol://some.domain.name/dir3/filename2

You can also specify host name "//another.domain.name/dir5/filename3" and get the same protocol but another host, dir and filename:

Relative: //another.domain.name/dir5/filename3

Absolute: protocol://another.domain.name/dir5/filename3

What might be confusing is that a webserver internally can add a / at the end of the url if the specified url points to a directory and not to a file.

protocol://some.domain.name/somename

If "somename" is a directory the webserver might translate it to (possible with a redirect)

protocol://some.domain.name/somename/

UPDATE

As cameron said in a comment: For reference, see step 6 in section 4 of RFC 1808

Title: Relative URLs in AJAX requests

Body:
Why does Javascript treat relative URLs differently than standard HTML? Think of the following URL (or just browse to it): http://en.wikipedia.org/wiki/Rome.
Open a Firebug console (or another Javascript console) and enter the following:

var x = new XMLHttpRequest();
x.open("GET", "foo", true);
x.send("bar");

Under my system the request is sent to "http://en.wikipedia.org/wiki/foo". The "Rome" in the URL is simply ignored. The same request with a trailing slash in the URL ("http://en.wikipedia.org/wiki/Rome/") appends the "foo" to the full URL.

This seems to make it pretty hard to encode the correct URLs in Javascript. Are there any Javascript libraries that help to overcome this problem?

(I asked a similiar question before, but more jQuery specific, where this also happens. I hope I get a better answer with this somewhat more library independent question.)