问:
How do I compute the non-client window size in WPF?
WPF has the SystemParameters class that exposes a great number of system metrics. On my computer I have noticed that a normal window has a title that is 30 pixels high and a border that is 8 pixels wide. This is on Windows 7 with the Aero theme enabled:

However, SystemParameters return the following values:

```<code>SystemParameters.BorderWidth = 5
SystemParameters.CaptionHeight = 21
</code>```

Here I have disabled the Aero theme:

Now, SystemParameters return the following values:

```<code>SystemParameters.BorderWidth = 1
SystemParameters.CaptionHeight = 18
</code>```

How do I compute the actual observed values by using SystemParameters?

答:
I'm pretty sure that the GetSystemMetrics function (which the SystemParameters class calls internally with the appropriate arguments) is returning the correct values for your system, it's just returning the correct values in the case whether the Aero theme is disabled. By turning on Aero, you get beefier borders and taller window captions, all the name of juicy graphical goodness.

If you want to get the correct size of these window elements, regardless of the user's current theme (remember, you can run Windows Vista and beyond with the Classic theme, the Aero Basic theme, or the full Aero theme, all of which are going to have different-sized UI elements), you need to use a different method available in Vista and later.

You need to send the window a WM_GETTITLEBARINFOEX message in order to request extended title bar information. The wParam is unused and should be zero. The lParam contains a pointer to a TITLEBARINFOEX structure that will receive all of the information. The caller is responsible for allocating memory for this structure and setting its cbSize member.

To do all of this from a .NET application, you'll obviously need to do some P/Invoke. Start by defining the constants you need, as well as the TITLEBARINFOEX structure:

```<code>internal const int WM_GETTITLEBARINFOEX = 0x033F;
internal const int CCHILDREN_TITLEBAR = 5;

[StructLayout(LayoutKind.Sequential)]
internal struct TITLEBARINFOEX
{
    public int cbSize;
    public Rectangle rcTitleBar;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = CCHILDREN_TITLEBAR + 1)]
    public int[] rgstate;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = CCHILDREN_TITLEBAR + 1)]
    public Rectangle[] rgrect;
}
</code>```

Then define the SendMessage function accordingly:

```<code>[DllImport("user32.dll", CharSet = CharSet.Auto)]
internal static extern IntPtr SendMessage(
                                          IntPtr hWnd,
                                          int uMsg,
                                          IntPtr wParam,
                                          ref TITLEBARINFOEX lParam);
</code>```

And finally, you can call all of that mess using something like the following code:

```<code>internal static TITLEBARINFOEX GetTitleBarInfoEx(IntPtr hWnd)
{
    // Create and initialize the structure
    TITLEBARINFOEX tbi = new TITLEBARINFOEX();
    tbi.cbSize = Marshal.SizeOf(typeof(TITLEBARINFOEX));

    // Send the WM_GETTITLEBARINFOEX message
    SendMessage(hWnd, WM_GETTITLEBARINFOEX, IntPtr.Zero, ref tbi);

    // Return the filled-in structure
    return tbi;
}
</code>```

EDIT: Now tested and working on my notebook running Windows 7.

Body:
WPF has the SystemParameters class that exposes a great number of system metrics. On my computer I have noticed that a normal window has a title that is 30 pixels high and a border that is 8 pixels wide. This is on Windows 7 with the Aero theme enabled:

However, SystemParameters return the following values:

SystemParameters.BorderWidth = 5
SystemParameters.CaptionHeight = 21

Here I have disabled the Aero theme:

Now, SystemParameters return the following values:

SystemParameters.BorderWidth = 1
SystemParameters.CaptionHeight = 18

How do I compute the actual observed values by using SystemParameters?

Body:
I'm pretty sure that the GetSystemMetrics function (which the SystemParameters class calls internally with the appropriate arguments) is returning the correct values for your system, it's just returning the correct values in the case whether the Aero theme is disabled. By turning on Aero, you get beefier borders and taller window captions, all the name of juicy graphical goodness.

If you want to get the correct size of these window elements, regardless of the user's current theme (remember, you can run Windows Vista and beyond with the Classic theme, the Aero Basic theme, or the full Aero theme, all of which are going to have different-sized UI elements), you need to use a different method available in Vista and later.

You need to send the window a WM_GETTITLEBARINFOEX message in order to request extended title bar information. The wParam is unused and should be zero. The lParam contains a pointer to a TITLEBARINFOEX structure that will receive all of the information. The caller is responsible for allocating memory for this structure and setting its cbSize member.

To do all of this from a .NET application, you'll obviously need to do some P/Invoke. Start by defining the constants you need, as well as the TITLEBARINFOEX structure:

internal const int WM_GETTITLEBARINFOEX = 0x033F;
internal const int CCHILDREN_TITLEBAR = 5;

[StructLayout(LayoutKind.Sequential)]
internal struct TITLEBARINFOEX
{
    public int cbSize;
    public Rectangle rcTitleBar;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = CCHILDREN_TITLEBAR + 1)]
    public int[] rgstate;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = CCHILDREN_TITLEBAR + 1)]
    public Rectangle[] rgrect;
}

Then define the SendMessage function accordingly:

[DllImport("user32.dll", CharSet = CharSet.Auto)]
internal static extern IntPtr SendMessage(
                                          IntPtr hWnd,
                                          int uMsg,
                                          IntPtr wParam,
                                          ref TITLEBARINFOEX lParam);

And finally, you can call all of that mess using something like the following code:

internal static TITLEBARINFOEX GetTitleBarInfoEx(IntPtr hWnd)
{
    // Create and initialize the structure
    TITLEBARINFOEX tbi = new TITLEBARINFOEX();
    tbi.cbSize = Marshal.SizeOf(typeof(TITLEBARINFOEX));

    // Send the WM_GETTITLEBARINFOEX message
    SendMessage(hWnd, WM_GETTITLEBARINFOEX, IntPtr.Zero, ref tbi);

    // Return the filled-in structure
    return tbi;
}

EDIT: Now tested and working on my notebook running Windows 7.


来源: stackexchange

问:
How to Export Multiple Row Headers in jQuery Datatables?
Hi I am using jQuery Datatables 1.10. I am trying to export Datatable multiple header rows but not getting. But it is Exporting only second header row. I am using Buttons: </p>

<pre class="lang-js prettyprint-override"><code> buttons: [{
        extend: 'excel',
        header: true

    }, {
        extend: 'print',
        header: true
    }],
</code>```

<p>My table Structure like </p>

<pre class="lang-html prettyprint-override"><code><table id="example" style="color: black;" class="display compact cell-border" cellspacing="0">
    <thead>
        <tr>
            <th rowspan="2">Sl.No</th>
            <th rowspan="2">Zone</th>
            <th colspan="2">Allotted</th>
            <th colspan="2">Vacant</th>
            <th colspan="2">Amenities</th>
            <th colspan="2">Total</th>
        </tr>
        <tr>
            <th>No Of Plots</th>
            <th>Area</th>
            <th>No Of Plots</th>
            <th>Area</th>
            <th>No Of Plots</th>
            <th>Area</th>
            <th>No Of Plots</th>
            <th>Area</th>
        </tr>
    </thead>
</table>
</code>```

答:
I've created a custom buttons.html5.js (based in Ronnie's solution) that allows Multiple Headers and Footers in Excel export

https://gist.github.com/emersonmoretto/41993309f74a4b09f8e90c0a541de342

ContentLicense: CC BY-SA 4.0

Body:
Hi I am using jQuery Datatables 1.10. I am trying to export Datatable multiple header rows but not getting. But it is Exporting only second header row. I am using Buttons:

 buttons: [{
        extend: 'excel',
        header: true

    }, {
        extend: 'print',
        header: true
    }],

My table Structure like

            Sl.No
            Zone
            Allotted
            Vacant
            Amenities
            Total

            No Of Plots
            Area
            No Of Plots
            Area
            No Of Plots
            Area
            No Of Plots
            Area


问:
What is the difference between these scripts for "geth attach"?
I am using using capegemini ethereum docker : https://github.com/Capgemini-AIE/ethereum-docker

geth attach http://localhost:8545

docker exec -it ethereum-docker_eth_1 geth attach ipc://root/.ethereum/devchain/geth.ipc

sudo docker exec -it fa78bf925a6b bash
geth attach /root/.ethereum/devchain/geth.ipc

All of the above scripts attach to geth and opens javascript console.
But when I check "eth.hashrate" only first script produces some result, rest outputs zero.

All of these should have same behaviour, but its different, why ?

答:
geth attach http://localhost:8545

You are using the binary on your host and communicate via rpc. It works only if you have exposed your container port to the host. If you haven't exposed your container port then it means that your attaching it to geth running on your local machine (not your container). Try to stop the docker container and running the command again, if it works, it means that you have a local geth running

docker exec -it ethereum-docker_eth_1 geth attach ipc://root/.ethereum/devchain/geth.ipc

You are running geth attach directly in your container using ipc. IPC is a way to communicate between process using file (i may be wrong on this point)

sudo docker exec -it fa78bf925a6b bash geth attach /root/.ethereum/devchain/geth.ipc

You don't need to run this command under sudo if you don't have a permission denied error. Same as before your attaching geth via ipc inside the container. bash means that you run your command in through bash, you don't need this (except if you have some trouble finding geth binary).

I hope this helps you troubleshot your problem.


问:
Passing a double pointer in a function
I was creating a program with linked lists in C. I created a head variable in main function. Then I passed it by reference to a function insert_at_head(struct node **head).

I have another function for inserting at tail. In a base condition, if my list is empty, I want to call insert_at_head(struct node **head) again. But I am getting confused in passing the actual parameter. Should it be insert_at_head (&(*head)) or insert_at_head (head)?

Personally, I think both are same, because both of them are passing a double pointer. Which one should I use?

答:
In C language, you can't pass a variable by reference.

You can, however, pass a pointer to your variable. Of course the pointer is passed by value. For example, if you declare a varable head which is a pointer to a structure node:

```<code>struct node* head;
</code>```

you can prepare a function to operate on such variable:

```<code>void insert_at_head(struct node** ptr);
</code>```

Then you call it with:

```<code>insert_at_head(&head);
</code>```

where operator & yield a pointer to your variable, i.e. a value of the struct node ** type. That value is passed to the callee.

Of course, another function, say:

```<code>void append_at_end(struct node** ptr);
</code>```

can call the former function when necessary, passing it the same pointer it got as a parameter:

```<code>void append_at_end(struct node** ptr)
{
    if(*ptr == NULL)          /* list is empty */
        insert_at_head(ptr);  /* the same pointer to a head pointer */
    else {
        /* other stuff */
    }
}
</code>```

Title: Passing a double pointer in a function

Body:
In C language, you can't pass a variable by reference.

You can, however, pass a pointer to your variable. Of course the pointer is passed by value. For example, if you declare a varable head which is a pointer to a structure node:

struct node* head;

you can prepare a function to operate on such variable:

void insert_at_head(struct node** ptr);

Then you call it with:

insert_at_head(&head);

where operator & yield a pointer to your variable, i.e. a value of the struct node ** type. That value is passed to the callee.

Of course, another function, say:

void append_at_end(struct node** ptr);

can call the former function when necessary, passing it the same pointer it got as a parameter:

void append_at_end(struct node** ptr)
{
    if(*ptr == NULL)          /* list is empty */
        insert_at_head(ptr);  /* the same pointer to a head pointer */
    else {
        /* other stuff */
    }
}


问:
VBA - Date-Time String Replace/Substitute
I have a column which has date and time of emails from outlook. Some dates are in format - January 2, 2020 4:15 PM, January-14-20 12:44 PM, December-24-19 20:15 PM.

I have tried to use Replace and Substitute functions, Replace does work as defined but from the string time is removed. I would like to have all dates as 2019-12-27 3:02 PM.

```<code>sub Replace()
 Dim sString, searchString as String
 dim i, LastCell as Long

 LastCell = Range("C" & Rows.Count).End(xlUp).Row
 Set searchRng = Range("C3:C" & lastCell)

 For Each c In searchRng
   sString = c
   searchString = "-"

   If InStr(1, sString, searchString, vbTextCompare) > 0 Then
      i = InStr(1, sString, SearchString, vbTextCompare)
      i = InStr(i + 1, sString, SearchString, vbTextCompare)
      c.Offset(0, 1) = WorksheetFunction.Replace(sString, i, "19", " 2020")
   End If
 Next c
End Sub
</code>```

答:
CDate will convert a date/time that is a string into a real date/time that can be formatted.

So code like:

```<code>For Each c In rngSrc
    c.Offset(0, 1) = CDate(c)
    c.Offset(0, 1).NumberFormat = "yyyy-mm-dd h:mm AM/PM"
Next c
</code>```

will convert

Body:
I have a column which has date and time of emails from outlook. Some dates are in format - January 2, 2020 4:15 PM, January-14-20 12:44 PM, December-24-19 20:15 PM.

I have tried to use Replace and Substitute functions, Replace does work as defined but from the string time is removed. I would like to have all dates as 2019-12-27 3:02 PM.

sub Replace()
 Dim sString, searchString as String
 dim i, LastCell as Long

 LastCell = Range("C" & Rows.Count).End(xlUp).Row
 Set searchRng = Range("C3:C" & lastCell)

 For Each c In searchRng
   sString = c
   searchString = "-"

   If InStr(1, sString, searchString, vbTextCompare) > 0 Then
      i = InStr(1, sString, SearchString, vbTextCompare)
      i = InStr(i + 1, sString, SearchString, vbTextCompare)
      c.Offset(0, 1) = WorksheetFunction.Replace(sString, i, "19", " 2020")
   End If
 Next c
End Sub

Body:
CDate will convert a date/time that is a string into a real date/time that can be formatted.

So code like:

For Each c In rngSrc
    c.Offset(0, 1) = CDate(c)
    c.Offset(0, 1).NumberFormat = "yyyy-mm-dd h:mm AM/PM"
Next c

will convert


问:
How can I tell when a web page resource is cached?
Is there a way in JavaScript for me to tell whether a resource is already in the browser cache?

We're instrumenting a fraction of our client-side page views so that we can get better data on how quickly pages are loading for our users. The first time users arrive on our site, a number of resources (JS, CSS, images) are cached by the browser, so their initial pageview is going to be slower than subsequent ones.

Right now, that data is mixed together, so it's hard to tell an initial page load from a subsequent pageview that's slow for some other reason. I'd love a cross-browser way to check to see whether the cache is already primed, so that I can segregate the two sorts of pageview and analyze them separately.

答:
You should use TransferSize:

```<code>window.performance.getEntriesByName("https://[resource-name].js")[0].transferSize
</code>```

To verify it, you can run the above line on Chrome...

If the browser has caching enabled and your resource was previously loaded with proper cache-control header, transferSize should be 0.

If you disable caching (Network tab -> Disable cache) and reload, transferSize should be > 0.

ContentLicense: CC BY-SA 2.5

Body:
You should use TransferSize:

window.performance.getEntriesByName("https://[resource-name].js")[0].transferSize

To verify it, you can run the above line on Chrome...

If the browser has caching enabled and your resource was previously loaded with proper cache-control header, transferSize should be 0.

If you disable caching (Network tab -> Disable cache) and reload, transferSize should be > 0.


问:
"SSLHandshakeException: Error signing certificate verify" after certificate update
I have a SpringBoot 2 application, running in Tomcat 8.5 with Java8 Runtime.
It is is using a JKS Keystore for two different certs/keys which are both used by the application for mutual TLS (mTLS).

Since we retrieved a new version of the certificate from the CA admin, the application cannot use the keystore anymore with the following exception, as soon as a client mTLS call is attempted.

```<code>Exception in thread "main" javax.net.ssl.SSLHandshakeException: Error signing certificate verify
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1946)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:316)
    at sun.security.ssl.ClientHandshaker.serverHelloDone(ClientHandshaker.java:1174)
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:369)
    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1037)
    at sun.security.ssl.Handshaker.process_record(Handshaker.java:965)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1064)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1367)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1395)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1379)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:167)
    at UrlEngine.submit(UrlEngine.java:52)
    at JCurl.execute(JCurl.java:126)
    at JCurl.main(JCurl.java:62)
Caused by: java.security.InvalidKeyException: No installed provider supports this key: sun.security.pkcs.PKCS8Key
    at java.security.Signature$Delegate.chooseProvider(Signature.java:1138)
    at java.security.Signature$Delegate.engineInitSign(Signature.java:1188)
    at java.security.Signature.initSign(Signature.java:553)
    at sun.security.ssl.HandshakeMessage$CertificateVerify.<init>(HandshakeMessage.java:1591)
    at sun.security.ssl.ClientHandshaker.serverHelloDone(ClientHandshaker.java:1171)
    ... 13 more
</code>```

We have rebuilt the Keystore multiple times from its PKCS12 origin and when using the exported cert and key with e.g. curl everything is working fine.

答:
We finally found the solution to the issue. It was caused by the alias set in the JKS keystore. The operations use a script to generate the JKS keystore from PKCS12, while doing that friendly names/ aliases are set to the JKS keystore. The alias which was autogenerated by the script and set in the JKS file was too long or contained invalid characters. Thus we fixed it by setting the alias to a very short name which only contained hyphens and alphanumeric characters.

Thus you can fix the issue, if you run into the same one using this command:

```<code>keytool -changealias -alias "previous-long-alias" -destalias "new-short-alias" -keystore /path/to/keystore.jks
</code>```

Use the -keypass and -storepass arguments, if needed.

Body:
I have a SpringBoot 2 application, running in Tomcat 8.5 with Java8 Runtime.
It is is using a JKS Keystore for two different certs/keys which are both used by the application for mutual TLS (mTLS).

Since we retrieved a new version of the certificate from the CA admin, the application cannot use the keystore anymore with the following exception, as soon as a client mTLS call is attempted.

Exception in thread "main" javax.net.ssl.SSLHandshakeException: Error signing certificate verify
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1946)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:316)
    at sun.security.ssl.ClientHandshaker.serverHelloDone(ClientHandshaker.java:1174)
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:369)
    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1037)
    at sun.security.ssl.Handshaker.process_record(Handshaker.java:965)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1064)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1367)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1395)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1379)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:167)
    at UrlEngine.submit(UrlEngine.java:52)
    at JCurl.execute(JCurl.java:126)
    at JCurl.main(JCurl.java:62)
Caused by: java.security.InvalidKeyException: No installed provider supports this key: sun.security.pkcs.PKCS8Key
    at java.security.Signature$Delegate.chooseProvider(Signature.java:1138)
    at java.security.Signature$Delegate.engineInitSign(Signature.java:1188)
    at java.security.Signature.initSign(Signature.java:553)
    at sun.security.ssl.HandshakeMessage$CertificateVerify.<init>(HandshakeMessage.java:1591)
    at sun.security.ssl.ClientHandshaker.serverHelloDone(ClientHandshaker.java:1171)
    ... 13 more

We have rebuilt the Keystore multiple times from its PKCS12 origin and when using the exported cert and key with e.g. curl everything is working fine.

Body:
We finally found the solution to the issue. It was caused by the alias set in the JKS keystore. The operations use a script to generate the JKS keystore from PKCS12, while doing that friendly names/ aliases are set to the JKS keystore. The alias which was autogenerated by the script and set in the JKS file was too long or contained invalid characters. Thus we fixed it by setting the alias to a very short name which only contained hyphens and alphanumeric characters.

Thus you can fix the issue, if you run into the same one using this command:

keytool -changealias -alias "previous-long-alias" -destalias "new-short-alias" -keystore /path/to/keystore.jks

Use the -keypass and -storepass arguments, if needed.


问:
sqlite3.OperationalError: near "create": syntax error
I'm getting a rather strange syntax error in my schema.sql file.

The error is as follows:

File "/Users/user/Documents/GitProjects/FlaskApp/flaskr/db.py", line
  88, in init_db_command
      init_db() File "/Users/user/Documents/GitProjects/FlaskApp/flaskr/db.py", line 80, in
  init_db
      db.executescript(f.read().decode("utf-8")) sqlite3.OperationalError: near "create": syntax error

My schema looks like this:

```<code>drop table if exists post;
drop table if exists post_user;

create table post_user (
    user_id integer primary key autoincrement,
    email text unique not null,
    username text unique not null,
    password text not null
);

create table post (
    post_id integer primary key autoincrement,
    author_id integer not null,
    create timestamp not null default current_timestamp,
    title text not null,
    body text not null,
    foreign key (author_id) references post_user (user_id)
);
</code>```

And my python looks like this:

```<code>def init_db():
    db = get_db()
    with current_app.open_resource("schema.sql") as f:
        db.executescript(f.read().decode("utf-8"))
</code>```

And finally the directory:

```<code>root
 |--db.py
 |--schema.sql
instance
 |-- project.sqlite
</code>```

I'm using flask and sqlite3.
And my troubleshooting steps have been the following:

1) Remove everything except the first line (this works)

2) Removed everything except the first two lines (this doesn't)

3) Remove the ./instance/project.sqlite file

4) Use an online validator
    This was especially interesting because this found that each individual command works.
    But as soon as I string two back-to-back it said the commands were invalid.

5) Double checked the sqlite documentation on dropping tables

6) Even went so far as to ensure my .vimrc was set to utf-8

I'm sure I've missed something small here but nothing seems to be working.
Any help would be appreciated!

答: You likely want create timestamp column to be something like create_timestamp to avoid clashing with sql keywords.

Body:
I'm getting a rather strange syntax error in my schema.sql file.

The error is as follows:

File "/Users/user/Documents/GitProjects/FlaskApp/flaskr/db.py", line
  88, in init_db_command
      init_db() File "/Users/user/Documents/GitProjects/FlaskApp/flaskr/db.py", line 80, in
  init_db
      db.executescript(f.read().decode("utf-8")) sqlite3.OperationalError: near "create": syntax error

My schema looks like this:

drop table if exists post;
drop table if exists post_user;

create table post_user (
    user_id integer primary key autoincrement,
    email text unique not null,
    username text unique not null,
    password text not null
);

create table post (
    post_id integer primary key autoincrement,
    author_id integer not null,
    create timestamp not null default current_timestamp,
    title text not null,
    body text not null,
    foreign key (author_id) references post_user (user_id)
);

And my python looks like this:

def init_db():
    db = get_db()
    with current_app.open_resource("schema.sql") as f:
        db.executescript(f.read().decode("utf-8"))

And finally the directory:

root
 |--db.py
 |--schema.sql
instance
 |-- project.sqlite

I'm using flask and sqlite3.
And my troubleshooting steps have been the following:

1) Remove everything except the first line (this works)

2) Removed everything except the first two lines (this doesn't)

3) Remove the ./instance/project.sqlite file

4) Use an online validator
    This was especially interesting because this found that each individual command works.
    But as soon as I string two back-to-back it said the commands were invalid.

5) Double checked the sqlite documentation on dropping tables

6) Even went so far as to ensure my .vimrc was set to utf-8

I'm sure I've missed something small here but nothing seems to be working.
Any help would be appreciated!


问:
NGINX regular expression to match location with optional parameter
I like to match location with two optional parameters so it it matches

```<code>/images/my.jpg
/images/my.jpg/200
/images/my.jpg/200/
/images/my.jpg/200/400
/images/my.jpg/200/400/
</code>```

I am using three match groups so that I can get the matched part in $image, $width and $height variables.

I tried this query. It works only if the full location is given but it does not match if one of the parameter is missing

```<code>~ ^/images/(?<img>.+?)/(?<width>\d+)/(?<height>\d+)?$
</code>```

I also tried which does not work at all

```<code>~ ^/images/(?<img>.+?)?(/?<width>\d+)?(/?<height>\d+)?$
</code>```

please help - I have input data here. https://regex101.com/r/qU7tI7/6

nginx config here

```<code> server {
    listen       80;
    server_name  f.myhost.com;
    set $sitename f.myhost.com;

    root $root_folder/myhost.com/files;
    set $path_info "";

    location / {
            root   /var/www/myhost.com/app/api/;
            include conf.d/site.template;
            add_header X-test "root";
    }

    location /files {
            root   /var/www/myhost.com/app/;
            include conf.d/site.template;
    }

    location ~ ^/images/(?<img>[^/]+)(/(?<width>\d*))?(/(?<height>\d*))?$ {
    #       root   /var/www/myhost.com/files/;
            alias   /var/www/myhost.com/app/test/$image;
    #       include conf.d/site.template;
            add_header X-test "test";
            add_header X-width "$width";
            add_header X-height "$height";
            add_header X-name "$image";
            image_filter resize $width -;
            image_filter_jpeg_quality 75;
            image_filter_buffer 8M;

    }

 }
</code>```

答:
Try to try the following regular expression: </p>

<pre class="lang-regex prettyprint-override"><code>/^(\/images\/)([\da-z\.-]+\.[a-z\.]{2,6}|[\d\.]+)\/(\d+)\/(\d+)?$/igm
</code>```

Body:
I like to match location with two optional parameters so it it matches

/images/my.jpg
/images/my.jpg/200
/images/my.jpg/200/
/images/my.jpg/200/400
/images/my.jpg/200/400/

I am using three match groups so that I can get the matched part in $image, $width and $height variables.

I tried this query. It works only if the full location is given but it does not match if one of the parameter is missing

~ ^/images/(?.+?)/(?<width>\d+)/(?<height>\d+)?$

I also tried which does not work at all

~ ^/images/(?.+?)?(/?<width>\d+)?(/?<height>\d+)?$

please help - I have input data here. https://regex101.com/r/qU7tI7/6

nginx config here

 server {
    listen       80;
    server_name  f.myhost.com;
    set $sitename f.myhost.com;

    root $root_folder/myhost.com/files;
    set $path_info "";

    location / {
            root   /var/www/myhost.com/app/api/;
            include conf.d/site.template;
            add_header X-test "root";
    }

    location /files {
            root   /var/www/myhost.com/app/;
            include conf.d/site.template;
    }

    location ~ ^/images/(?[^/]+)(/(?<width>\d*))?(/(?<height>\d*))?$ {
    #       root   /var/www/myhost.com/files/;
            alias   /var/www/myhost.com/app/test/$image;
    #       include conf.d/site.template;
            add_header X-test "test";
            add_header X-width "$width";
            add_header X-height "$height";
            add_header X-name "$image";
            image_filter resize $width -;
            image_filter_jpeg_quality 75;
            image_filter_buffer 8M;

    }

 }

Body:
Try to try the following regular expression:

/^(\/images\/)([\da-z\.-]+\.[a-z\.]{2,6}|[\d\.]+)\/(\d+)\/(\d+)?$/igm


问:
I want to create a layout with background with two different parts upper part will have different background color and bottom part will have different
Also outer view should have rounded corners.

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#ffffff"></solid>
    <corners android:radius="10dp" />
    <stroke
        android:width="@dimen/dimen_1"
        android:color="#1877ee" />
</shape>
</code>```

答:
```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:background="@drawable/round_corners"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:weightSum="2">

    <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_weight="1"
      android:orientation="vertical"
      android:background="@color/upper_one"> //code for layout for adjusting height </LinearLayout>

   <LinearLayout
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:layout_weight="1"
     android:orientation="vertical"
     android:background="@color/lower_color"> //code for layout for adjusting height</LinearLayout>
</LinearLayout>
</code>```

<p>You can fix the height or use wrap content to height and adjust view height inside linearlayouts </p>

Body:
Also outer view should have rounded corners.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#ffffff"></solid>
    <corners android:radius="10dp" />
    <stroke
        android:width="@dimen/dimen_1"
        android:color="#1877ee" />
</shape>

Body:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:background="@drawable/round_corners"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:weightSum="2">

    <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_weight="1"
      android:orientation="vertical"
      android:background="@color/upper_one"> //code for layout for adjusting height </LinearLayout>

   <LinearLayout
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:layout_weight="1"
     android:orientation="vertical"
     android:background="@color/lower_color"> //code for layout for adjusting height</LinearLayout>
</LinearLayout>

You can fix the height or use wrap content to height and adjust view height inside linearlayouts


问:
How to convert one string to another by successive substitutions of characters?
I'm currently trying to design an algorithm that doing such thing:

I got two strings A and B which consist of lowercase characters 'a'-'z'
and I can modify string A using the following operations:

```<code>1. Select two characters 'c1' and 'c2' from the character set ['a'-'z'].
2. Replace all characters 'c1' in string A with character 'c2'.
</code>```

I need to find the minimum number of operations needed to convert string A to string B when possible.

I have 2 ideas that didn't work

```<code>1. Simple range-based for cycle that changes string B and compares it with A.
2. Idea with map<char, int> that does the same.
</code>```

Right now I'm stuck on unit-testing with such situation : 'ab' is transferable to 'ba' in 3 iterations and 'abc' to 'bca' in 4 iterations.
My algorithm is wrong and I need some fresh ideas or working solution.
Can anyone help with this?

Here is some code that shows minimal RepEx:

int Transform(string& A, string& B)
{
    int count = 0;

    if(A.size() != B.size()){
        return -1;
    }

    for(int i = A.size() - 1; i >= 0; i--){
        if(A[i]!=B[i]){
           char rep_elem = A[i];
           ++count;
           replace(A.begin(),A.end(),rep_elem,B[i]);
        }
    }

    if(A != B){
        return -1;
    }

    return count;
}
```

How can I improve this or I should find another ideas?

答:
First of all, don't worry about string operations. Your problem is algorithmic, not textual. You should somehow analyze your data, and only afterwards print your solution.

Start with building a data structure which tells, for each letter, which letter it should be replaced with. Use an array (or std::map<char, char> — it should conceptually be similar, but have different syntax).

If you discover that you should convert a letter to two different letters — error, conversion impossible. Otherwise, count the number of non-trivial cycles in the conversion graph.

The length of your solution will be the number of letters which shouldn't be replaced by themselves plus the number of cycles.

I think the code to implement this would be too long to be helpful.

Body:
I'm currently trying to design an algorithm that doing such thing:

I got two strings A and B which consist of lowercase characters 'a'-'z'
and I can modify string A using the following operations:

1. Select two characters 'c1' and 'c2' from the character set ['a'-'z'].
2. Replace all characters 'c1' in string A with character 'c2'.

I need to find the minimum number of operations needed to convert string A to string B when possible.

I have 2 ideas that didn't work

1. Simple range-based for cycle that changes string B and compares it with A.
2. Idea with map<char, int> that does the same.

Right now I'm stuck on unit-testing with such situation : 'ab' is transferable to 'ba' in 3 iterations and 'abc' to 'bca' in 4 iterations.
My algorithm is wrong and I need some fresh ideas or working solution.
Can anyone help with this?

Here is some code that shows minimal RepEx:

int Transform(string& A, string& B)
{
    int count = 0;

    if(A.size() != B.size()){
        return -1;
    }

    for(int i = A.size() - 1; i >= 0; i--){
        if(A[i]!=B[i]){
           char rep_elem = A[i];
           ++count;
           replace(A.begin(),A.end(),rep_elem,B[i]);
        }
    }

    if(A != B){
        return -1;
    }

    return count;
}

How can I improve this or I should find another ideas?


问:
maxDistance parameter of Query.Near not working
I'm using MongoDB's C# driver and am trying to get Query.Near to work to return homes for sale within 5, 10, 25, or 50 miles of a center point. Here is the query:

```<code>var near = Query.Near("Coordinates", coordinates.Latitude, coordinates.Longitude, find.GetRadiansAway(), false);
    //var near = Query.WithinCircle("Coordinates", coordinates.Latitude, coordinates.Longitude, find.GetRadiansAway(), false);
    var query = Collection().Find(near);
    query.Limit = 1000;
    var listings = query.ToList();
</code>```

I'm dividing the mile radius by 62.1868289 to get the radians and inputting that into the query, however it's returning the same amount of homes for sale regardless of what radians value I pass in. I also tried both setting the spherical param to true and using Query.WithinCircle, however neither works any better.

I'm using the latest C# driver (1.0.0.4098), is this a bug in the C# driver, a bug in MongoDB, or am I missing something here?

Here are what the queries look like:

5 miles away (near):

```<code>db.Listing.find({ "Coordinates" : { "$near" : [39.4812172, -76.6438598], "$maxDistance" : 0.072463768115942032 } });
</code>```

10 miles away (near):

```<code>db.Listing.find({ "Coordinates" : { "$near" : [39.4812172, -76.6438598], "$maxDistance" : 0.14492753623188406 } });
</code>```

5 miles away (spherical near):

```<code>db.Listing.find({ "Coordinates" : { "$nearSphere" : [39.4812172, -76.6438598], "$maxDistance" : 0.0012629451881788331 } });
</code>```

10 miles away (spherical near):

```<code>db.Listing.find({ "Coordinates" : { "$nearSphere" : [39.4812172, -76.6438598], "$maxDistance" : 0.0025258903763576662 } });
</code>```

Here is my test case that returns the same # of results whether I pass in 5 miles away or 25 miles away:

```<code>[Test]
        public void NearTest()
        {
            var isSpherical = true;
            var latitude = 39.4812172;
            var longitude = -76.6438598;
            var milesAway = 5;
            var distance = milesAway / (isSpherical ? 3959.0 : 69.0);

            //search within 5 miles.
            var near = Query.Near("Coordinates", latitude, longitude, distance, isSpherical);
            var collection = ContextWorker.Database.GetCollection<Schemas.Listing.Listing>("Listing");
            var query = collection.Find(near);
            query.Limit = 1000;
            var listings = query.ToList();
            var count1 = listings.Count;
            //Console.WriteLine("query: {0}", query.ToJson());
            Console.WriteLine(count1 + " results returned that are " + milesAway + " miles away");

            //search within 25 miles.
            milesAway = 25;
            distance = milesAway / (isSpherical ? 3959.0 : 69.0);
            near = Query.Near("Coordinates", latitude, longitude, distance, isSpherical);
            query = collection.Find(near);
            query.Limit = 1000;
            listings = query.ToList();
            var count2 = listings.Count;
            //Console.WriteLine("query: {0}", query.ToJson());
            Console.WriteLine(count2 + " results returned that are " + milesAway + " miles away");

            //values should be different.
            Assert.AreNotEqual(count1, count2, "Returned same results for 5 and 25 miles away");
        }

172 results returned that are 5 miles away
172 results returned that are 25 miles away
Test 'Housters.Test.SearchTest.NearTest' failed:
  Returned same results for 5 and 25 miles away
  Expected: not 172
  But was:  172
    SearchTest.cs(68,0): at Housters.Test.SearchTest.NearTest()
</code>```

答:
A good way to determine whether a problem is in the C# driver or in the queries themselves is to get the queries working in the mongo shell first. Then you can write the equivalent query using the C# Query builder. As a final check you can see what the equivalent JSON query would be as follows:

var query = Query.Near(...);
var json = query.ToJson();

Can you provide some sample documents that you think should be returned?

ContentLicense: CC BY-SA 3.0

Body:
I'm using MongoDB's C# driver and am trying to get Query.Near to work to return homes for sale within 5, 10, 25, or 50 miles of a center point. Here is the query:

var near = Query.Near("Coordinates", coordinates.Latitude, coordinates.Longitude, find.GetRadiansAway(), false);
    //var near = Query.WithinCircle("Coordinates", coordinates.Latitude, coordinates.Longitude, find.GetRadiansAway(), false);
    var query = Collection().Find(near);
    query.Limit = 1000;
    var listings = query.ToList();

I'm dividing the mile radius by 62.1868289 to get the radians and inputting that into the query, however it's returning the same amount of homes for sale regardless of what radians value I pass in. I also tried both setting the spherical param to true and using Query.WithinCircle, however neither works any better.

I'm using the latest C# driver (1.0.0.4098), is this a bug in the C# driver, a bug in MongoDB, or am I missing something here?

Here are what the queries look like:

5 miles away (near):

db.Listing.find({ "Coordinates" : { "$near" : [39.4812172, -76.6438598], "$maxDistance" : 0.072463768115942032 } });

10 miles away (near):

db.Listing.find({ "Coordinates" : { "$near" : [39.4812172, -76.6438598], "$maxDistance" : 0.14492753623188406 } });

5 miles away (spherical near):

db.Listing.find({ "Coordinates" : { "$nearSphere" : [39.4812172, -76.6438598], "$maxDistance" : 0.0012629451881788331 } });

10 miles away (spherical near):

db.Listing.find({ "Coordinates" : { "$nearSphere" : [39.4812172, -76.6438598], "$maxDistance" : 0.0025258903763576662 } });

Here is my test case that returns the same # of results whether I pass in 5 miles away or 25 miles away:

[Test]
        public void NearTest()
        {
            var isSpherical = true;
            var latitude = 39.4812172;
            var longitude = -76.6438598;
            var milesAway = 5;
            var distance = milesAway / (isSpherical ? 3959.0 : 69.0);

            //search within 5 miles.
            var near = Query.Near("Coordinates", latitude, longitude, distance, isSpherical);
            var collection = ContextWorker.Database.GetCollection<Schemas.Listing.Listing>("Listing");
            var query = collection.Find(near);
            query.Limit = 1000;
            var listings = query.ToList();
            var count1 = listings.Count;
            //Console.WriteLine("query: {0}", query.ToJson());
            Console.WriteLine(count1 + " results returned that are " + milesAway + " miles away");

            //search within 25 miles.
            milesAway = 25;
            distance = milesAway / (isSpherical ? 3959.0 : 69.0);
            near = Query.Near("Coordinates", latitude, longitude, distance, isSpherical);
            query = collection.Find(near);
            query.Limit = 1000;
            listings = query.ToList();
            var count2 = listings.Count;
            //Console.WriteLine("query: {0}", query.ToJson());
            Console.WriteLine(count2 + " results returned that are " + milesAway + " miles away");

            //values should be different.
            Assert.AreNotEqual(count1, count2, "Returned same results for 5 and 25 miles away");
        }

172 results returned that are 5 miles away
172 results returned that are 25 miles away
Test 'Housters.Test.SearchTest.NearTest' failed:
  Returned same results for 5 and 25 miles away
  Expected: not 172
  But was:  172
    SearchTest.cs(68,0): at Housters.Test.SearchTest.NearTest()


问:
Count is 0 for isnull(table_name) but there are no values for many rows in that table. How to get the correct count?
I am trying to improve the data quality and reporting accuracy by tracing and transforming empty cells in rows of a table. But, to know how many tables have no values, I used
SELECT COUNT() FROM TABLE_NAME WHERE isNull(column_name)*

This query returned 0 count which is an issue for me.
Can you provide me with a solution to overcome this issue?

答:
Null vs '' problem ??</p>

```<code>create table TABLE_NAME(column_name Nullable(String)) Engine=Log;
insert into TABLE_NAME values(''), ('1'), (Null);

SELECT *
FROM TABLE_NAME

┌─column_name─┐
│             │
│ 1           │
│ ᴺᵁᴸᴸ        │
└─────────────┘

SELECT COUNT()
FROM TABLE_NAME
WHERE isNull(column_name)

┌─COUNT()─┐
│       1 │
└─────────┘

SELECT COUNT()
FROM TABLE_NAME
WHERE column_name = ''

┌─COUNT()─┐
│       1 │
└─────────┘

SELECT COUNT()
FROM TABLE_NAME
WHERE coalesce(column_name, '') = ''

┌─COUNT()─┐
│       2 │
└─────────┘
</code>```

Body:
Null vs '' problem ??

create table TABLE_NAME(column_name Nullable(String)) Engine=Log;
insert into TABLE_NAME values(''), ('1'), (Null);

SELECT *
FROM TABLE_NAME

┌─column_name─┐
│             │
│ 1           │
│ ᴺᵁᴸᴸ        │
└─────────────┘

SELECT COUNT()
FROM TABLE_NAME
WHERE isNull(column_name)

┌─COUNT()─┐
│       1 │
└─────────┘

SELECT COUNT()
FROM TABLE_NAME
WHERE column_name = ''

┌─COUNT()─┐
│       1 │
└─────────┘

SELECT COUNT()
FROM TABLE_NAME
WHERE coalesce(column_name, '') = ''

┌─COUNT()─┐
│       2 │
└─────────┘


问:
Is there a way to retrieve the queue / topic name from IDestination?
I can get IDestination from the received IMessage.NMSReplyTo. But I'd like to see its name (for logging). Is there a way?

答: The IDestination interface has a method to fetch the type of Destination that it represents and from there you can cast to the type of Destination which can then allow you to get the name.  For instance an IDestination that return a type of Topic can be cast to an ITopic and from there you can call TopicName to read the destination name.  For temporary destinations you don't really need to know the names in most cases as they are generated and their lifetime is linked to the connection.


问:
From array, generate all distinct, non-empty subarrays, with preserved order
I have an array, with subarrays and need an algorithm that generates all possible distinct combinations of the subarrays. The resultant combinations can be any length. For example, if the Array has 4 subarrays, the first subarray by itself would be a unique and valid resultant combination, as would any other unique combination of any length.

A combination with the sub-array with the same items in a different order would not be considered unique.

let mainArray = [[0.3, 1], [0.5, 2], [0.6, 3], [0.3, 4]]

// Valid resultant combinations:
[[0.3, 1]]
[[0.3, 1], [0.5, 2]]
[[0.3, 1], [0.5, 2], [0.6, 3]]
[[0.3, 1], [0.5, 2], [0.6, 3], [0.3, 4]]
[[0.5, 2]]
[[0.5, 2], [0.6, 3]]
[[0.5, 2], [0.6, 3], [0.3, 4]]
[[0.6, 3]]
[[0.6, 3], [0.3, 4]]
[[0.3, 4]]
[[0.3, 1], [0.6, 3], [0.3, 4]]
[[0.3, 1], [0.5, 2], [0.3, 4]]
[[0.3, 1], [0.3, 4]]
[[0.3, 1], [0.6, 3]]
[[0.5, 2], [0.3, 4]]

// Don’t think I missed any.
```

答:
Here's another approach:

```<code>function combinations(array) {
  const results = [];
  for (let item of array) {
    // take every result that is in the results yet,
    const withItem = results.map(row => [...row, item]);
    // add that result + the current item
    results.push(...withItem);
    // also add just the current item
    results.push([item]);
  }
  return results;
}
</code>```

or like this:

const values = [1,2,3,4];

function combinations(array) {
  return array.reduce((results, item) => [...results, ...results.map(row => [...row, item]), [item]], []);
}

console.log(combinations(values).join("\n"));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper{top:0;max-height:100%!important}</code>```

Body:
Here's another approach:

function combinations(array) {
  const results = [];
  for (let item of array) {
    // take every result that is in the results yet,
    const withItem = results.map(row => [...row, item]);
    // add that result + the current item
    results.push(...withItem);
    // also add just the current item
    results.push([item]);
  }
  return results;
}

or like this:

const values = [1,2,3,4];

function combinations(array) {
  return array.reduce((results, item) => [...results, ...results.map(row => [...row, item]), [item]], []);
}

console.log(combinations(values).join("\n"));

.as-console-wrapper{top:0;max-height:100%!important}


问:
Couchbase Lite pull replication fails with error in a sample Couchbase Mobile End to End testing project
I am getting started with Couchbase Mobile. The feature that I am most interested (for now) is PULL replication (keep data on mobile in sync with backend database).

I followed the steps described in Using Docker to develop with Couchbase Mobile and have got the Couchbase server (enterprise-6.5.0) and sync gateway (2.7.0-enterprise) deployed locally. I have added the beer-sample database (has ~8400 documents) and now I'm trying to replicate it on an android application. I customized the Userprofile Couchbase Mobile Android project and I pointed it to my local sync-gateway. I have a piece of code to replicate like below :

```<code>  public static void startPullReplication() {
    Log.i("Pull", "Start pull beer-sample");
    URI url = null;
    try {
      url = new URI(String.format("%s/%s", "ws://10.0.1.7:4984", beerSampleDbName));
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }

    ReplicatorConfiguration config =
        new ReplicatorConfiguration(beerSampleDatabase, new URLEndpoint(url)); // <1>
    config.setReplicatorType(ReplicatorConfiguration.ReplicatorType.PULL); // <2>
    config.setContinuous(true); // <3>
    config.setAuthenticator(new BasicAuthenticator("admin", "password")); // <4>
    //    config.setChannels(Arrays.asList("channel." + "admin")); // <5>

    replicator = new Replicator(config);
    replicatorListenerToken =
        replicator.addChangeListener(
            new ReplicatorChangeListener() {
              @Override
              public void changed(ReplicatorChange change) {
                Log.i("Pull", "Changed pull beer sample : " + change.getStatus());
                if (change
                    .getReplicator()
                    .getStatus()
                    .getActivityLevel()
                    .equals(Replicator.ActivityLevel.IDLE)) {
                  Log.i("Replication Comp Log", "Scheduler Completed");
                }
                if (change
                        .getReplicator()
                        .getStatus()
                        .getActivityLevel()
                        .equals(Replicator.ActivityLevel.STOPPED)
                    || change
                        .getReplicator()
                        .getStatus()
                        .getActivityLevel()
                        .equals(Replicator.ActivityLevel.OFFLINE)) {
                  Log.i("Rep Scheduler  Log", "ReplicationTag Stopped");
                }
              }
            });
    replicator.start();

    Log.i("Pull", "Replication beer-sample started");
  }
</code>```

and listen to changes in the db like below :

```<code>
  private void registerForDatabaseChanges() {
    beerSampleListenerToken =
        beerSampleDatabase.addChangeListener(
            new DatabaseChangeListener() {
              Integer i=0;
              @Override
              public void changed(@NonNull DatabaseChange change) {
                Log.i("DatabaseChangeEvent", String.valueOf(i));
                i++;
                for (String docId : change.getDocumentIDs()) {
                  Document doc = beerSampleDatabase.getDocument(docId);
                  if (doc != null) {
                    Log.i("DatabaseChangeEvent", doc.getId() + ": Document was added/updated");
                  } else {
                    Log.i("DatabaseChangeEvent", docId + "Document was deleted");
                  }
                }
              }
            });
  }

</code>```

Now when I run the app I am getting the following logs.

```<code>2020-02-11 15:44:46.420 22513-22513/com.cbmob.testapp W/CouchbaseLite/DATABASE: Database.log.getFile().getConfig() is null, meaning file logging is disabled.  Log files required for product support are not being generated.
2020-02-11 15:44:46.615 22513-22545/com.cbmob.testapp D/OpenGLRenderer: HWUI GL Pipeline
2020-02-11 15:44:46.744 22513-22545/com.cbmob.testapp I/zygote: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
2020-02-11 15:44:46.744 22513-22545/com.cbmob.testapp I/OpenGLRenderer: Initialized EGL, version 1.4
2020-02-11 15:44:46.744 22513-22545/com.cbmob.testapp D/OpenGLRenderer: Swap behavior 1
2020-02-11 15:44:46.745 22513-22545/com.cbmob.testapp W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
2020-02-11 15:44:46.745 22513-22545/com.cbmob.testapp D/OpenGLRenderer: Swap behavior 0
2020-02-11 15:44:46.752 22513-22545/com.cbmob.testapp D/EGL_emulation: eglCreateContext: 0xa9f30d40: maj 3 min 0 rcv 3
2020-02-11 15:44:46.765 22513-22545/com.cbmob.testapp D/EGL_emulation: eglMakeCurrent: 0xa9f30d40: ver 3 0 (tinfo 0x9f7bf880)
2020-02-11 15:44:46.976 22513-22545/com.cbmob.testapp D/EGL_emulation: eglMakeCurrent: 0xa9f30d40: ver 3 0 (tinfo 0x9f7bf880)

2020-02-11 15:44:56.458 22513-22513/com.cbmob.testapp I/Pull: Start pull beer-sample
2020-02-11 15:44:56.480 22513-22576/com.cbmob.testapp W/CouchbaseLite/NETWORK: C4Socket.open() socket -> 2852069288
2020-02-11 15:44:56.480 22513-22576/com.cbmob.testapp W/CouchbaseLite/NETWORK: C4Socket.open() clazz -> com.couchbase.lite.internal.replicator.CBLWebSocket
2020-02-11 15:44:56.482 22513-22513/com.cbmob.testapp I/Pull: Replication beer-sample started
2020-02-11 15:44:56.497 22513-22513/com.cbmob.testapp I/Pull: Changed pull beer sample : Status{activityLevel=CONNECTING, progress=Progress{completed=0, total=0}, error=null}
2020-02-11 15:44:56.519 22513-22576/com.cbmob.testapp D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2020-02-11 15:44:56.528 22513-22576/com.cbmob.testapp E/CouchbaseLite/NETWORK: CBLWebSocket.socket_open()
2020-02-11 15:44:56.582 22513-22576/com.cbmob.testapp W/CouchbaseLite/NETWORK: C4Socket.write() handle -> 2852069288
2020-02-11 15:44:56.586 22513-22576/com.cbmob.testapp W/CouchbaseLite/NETWORK: completedWrite(long) handle -> 2852069288, byteCount -> 68
2020-02-11 15:44:56.591 22513-22513/com.cbmob.testapp I/Pull: Changed pull beer sample : Status{activityLevel=BUSY, progress=Progress{completed=0, total=0}, error=null}
2020-02-11 15:44:56.591 22513-22576/com.cbmob.testapp W/CouchbaseLite/NETWORK: C4Socket.write() handle -> 2852069288
2020-02-11 15:44:56.592 22513-22576/com.cbmob.testapp W/CouchbaseLite/NETWORK: completedWrite(long) handle -> 2852069288, byteCount -> 121
2020-02-11 15:44:56.605 22513-22577/com.cbmob.testapp W/CouchbaseLite/NETWORK: C4Socket.completedReceive() handle -> 2852069288
2020-02-11 15:44:56.608 22513-22577/com.cbmob.testapp I/chatty: uid=10086(com.cbmob.testapp) Thread-9 identical 1 line
2020-02-11 15:44:56.612 22513-22577/com.cbmob.testapp W/CouchbaseLite/NETWORK: C4Socket.completedReceive() handle -> 2852069288
2020-02-11 15:44:56.627 22513-22513/com.cbmob.testapp I/Pull: Changed pull beer sample : Status{activityLevel=IDLE, progress=Progress{completed=0, total=0}, error=null}
2020-02-11 15:44:56.628 22513-22513/com.cbmob.testapp E/Replication Comp Log: Scheduler Completed
</code>```

Clearly the document changes in the db are not being logged. From this, I am assuming that the replication is not at all happening. I am not sure how to go about debugging this. If anyone has any pointers on how this can be debugged, I would appreciate it. If needed, I could post the sync gateway logs.

If anyone has any links to any blogspots or projects which explains how to get all the pieces working together, kindly share that.

Looking forward to hearing back from people.

答:
After a painful journey going through this whole process and getting no clue from the debug logs of emulator, I tried to run the app on a real device and it logged a error log statement which said something to the effect of not allowed to communicate with the network (I lost the exact log statement). After digging into that issue, I learnt that I was targeting API 28 and as documented here, for API >= 28, the default value for cleartextTrafficPermitted is false. Setting that to true fixed the issue.

I hope this helps someone save time.

Body:
I am getting started with Couchbase Mobile. The feature that I am most interested (for now) is PULL replication (keep data on mobile in sync with backend database).

I followed the steps described in Using Docker to develop with Couchbase Mobile and have got the Couchbase server (enterprise-6.5.0) and sync gateway (2.7.0-enterprise) deployed locally. I have added the beer-sample database (has ~8400 documents) and now I'm trying to replicate it on an android application. I customized the Userprofile Couchbase Mobile Android project and I pointed it to my local sync-gateway. I have a piece of code to replicate like below :

  public static void startPullReplication() {
    Log.i("Pull", "Start pull beer-sample");
    URI url = null;
    try {
      url = new URI(String.format("%s/%s", "ws://10.0.1.7:4984", beerSampleDbName));
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }

    ReplicatorConfiguration config =
        new ReplicatorConfiguration(beerSampleDatabase, new URLEndpoint(url)); // <1>
    config.setReplicatorType(ReplicatorConfiguration.ReplicatorType.PULL); // <2>
    config.setContinuous(true); // <3>
    config.setAuthenticator(new BasicAuthenticator("admin", "password")); // <4>
    //    config.setChannels(Arrays.asList("channel." + "admin")); // <5>

    replicator = new Replicator(config);
    replicatorListenerToken =
        replicator.addChangeListener(
            new ReplicatorChangeListener() {
              @Override
              public void changed(ReplicatorChange change) {
                Log.i("Pull", "Changed pull beer sample : " + change.getStatus());
                if (change
                    .getReplicator()
                    .getStatus()
                    .getActivityLevel()
                    .equals(Replicator.ActivityLevel.IDLE)) {
                  Log.i("Replication Comp Log", "Scheduler Completed");
                }
                if (change
                        .getReplicator()
                        .getStatus()
                        .getActivityLevel()
                        .equals(Replicator.ActivityLevel.STOPPED)
                    || change
                        .getReplicator()
                        .getStatus()
                        .getActivityLevel()
                        .equals(Replicator.ActivityLevel.OFFLINE)) {
                  Log.i("Rep Scheduler  Log", "ReplicationTag Stopped");
                }
              }
            });
    replicator.start();

    Log.i("Pull", "Replication beer-sample started");
  }

and listen to changes in the db like below :

  private void registerForDatabaseChanges() {
    beerSampleListenerToken =
        beerSampleDatabase.addChangeListener(
            new DatabaseChangeListener() {
              Integer i=0;
              @Override
              public void changed(@NonNull DatabaseChange change) {
                Log.i("DatabaseChangeEvent", String.valueOf(i));
                i++;
                for (String docId : change.getDocumentIDs()) {
                  Document doc = beerSampleDatabase.getDocument(docId);
                  if (doc != null) {
                    Log.i("DatabaseChangeEvent", doc.getId() + ": Document was added/updated");
                  } else {
                    Log.i("DatabaseChangeEvent", docId + "Document was deleted");
                  }
                }
              }
            });
  }

Now when I run the app I am getting the following logs.

2020-02-11 15:44:46.420 22513-22513/com.cbmob.testapp W/CouchbaseLite/DATABASE: Database.log.getFile().getConfig() is null, meaning file logging is disabled.  Log files required for product support are not being generated.
2020-02-11 15:44:46.615 22513-22545/com.cbmob.testapp D/OpenGLRenderer: HWUI GL Pipeline
2020-02-11 15:44:46.744 22513-22545/com.cbmob.testapp I/zygote: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
2020-02-11 15:44:46.744 22513-22545/com.cbmob.testapp I/OpenGLRenderer: Initialized EGL, version 1.4
2020-02-11 15:44:46.744 22513-22545/com.cbmob.testapp D/OpenGLRenderer: Swap behavior 1
2020-02-11 15:44:46.745 22513-22545/com.cbmob.testapp W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
2020-02-11 15:44:46.745 22513-22545/com.cbmob.testapp D/OpenGLRenderer: Swap behavior 0
2020-02-11 15:44:46.752 22513-22545/com.cbmob.testapp D/EGL_emulation: eglCreateContext: 0xa9f30d40: maj 3 min 0 rcv 3
2020-02-11 15:44:46.765 22513-22545/com.cbmob.testapp D/EGL_emulation: eglMakeCurrent: 0xa9f30d40: ver 3 0 (tinfo 0x9f7bf880)
2020-02-11 15:44:46.976 22513-22545/com.cbmob.testapp D/EGL_emulation: eglMakeCurrent: 0xa9f30d40: ver 3 0 (tinfo 0x9f7bf880)

2020-02-11 15:44:56.458 22513-22513/com.cbmob.testapp I/Pull: Start pull beer-sample
2020-02-11 15:44:56.480 22513-22576/com.cbmob.testapp W/CouchbaseLite/NETWORK: C4Socket.open() socket -> 2852069288
2020-02-11 15:44:56.480 22513-22576/com.cbmob.testapp W/CouchbaseLite/NETWORK: C4Socket.open() clazz -> com.couchbase.lite.internal.replicator.CBLWebSocket
2020-02-11 15:44:56.482 22513-22513/com.cbmob.testapp I/Pull: Replication beer-sample started
2020-02-11 15:44:56.497 22513-22513/com.cbmob.testapp I/Pull: Changed pull beer sample : Status{activityLevel=CONNECTING, progress=Progress{completed=0, total=0}, error=null}
2020-02-11 15:44:56.519 22513-22576/com.cbmob.testapp D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2020-02-11 15:44:56.528 22513-22576/com.cbmob.testapp E/CouchbaseLite/NETWORK: CBLWebSocket.socket_open()
2020-02-11 15:44:56.582 22513-22576/com.cbmob.testapp W/CouchbaseLite/NETWORK: C4Socket.write() handle -> 2852069288
2020-02-11 15:44:56.586 22513-22576/com.cbmob.testapp W/CouchbaseLite/NETWORK: completedWrite(long) handle -> 2852069288, byteCount -> 68
2020-02-11 15:44:56.591 22513-22513/com.cbmob.testapp I/Pull: Changed pull beer sample : Status{activityLevel=BUSY, progress=Progress{completed=0, total=0}, error=null}
2020-02-11 15:44:56.591 22513-22576/com.cbmob.testapp W/CouchbaseLite/NETWORK: C4Socket.write() handle -> 2852069288
2020-02-11 15:44:56.592 22513-22576/com.cbmob.testapp W/CouchbaseLite/NETWORK: completedWrite(long) handle -> 2852069288, byteCount -> 121
2020-02-11 15:44:56.605 22513-22577/com.cbmob.testapp W/CouchbaseLite/NETWORK: C4Socket.completedReceive() handle -> 2852069288
2020-02-11 15:44:56.608 22513-22577/com.cbmob.testapp I/chatty: uid=10086(com.cbmob.testapp) Thread-9 identical 1 line
2020-02-11 15:44:56.612 22513-22577/com.cbmob.testapp W/CouchbaseLite/NETWORK: C4Socket.completedReceive() handle -> 2852069288
2020-02-11 15:44:56.627 22513-22513/com.cbmob.testapp I/Pull: Changed pull beer sample : Status{activityLevel=IDLE, progress=Progress{completed=0, total=0}, error=null}
2020-02-11 15:44:56.628 22513-22513/com.cbmob.testapp E/Replication Comp Log: Scheduler Completed

Clearly the document changes in the db are not being logged. From this, I am assuming that the replication is not at all happening. I am not sure how to go about debugging this. If anyone has any pointers on how this can be debugged, I would appreciate it. If needed, I could post the sync gateway logs.

If anyone has any links to any blogspots or projects which explains how to get all the pieces working together, kindly share that.

Looking forward to hearing back from people.


问:
python opens text file with a space between every character
Whenever I try to open a .csv file with the python command
fread = open('input.csv', 'r')
it always opens the file with spaces between every single character.  I'm guessing it's something wrong with the text file because I can open other text files with the same command and they are loaded correctly.  Does anyone know why a text file would load like this in python?

Thanks.

Update

Ok, I got it with the help of Jarret Hardie's post

this is the code that I used to convert the file to ascii

```<code>fread = open('input.csv', 'rb').read()
mytext = fread.decode('utf-16')
mytext = mytext.encode('ascii', 'ignore')
fwrite = open('input-ascii.csv', 'wb')
fwrite.write(mytext)
</code>```

Thanks!

答:
The post by recursive is probably right... the contents of the file are likely encoded with a multi-byte charset. If this is, in fact, the case you can likely read the file in python itself without having to convert it first outside of python.

Try something like:

```<code>fread = open('input.csv', 'rb').read()
mytext = fread.decode('utf-16')
</code>```

The 'b' flag ensures the file is read as binary data. You'll need to know (or guess) the original encoding... in this example, I've used utf-16, but YMMV. This will convert the file to unicode. If you truly have a file with multi-byte chars, I don't recommend converting it to ascii as you may end up losing a lot of the characters in the process.

EDIT: Thanks for uploading the file. There are two bytes at the front of the file which indicates that it does, indeed, use a wide charset. If you're curious, open the file in a hex editor as some have suggested... you'll see something in the text version like 'I.D.|.' (etc). The dot is the extra byte for each char.

The code snippet above seems to work on my machine with that file.

Body:
Whenever I try to open a .csv file with the python command
fread = open('input.csv', 'r')
it always opens the file with spaces between every single character.  I'm guessing it's something wrong with the text file because I can open other text files with the same command and they are loaded correctly.  Does anyone know why a text file would load like this in python?

Thanks.

Update

Ok, I got it with the help of Jarret Hardie's post

this is the code that I used to convert the file to ascii

fread = open('input.csv', 'rb').read()
mytext = fread.decode('utf-16')
mytext = mytext.encode('ascii', 'ignore')
fwrite = open('input-ascii.csv', 'wb')
fwrite.write(mytext)

Thanks!

LastEditorDisplayName: ΤΖΩΤΖΙΟΥ

Body:
The post by recursive is probably right... the contents of the file are likely encoded with a multi-byte charset. If this is, in fact, the case you can likely read the file in python itself without having to convert it first outside of python.

Try something like:

fread = open('input.csv', 'rb').read()
mytext = fread.decode('utf-16')

The 'b' flag ensures the file is read as binary data. You'll need to know (or guess) the original encoding... in this example, I've used utf-16, but YMMV. This will convert the file to unicode. If you truly have a file with multi-byte chars, I don't recommend converting it to ascii as you may end up losing a lot of the characters in the process.

EDIT: Thanks for uploading the file. There are two bytes at the front of the file which indicates that it does, indeed, use a wide charset. If you're curious, open the file in a hex editor as some have suggested... you'll see something in the text version like 'I.D.|.' (etc). The dot is the extra byte for each char.

The code snippet above seems to work on my machine with that file.

OwnerDisplayName: Jarret Hardie

LastEditorDisplayName: Jarret Hardie


问:
libxml2 get inner (X)HTML
I have some sample XHTML data, like this:

```<code><html>
    <head>
        <style type="text/css">
            ..snip
        </style>
        <script type="text/javascript" src="http://code.jquery.com/mobile/1.0a4.1/jquery.mobile-1.0a4.1.js"></script>
    </head>
    <body>
        <div id="contentA">
             This is sample content <b> that is bolded as well </b>
        </div>
    </body>
</html>
</code>```

Now, what I need to do, is using an xmlNode *, get the inner HTML of the div contentA. I have the xmlNode * for it, but how can I get the innerXML of that? I looked at content, but that only returns This is sample content and not the xml in the bold tags. I looked into jQuery for this, but due to limitations on Apple and JavaScript, I cannot use jQuery to get the innerXML of that node.

On another note, Is there another library I should be using to get the inner XML? I looked into TBXML, but that had the same problem.

答:
The content of the div node is not a single text string.  It probably consists of:

A text node containing This is sample content (with the preceding new line).

an element node with a tag name of b

A text node containing the trailing new line and the indentation up to the div's closing tag.

The element node for the ... will have the text content that is bolded as well.

To get all the text in the div as one string, you'll need to recursively descend through the entire tree of child nodes looking for text content.

Title: libxml2 get inner (X)HTML

Body:
I have some sample XHTML data, like this:

             This is sample content  that is bolded as well

Now, what I need to do, is using an xmlNode *, get the inner HTML of the div contentA. I have the xmlNode * for it, but how can I get the innerXML of that? I looked at content, but that only returns This is sample content and not the xml in the bold tags. I looked into jQuery for this, but due to limitations on Apple and JavaScript, I cannot use jQuery to get the innerXML of that node.

On another note, Is there another library I should be using to get the inner XML? I looked into TBXML, but that had the same problem.

Body:
The content of the div node is not a single text string.  It probably consists of:

A text node containing This is sample content (with the preceding new line).

an element node with a tag name of b

A text node containing the trailing new line and the indentation up to the div's closing tag.

The element node for the <b>...</b> will have the text content that is bolded as well.

To get all the text in the div as one string, you'll need to recursively descend through the entire tree of child nodes looking for text content.


问:
Finding the corner points in a spatial mesh
So I've been working on some code to get the floor from a point-cloud mesh. Untill now, I've achieved to get the triangles that make up this floor mesh, but now I want to create a flat plane to cover those points to represent a flat floor.

Floor mesh

Oke, just to make it a bit more clear. Right now I've got this Mesh. (triangles, vertices and normals). I want to create a plane or something simular to cover this mesh to represent the floor (since this floor is not as flat as an actual floor should be).

It should create 1 or multiple planes to cover the encapsulated area

I do know of a library to use that calculates what an area should be based on some key-points. So if I would be able to get for example these points from the mesh (See below) it would create the following objects (See further below). This would also give me the desired result.

below
further below

If someone has done something simular before or has an idea of how to solve this issue, I would be very gratefull :).

(I'm using Unity and C# btw)

One last thing to note about this mesh is sadly that not all triangles connect very well to each other. So there are points in the middle of the mesh that stick out a little bit. This makes it harder to check if a triangle is on a corner.

答:
If I understand your problem correctly, you may have actually done too much work in creating your point cloud mesh, but it's cool anyway.

If all you want is a flat plane where the floor is, what you have is an approximation problem; one that can be as simple or as complex as you want really.

The simplest route:
You know it's the floor in this case, so you can assume the normal vec is up (i.e. Vector3.up), so step 1 would be to estimate the z coordinate of your plane. The easiest way to do this would be to average all or some of the z coordinates of the points in your point cloud.

Now you need to the find the x and y coordinates for the corners of your plane. The absolute simplest solution, is to assume that most rooms are rectangular and so is the one you're working with. Then you can find the farthest point in any direction (x and y directions) and create a rectangular plane using those points.

This of course does not account for rotation of the floor (you're probably not standing looking perfectly perpendicular to a wall) which requires quite a bit more thinking.


问:
Is it possible to share rpc endpoint for azure blockchain service with restricted access?
I want to create ERC20 token on azure blockchain service, and want to allow publicly sending ERC20 tokens and checking balances using metamask. However, I want to allow only sending ERC20 tokens, but don't want to allow other administrative operations publicly.<br>
Is it possible to share rpc with such a restricted access right? </p>

答:
You can have only one rpc port and every client connecting to this rpc will have the same right.

You can use IPC to do your administrative operation.

Body:
I want to create ERC20 token on azure blockchain service, and want to allow publicly sending ERC20 tokens and checking balances using metamask. However, I want to allow only sending ERC20 tokens, but don't want to allow other administrative operations publicly.

Is it possible to share rpc with such a restricted access right?


问:
Align element on the same level as v-card-title in vuetify
Is it possible to align element on the same height as the v-card-title in the card component of vuetify?
Currentl when using class="float-right" the element goes to the right but it is line below the title. I would like for it to be at the same level.
Here is the codepen:

new Vue({
  el: '#app',
  vuetify: new Vuetify(),

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="app">
  <v-app id="inspire">
    <v-card
      class="mx-auto"
    width="400"
    >
<!--  Top row -->
    <v-card-title>Cafe Badilico</v-card-title>
      <button class="float-right">click me</button>
<!--     End of top row -->

<!-- Put components here -->

    <v-card-title >
     News
    </v-card-title>

<v-list-item dense
        >

          <v-list-item-avatar>
             <v-avatar color="indigo" size="36">
      <span class="white--text headline">36</span>
    </v-avatar>
          </v-list-item-avatar>
          <v-list-item-content>
            <v-list-item-title>Header</v-list-item-title>
            <v-list-item-subtitle>Subheader</v-list-item-subtitle>
            <v-list-item-subtitle>2019-05-31</v-list-item-subtitle>
          </v-list-item-content>
        </v-list-item>
   <v-divider></v-divider>
   <v-card-title >
     News
   </v-card-title>

<v-list-item dense>

          <v-list-item-avatar>
             <v-avatar color="indigo" size="36">
      <span class="white--text headline">36</span>
    </v-avatar>
          </v-list-item-avatar>
          <v-list-item-content>
            <v-list-item-title >Header</v-list-item-title>

            <v-list-item-subtitle >Subheader</v-list-item-subtitle>
            <v-list-item-subtitle >2019-05-31</v-list-item-subtitle>
          </v-list-item-content>
        </v-list-item>

    </v-card>
  </v-app>
</div></code>```

答:
You can move the button into the title and use the v-spacer component:

```<code><v-card-title>
  Cafe Badilico
  <v-spacer></v-spacer>
  <button>click me</button>
</v-card-title>
</code>```

https://codepen.io/El_Matella/pen/mdJrKNE

If you don't want it to be part of the title component, you can also use a flex container:

```<code><div class="d-flex align-center justify-space-between">
  <v-card-title>
    Cafe Badilico
  </v-card-title>
  <button>click me</button>
</div>
</code>```

https://codepen.io/El_Matella/pen/ZEGpjEq

Body:
Is it possible to align element on the same height as the v-card-title in the card component of vuetify?
Currentl when using class="float-right" the element goes to the right but it is line below the title. I would like for it to be at the same level.
Here is the codepen:

new Vue({
  el: '#app',
  vuetify: new Vuetify(),

})

  <v-app id="inspire">
    <v-card
      class="mx-auto"
    width="400"
    >

    <v-card-title>Cafe Badilico</v-card-title>
      <button class="float-right">click me</button>

    <v-card-title >
     News
    </v-card-title>

<v-list-item dense
        >

          <v-list-item-avatar>
             <v-avatar color="indigo" size="36">
      36
    </v-avatar>
          </v-list-item-avatar>
          <v-list-item-content>
            <v-list-item-title>Header</v-list-item-title>
            <v-list-item-subtitle>Subheader</v-list-item-subtitle>
            <v-list-item-subtitle>2019-05-31</v-list-item-subtitle>
          </v-list-item-content>
        </v-list-item>
   <v-divider></v-divider>
   <v-card-title >
     News
   </v-card-title>

<v-list-item dense>

          <v-list-item-avatar>
             <v-avatar color="indigo" size="36">
      36
    </v-avatar>
          </v-list-item-avatar>
          <v-list-item-content>
            <v-list-item-title >Header</v-list-item-title>

            <v-list-item-subtitle >Subheader</v-list-item-subtitle>
            <v-list-item-subtitle >2019-05-31</v-list-item-subtitle>
          </v-list-item-content>
        </v-list-item>

    </v-card>
  </v-app>

Body:
You can move the button into the title and use the v-spacer component:

<v-card-title>
  Cafe Badilico
  <v-spacer></v-spacer>
  <button>click me</button>
</v-card-title>

https://codepen.io/El_Matella/pen/mdJrKNE

If you don't want it to be part of the title component, you can also use a flex container:

<div class="d-flex align-center justify-space-between">
  <v-card-title>
    Cafe Badilico
  </v-card-title>
  <button>click me</button>
</div>

https://codepen.io/El_Matella/pen/ZEGpjEq


问:
Authenticate the Test User { "error_type": "OAuthException", "code": 400, "error_message": "Invalid platform app" }
I'm trying to recover the access token via the Instagram Basic Display API but when trying to authenticate the test user I get this error:

```<code>{
    "error_type": "OAuthException",
    "code": 400,
    "error_message": "Invalid platform app"
}
</code>```

I expect to see the app authorization screen

答: Passing parameters through the body and in x-www-form-urlencoded works fine as you can see in the picture below

Body:
I'm trying to recover the access token via the Instagram Basic Display API but when trying to authenticate the test user I get this error:

{
    "error_type": "OAuthException",
    "code": 400,
    "error_message": "Invalid platform app"
}

I expect to see the app authorization screen


问:
Type deduction for variable declared in lambda's capture
In this snippet I am declaring a variable i inside the lambda's capture.

```<code>int main()
{
    vector<int> vec;

    // Pushing 0-99 numbers to vector
    std::generate_n(std::back_inserter(vec), 100, [i = 0]() mutable { return i++; });

    return 0;
}
</code>```

As one can see, there is no type stated anywhere for i.

As far as I know, I can write the equivalent functionality in this way:

```<code>int main()
{
    vector<int> vec;

    // Pushing 0-99 numbers to vector
    std::generate_n(std::back_inserter(vec), 100, [](){
             static int i = 0;
             return i++; });

    return 0;
}
</code>```

How does the compiler know the type of i in the first example? Is it deduced from the operation I perform on it (++) ? Does it know that it is int because of the container?

There are no complaints when compiling with GCC with -std=c++14 and -std=c++17.
Nevertheless, if I compile with -std=c++11 I get the following warning:

```<code>lambda_test.cpp: In function ‘int main()’:
lambda_test.cpp:24:51: warning: lambda capture initializers only available with -std=c++14 or -std=gnu++14
  std::generate_n(std::back_inserter(first), 100, [i = 0]() mutable { return i++; });
                                                   ^
</code>```

MORE: Given the comments, I tried to see a difference on what the compiler produces for c++11 and 14, but it generates the same code:
https://cppinsights.io/s/43411e6f

答:
As the error says, you must activate C++14 for lambda capture initializer to work since it was added in C++14.

As far as I know, I can write the equivalent functionality in this way:

No, static storage is functionally different. With capture you can copy the lambda and it will copy the state of the captures. With static variables each lambda access the same global.

How does the compiler know the type of i in the first example? Is it deduced from the operation I perform on it (++) ? Does it know that it is int because of the container?

No, since many many types has the ++ operator.

The compiler simply use the initializer to deduce the type. You can see it as if there was a hidden auto there:

```<code>std::generate_n(std::back_inserter(vec), 100, [/* auto */ i = 0]() mutable { return i++; });
</code>```

The literal 0 is of type int. So i is an int.

You could technically do this too:

```<code>std::generate_n(std::back_inserter(vec), 100, [/* auto */ i = 0ull]() mutable { return i++; });
</code>```

Then i has the type unsigned long long, since the literal 0ull is of that type.

Body:
In this snippet I am declaring a variable i inside the lambda's capture.

int main()
{
    vector<int> vec;

    // Pushing 0-99 numbers to vector
    std::generate_n(std::back_inserter(vec), 100, [i = 0]() mutable { return i++; });

    return 0;
}

As one can see, there is no type stated anywhere for i.

As far as I know, I can write the equivalent functionality in this way:

int main()
{
    vector<int> vec;

    // Pushing 0-99 numbers to vector
    std::generate_n(std::back_inserter(vec), 100, [](){
             static int i = 0;
             return i++; });

    return 0;
}

How does the compiler know the type of i in the first example? Is it deduced from the operation I perform on it (++) ? Does it know that it is int because of the container?

There are no complaints when compiling with GCC with -std=c++14 and -std=c++17.
Nevertheless, if I compile with -std=c++11 I get the following warning:

lambda_test.cpp: In function ‘int main()’:
lambda_test.cpp:24:51: warning: lambda capture initializers only available with -std=c++14 or -std=gnu++14
  std::generate_n(std::back_inserter(first), 100, [i = 0]() mutable { return i++; });
                                                   ^

MORE: Given the comments, I tried to see a difference on what the compiler produces for c++11 and 14, but it generates the same code:
https://cppinsights.io/s/43411e6f

Body:
As the error says, you must activate C++14 for lambda capture initializer to work since it was added in C++14.

As far as I know, I can write the equivalent functionality in this way:

No, static storage is functionally different. With capture you can copy the lambda and it will copy the state of the captures. With static variables each lambda access the same global.

How does the compiler know the type of i in the first example? Is it deduced from the operation I perform on it (++) ? Does it know that it is int because of the container?

No, since many many types has the ++ operator.

The compiler simply use the initializer to deduce the type. You can see it as if there was a hidden auto there:

std::generate_n(std::back_inserter(vec), 100, [/* auto */ i = 0]() mutable { return i++; });

The literal 0 is of type int. So i is an int.

You could technically do this too:

std::generate_n(std::back_inserter(vec), 100, [/* auto */ i = 0ull]() mutable { return i++; });

Then i has the type unsigned long long, since the literal 0ull is of that type.


问:
Resizing base64 Images
I have multiple Images - saved as Base64 Strings and now i want to resize these images to get thumbnails of them...

Best would be using Javascript (Node-Server) to resize them, but it would be possible to resize them with php, too.

Thanks in advance

答:
Maybe you just can use a lib to handle that. Try WideImage. I have used it and worked nicely.

Example:

```<code>$image = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $req->image));

$thumbnail = WideImage::load($image)
  ->resize(300, 300, 'inside')
  ->crop('center', 'center', 300, 300);
</code>```

Library Documentation: http://wideimage.sourceforge.net/

Title: Resizing base64 Images

Body:
Maybe you just can use a lib to handle that. Try WideImage. I have used it and worked nicely.

Example:

$image = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $req->image));

$thumbnail = WideImage::load($image)
  ->resize(300, 300, 'inside')
  ->crop('center', 'center', 300, 300);

Library Documentation: http://wideimage.sourceforge.net/


问:
Text trimming in Windows Phone 7
can somebody explain me how do I use the code in here http://nerdplusart.com/texttrimming-textblock-for-silverlight to trim texts?

I've been searching for a solution to trim my texts to a determined lenght and add an ellipsis to the end, but I only find links to that code that I don't know how to use!

Thank you very much

答:
You just use it as you would and instead of a TextBlock.

So (assuming you save that source as is into your app):

```<code><PixelLab:DynamicTextBlock Text="some really really really really really long text that won't fit on a line" />
</code>```

And be sure to set the appropriate namepace:

```<code>xmlns:PixelLab="clr-namespace:PixelLab"
</code>```

Title: Text trimming in Windows Phone 7

Body:
You just use it as you would and instead of a TextBlock.

So (assuming you save that source as is into your app):

<PixelLab:DynamicTextBlock Text="some really really really really really long text that won't fit on a line" />

And be sure to set the appropriate namepace:

xmlns:PixelLab="clr-namespace:PixelLab"


问:
Teradata stored procedure
i am planning to write stored procedure (teradata) with bunch of update statements in it .i want to capture number of rows updated for each update statement into an audit table .so can some one help me with SQL?

答:
You can use the ACTIVITY_COUNT variable within your stored procedure.  For example:

   UPDATE MyTable
   SET col1 = 'val';

   INSERT INTO MyAuditTable (ActivityCount)
   VALUES (:ACTIVITY_COUNT);
```

Keep in mind this variable is only accessible within your SP.

TD Manual

Title: Teradata stored procedure

Body:
You can use the ACTIVITY_COUNT variable within your stored procedure.  For example:

   UPDATE MyTable
   SET col1 = 'val';

   INSERT INTO MyAuditTable (ActivityCount)
   VALUES (:ACTIVITY_COUNT);

Keep in mind this variable is only accessible within your SP.

TD Manual


问:
How can I make a validation that depends on the value of another field with the StreamTransform Flutter
The fields are a select and the other is a field of identity card. It depends on what you select the field has a different validation.
I get the value of the select but when validating the field, it doesn't take the value

final _idController=StreamController<String>.broadcast();
String type = '';
  // The controller to stream the final output to the required StreamBuilder
  final _typeId = BehaviorSubject<String>();
  Stream<String> get typeId => _typeId.stream;

  // The controller to receive the input form the app elements
  final _query = StreamController<String>();
  Sink<String> get query => _query.sink;
  Stream<String> get result => _query.stream;

  // The business logic
  OtherChargesController() {
   result.listen((newType) {
      // Listen for incoming input
      type = newType; // Process the required data
      _typeId.sink.add(type); // Stream the required output

    });

    //Form State
  }

Stream<String> get id => _idController.stream.transform(type.contains('01') ? validPhysialId : type.contains('02') || type.contains('04') ? validaLegalAndNITEId : type.contains('03') ? validaDIMEXId : validaId);```

答:
You need to write listener for second field.
While enter value in second field the attached listener will listen controller and there you can implement your logic of validation.
Hint: Register your listener in initState(){}</p>


问:
How to bring back rows where no result set is found

Here is my problem I am trying to get some counts on ID's that did not match.

My expected result set is the replicationTime column (e.g. 201701, 201702...), when I do my count I only have NULL values for 201702, but not 201701...is there a way to bring back all the existing replicationTime values (i.e. 201701 AND 201702) but padded the count column with a zero or a NULL? I basically need to bring back two rows, but only one comes back which is the one that had no matches

```<code>select replicationTime, count(*) as CountsForNoMatches
from table
where ID IS NULL
Group By ReplicationTime
</code>```

I have tried using ISNULL... but It is not bringing back anything other than the same row.

Also, keep in mind this is the portion of a Subquery and it serves a larger picture in the overall query where I need all rows and not just one otherwise my result set returns nothing.

答:
Like this

```<code>select replicationTime, sum(case when ID is null then 1 else 0 end) as CountsForNoMatches
from table
Group By ReplicationTime
</code>```

or

```<code>select replicationTime, max(case when ID is null then 1 else 0 end) as CountsForNoMatches
from table
Group By ReplicationTime
</code>```

if you just want to know if there is some row with a null ID for that ReplicationTime.

Body:
Here is my problem I am trying to get some counts on ID's that did not match.

My expected result set is the replicationTime column (e.g. 201701, 201702...), when I do my count I only have NULL values for 201702, but not 201701...is there a way to bring back all the existing replicationTime values (i.e. 201701 AND 201702) but padded the count column with a zero or a NULL? I basically need to bring back two rows, but only one comes back which is the one that had no matches

select replicationTime, count(*) as CountsForNoMatches
from table
where ID IS NULL
Group By ReplicationTime

I have tried using ISNULL... but It is not bringing back anything other than the same row.

Also, keep in mind this is the portion of a Subquery and it serves a larger picture in the overall query where I need all rows and not just one otherwise my result set returns nothing.

Body:
Like this

select replicationTime, sum(case when ID is null then 1 else 0 end) as CountsForNoMatches
from table
Group By ReplicationTime

or

select replicationTime, max(case when ID is null then 1 else 0 end) as CountsForNoMatches
from table
Group By ReplicationTime

if you just want to know if there is some row with a null ID for that ReplicationTime.


答:
It works just like it does when you do

```<code>auto i = 0;
</code>```

You have to specify an initializer if you are not capturing an existing variable and that initializer is what is used to determine the type.

Title: Type deduction for variable declared in lambda's capture

Body:
It works just like it does when you do

auto i = 0;

You have to specify an initializer if you are not capturing an existing variable and that initializer is what is used to determine the type.


问:
How to update the main angular component on routing?
I want my entire app to have the same nav bar, so naturally I put it in app.component.html. This nav bar contains the email of the logged user, and so should appear on the nav bar after connection. In order to keep that info even after a page refresh, I keep the email in session storage.

The thing is that, in order for the HTML code to pick up the value added in session storage after logging in, app.component has to refresh. But it's not happening when going to the next page after logging in. I have to refresh the page for the info to appear on the navbar, and I clearly don't want to do that.

I could create a nav bar component, but I don't want to have to include it everywhere on the app, even though it would somewhat solve my problem.

Some code next, just to visualize things a bit better

答:
I recommend you using a simple EventEmitter or RxJS Subject/BehaviorSubject.

user = new BehaviorSubject<User>(null);

this user will be a property of you auth service.

each time a user successfully signed-up or logged-in, you will notify all the
subscribers with the new value.

this.user.next(user);

and for the auto-login, auto-logout functionality you may use localStorage

localStorage.setItem('userData', JSON.stringify(user));

wherever you need the current user, for example on navbar, subscribe to it and it will gives you the latest changes.

```<code>this.userSub = this.authService.user.subscribe(user => {

});
</code>```

and finally make sure unsubscribe from user subscription wherever you subscribed

```<code>ngOnDestroy() {
    this.userSub.unsubscribe();
}
</code>```

for auto-login functionality, even if the page refreshed, we stored current user object in local-storage whenever user logged-in/signed-up successfully, so by using ngOnInit hook on the app.component (a parental component) we can achieve what you need by retrieving and restoring the user object to angular-app.

```<code>autoLogin() {
  const userData = JSON.parse(localStorage.getItem('userData'));
  if (!userData) {
    return;
  }

  const loadedUser = new User(
    userData.email,
    userData.token,
    new Date(userData.expiresIn)
  );

  if (loadedUser.token) {
    this.user.next(loadedUser);
  }
}
</code>```

you may check token validity and expiresIn before emitting the restored user.

make sure to call autoLogin() as the angular-app starts.

Body:
I recommend you using a simple EventEmitter or RxJS Subject/BehaviorSubject.

user = new BehaviorSubject<User>(null);

this user will be a property of you auth service.

each time a user successfully signed-up or logged-in, you will notify all the
subscribers with the new value.

this.user.next(user);

and for the auto-login, auto-logout functionality you may use localStorage

localStorage.setItem('userData', JSON.stringify(user));

wherever you need the current user, for example on navbar, subscribe to it and it will gives you the latest changes.

this.userSub = this.authService.user.subscribe(user => {

});

and finally make sure unsubscribe from user subscription wherever you subscribed

ngOnDestroy() {
    this.userSub.unsubscribe();
}

for auto-login functionality, even if the page refreshed, we stored current user object in local-storage whenever user logged-in/signed-up successfully, so by using ngOnInit hook on the app.component (a parental component) we can achieve what you need by retrieving and restoring the user object to angular-app.

autoLogin() {
  const userData = JSON.parse(localStorage.getItem('userData'));
  if (!userData) {
    return;
  }

  const loadedUser = new User(
    userData.email,
    userData.token,
    new Date(userData.expiresIn)
  );

  if (loadedUser.token) {
    this.user.next(loadedUser);
  }
}

you may check token validity and expiresIn before emitting the restored user.

make sure to call autoLogin() as the angular-app starts.


问:
C warning(clang compiler) "integer literal is too large to be represented in a signed integer"
I have this piece of code

```<code>#include <stdio.h>

typedef signed long long v2signed_long
      __attribute__ ((__vector_size__ (sizeof(signed long long) * 2)));

int main()
{
        v2signed_long v = {4611686018427387904LL, -9223372036854775808LL};

        printf("%lli, %lli\n", v[0], v[1]);
        return 0;
}
</code>```

Which gives the following warning(The related questions didn't help):

```<code>:7:45: warning: integer literal is too large to be represented in
       a signed integer type, interpreting as unsigned
  [-Wimplicitly-unsigned-literal]
    v2signed_long v = {4611686018427387904LL, -9223372036854775808LL};
</code>```

Is there a way to solve this warning? Thanks!

答:
The problem is that -9223372036854775808LL is not actually an integer literal.  It's the literal 9223372036854775808LL with the unary - operator applied to it.  The value 9223372036854775808 is too large to fit in a signed long long which is why you're getting the warning.

You can fix this by using the expression -9223372036854775807LL - 1LL instead.  The value 9223372036854775807 fits in a signed long long as does -9223372036854775807LL, then subtracting 1 gives you the value you want.

Alternately, you can use the macro LLONG_MIN.

Body:
I have this piece of code

#include <stdio.h>

typedef signed long long v2signed_long
      __attribute__ ((__vector_size__ (sizeof(signed long long) * 2)));

int main()
{
        v2signed_long v = {4611686018427387904LL, -9223372036854775808LL};

        printf("%lli, %lli\n", v[0], v[1]);
        return 0;
}

Which gives the following warning(The related questions didn't help):

:7:45: warning: integer literal is too large to be represented in
       a signed integer type, interpreting as unsigned
  [-Wimplicitly-unsigned-literal]
    v2signed_long v = {4611686018427387904LL, -9223372036854775808LL};

Is there a way to solve this warning? Thanks!


问:
Url with special char #
I've to show with a browser some files that contains this # on the name. Using it on the url the file seems to be not available.

How can I configure IIS or my web.config to allow this?

thanks,
Andrea

答:
That's not how URLs work.

The # character is used to denote the hash portion; anything after it is not sent to the server.

You need to escape the # as %23

Title: Url with special char #