问:
Javascript error when html passed in JSON packet
I am going mad trying to resolve this issue. I have implemented a Coldfusion Ajax-like File Upload that uploads a file using a hidden frame and then grabs the contents returned by the frame. It is based on this article: http://www.bennadel.com/blog/1244-ColdFusion-jQuery-And-AJAX-File-Upload-Demo.htm

So, everything is working great, EXCEPT when I send back HTML in the data. So, if you look in the code below, I have provided the action page that streams data back to the hidden frame. The first line works, the second line with html does not.

```<code>    <!--- Create the return HTML. Remember, we are going to be treating the BODY of the returned document as if it were a JSON string. --->
    <cfsavecontent variable="strHTML">

        <cfset var sResponse = {} />
        <!--- THIS WORKS --->
        <cfset sResponse = {SUCCESS = true, ERRORS = [], DATA = "Hello World", RETURNID=""} />
        <!--- THIS DOES NOT WORK --->
        <cfset sResponse = {SUCCESS = true, ERRORS = [], DATA = #HtmlEditFormat('<div>Hello World</div>')#", RETURNID=""} />

        <cfoutput>
            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
            <html>
            <head></head>
            <body>#SerializeJSON( sResponse )#</body>
            </html>
        </cfoutput>
    </cfsavecontent>

<!--- Create binary response data. --->
<cfset binResponse = ToBinary( ToBase64( strHTML ) ) />

<!--- Tell the client how much data to expect. --->
<cfheader name="content-length" value="#ArrayLen( binResponse )#" />

<!--- Stream the "plain text" back to the client .--->
<cfcontent type="text/html" variable="#binResponse#" />
</code>```

The javascript for doing all of this is below. The line that it errors on when HTML is passed back is:

// Assuming that our return data is in JSON format, evaluate the body html to get our return data.
var objData = eval( "(" + jBody.html() + ")" );

```<code>//ShareForm Photo Upload Form Process (simulated Ajax)
$(document).ready(function() {
    // Attach an event to the submit method. Instead of submitting the actual form to the primary page, we are going to be submitting the form to a hidden iFrame that we dynamically create.
    $( "#frmShareForm" ).submit(
        function( objEvent ){
            var jThis = $( this );
            var photoUploadAction = $("#photoUploadAction").val();

            // Create a unique name for our iFrame. We can do this by using the tick count from the date.
            var strName = ("uploader" + (new Date()).getTime());

            // Create an iFrame with the given name that does not point to any page - we can use the address "about:blank" to get this to happen.
            var jFrame = $( "<iframe name=\"" + strName + "\" src=\"about:blank\" />" );

            // We now have an iFrame that is not attached to the document. Before we attach it, let's make sure it will not be seen.
            jFrame.css( "display", "none" );

            // Since we submitting the form to the iFrame, we will want to be able to get back data from the form submission.
            // To do this, we will have to set up an event listener for the LOAD event of the iFrame.
            jFrame.load(
                function( objEvent ){
                    // Get a reference to the body tag of the loaded iFrame. We are doing to assume that this element will contain our return data in JSON format.
                    var objUploadBody = window.frames[ strName ].document.getElementsByTagName( "body" )[ 0 ];

                    // Get a jQuery object of the body so that we can have better access to it.
                    var jBody = $( objUploadBody );

                    // Assuming that our return data is in JSON format, evaluate the body html to get our return data.
                    var objData = eval( "(" + jBody.html() + ")" );
                    alert(objData);

                    // A JSON-format struct is returned that will be used to do callback functionality
                    SharePhotoAjaxResponseHandler(objData);

                    // Remove the iFrame from the document. Because FireFox has some issues with "Infinite thinking", let's put a small delay on the frame removal.
                    setTimeout
                    (
                        function()
                        {
                            jFrame.remove();
                        }, 100
                    );
                }
            );

            // Attach to body.
            $( "body:first" ).append( jFrame );

            // Now that our iFrame it totally in place, hook up the frame to post to the iFrame.
            jThis
                .attr( "action",  photoUploadAction)
                .attr( "method", "post" )
                .attr( "enctype", "multipart/form-data" )
                .attr( "encoding", "multipart/form-data" )
                .attr( "target", strName );
    });
});
</code>```

The javascript error I get is usually something like:
"unterminated regular expression literal"

I have also tried removing the SerialiseJson on the CFM page, and the eval in the javascript, which both result in other js errors. I have also tried removing the surrounding html as well as change .html() to .text(), remove the eval() and combinations of all of them. No luck.

Please can someone tell me what the problem is. I know I can't be far off as it works without html.

Thanks

UPDATE: I ran the JSON output that Coldfusion generates through the JSON validator and it failed, due to (from what I can see) the double quotation marks:

```<code>{""RETURNID"":"""",""DATA"":""<div>Hello World<\/div>"",""SUCCESS"":true,""ERRORS"":[]}
</code>```

Now I really don't know why Coldfusion is doing double quotations?? Anyone have any ideas?

答:
The problem is that you're embedding the JSON response from the server inside more html. A JSON response for an AJAX call should comprise of ONLY the JSON text, and nothing else.

Since you're embedding it in HTML, then retrieving it with a DOM call, most likely the browser is totally getting confused by your html within json within html and mangling the DOM.

Try this, instead:

```<code><cfoutput>#SerializeJSON( sResponse )#</cfoutput>
</code>```

and

```<code>var objData = eval(jBody);
</code>```

though, as other answeres have pointed out, you should not use eval for this. There's far safer ways of getting JSON data parsed back into javascript objects than eval.

Body:
I am going mad trying to resolve this issue. I have implemented a Coldfusion Ajax-like File Upload that uploads a file using a hidden frame and then grabs the contents returned by the frame. It is based on this article: http://www.bennadel.com/blog/1244-ColdFusion-jQuery-And-AJAX-File-Upload-Demo.htm

So, everything is working great, EXCEPT when I send back HTML in the data. So, if you look in the code below, I have provided the action page that streams data back to the hidden frame. The first line works, the second line with html does not.

    <cfsavecontent variable="strHTML">

        <cfset var sResponse = {} />

        <cfset sResponse = {SUCCESS = true, ERRORS = [], DATA = "Hello World", RETURNID=""} />

        <cfset sResponse = {SUCCESS = true, ERRORS = [], DATA = #HtmlEditFormat('
Hello World
')#", RETURNID=""} />

        <cfoutput>
            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

            #SerializeJSON( sResponse )#

        </cfoutput>
    </cfsavecontent>

<cfset binResponse = ToBinary( ToBase64( strHTML ) ) />

<cfheader name="content-length" value="#ArrayLen( binResponse )#" />

<cfcontent type="text/html" variable="#binResponse#" />

The javascript for doing all of this is below. The line that it errors on when HTML is passed back is:

// Assuming that our return data is in JSON format, evaluate the body html to get our return data.
var objData = eval( "(" + jBody.html() + ")" );

//ShareForm Photo Upload Form Process (simulated Ajax)
$(document).ready(function() {
    // Attach an event to the submit method. Instead of submitting the actual form to the primary page, we are going to be submitting the form to a hidden iFrame that we dynamically create.
    $( "#frmShareForm" ).submit(
        function( objEvent ){
            var jThis = $( this );
            var photoUploadAction = $("#photoUploadAction").val();

            // Create a unique name for our iFrame. We can do this by using the tick count from the date.
            var strName = ("uploader" + (new Date()).getTime());

            // Create an iFrame with the given name that does not point to any page - we can use the address "about:blank" to get this to happen.
            var jFrame = $( "" );

            // We now have an iFrame that is not attached to the document. Before we attach it, let's make sure it will not be seen.
            jFrame.css( "display", "none" );

            // Since we submitting the form to the iFrame, we will want to be able to get back data from the form submission.
            // To do this, we will have to set up an event listener for the LOAD event of the iFrame.
            jFrame.load(
                function( objEvent ){
                    // Get a reference to the body tag of the loaded iFrame. We are doing to assume that this element will contain our return data in JSON format.
                    var objUploadBody = window.frames[ strName ].document.getElementsByTagName( "body" )[ 0 ];

                    // Get a jQuery object of the body so that we can have better access to it.
                    var jBody = $( objUploadBody );

                    // Assuming that our return data is in JSON format, evaluate the body html to get our return data.
                    var objData = eval( "(" + jBody.html() + ")" );
                    alert(objData);

                    // A JSON-format struct is returned that will be used to do callback functionality
                    SharePhotoAjaxResponseHandler(objData);

                    // Remove the iFrame from the document. Because FireFox has some issues with "Infinite thinking", let's put a small delay on the frame removal.
                    setTimeout
                    (
                        function()
                        {
                            jFrame.remove();
                        }, 100
                    );
                }
            );

            // Attach to body.
            $( "body:first" ).append( jFrame );

            // Now that our iFrame it totally in place, hook up the frame to post to the iFrame.
            jThis
                .attr( "action",  photoUploadAction)
                .attr( "method", "post" )
                .attr( "enctype", "multipart/form-data" )
                .attr( "encoding", "multipart/form-data" )
                .attr( "target", strName );
    });
});

The javascript error I get is usually something like:
"unterminated regular expression literal"

I have also tried removing the SerialiseJson on the CFM page, and the eval in the javascript, which both result in other js errors. I have also tried removing the surrounding html as well as change .html() to .text(), remove the eval() and combinations of all of them. No luck.

Please can someone tell me what the problem is. I know I can't be far off as it works without html.

Thanks

UPDATE: I ran the JSON output that Coldfusion generates through the JSON validator and it failed, due to (from what I can see) the double quotation marks:

{""RETURNID"":"""",""DATA"":""
Hello World<\/div>"",""SUCCESS"":true,""ERRORS"":[]}

Now I really don't know why Coldfusion is doing double quotations?? Anyone have any ideas?

Body:
The problem is that you're embedding the JSON response from the server inside more html. A JSON response for an AJAX call should comprise of ONLY the JSON text, and nothing else.

Since you're embedding it in HTML, then retrieving it with a DOM call, most likely the browser is totally getting confused by your html within json within html and mangling the DOM.

Try this, instead:

<cfoutput>#SerializeJSON( sResponse )#</cfoutput>

and

var objData = eval(jBody);

though, as other answeres have pointed out, you should not use eval for this. There's far safer ways of getting JSON data parsed back into javascript objects than eval.


来源: stackexchange

问:
Include the key from a Kafka message with a connect sink HDFS connector
I'm using the Kafka connect HDFS sink connector to write to HDFS from kafka, it is working fine. My messages look like this:

```<code>key: my-key
value: {
"name": "helen"
}
</code>```

My use case is that in need to append the keys of my message to the events i send to HDFS.

The problem is that the key doesn't appear in the value payload so that i cannot use:

```<code>"partitioner.class":
"io.confluent.connect.hdfs.partitioner.FieldPartitioner",
"partition.field.name": "key",
</code>```

My question is how can I add the key to the message I send to the HDFS or how can i partioned based on the key?

答:
Out of the box, you can't (same goes for S3 Connect), just based on the way the code is written, not a limitation of the Connect framework

Edit - For the S3 sink, at least, I think there is now a property to include the keys

At the very least, you would need to build and add this SMT to your Connect workers, which will "move" the key, topic, and partition all over into the "value" of the Connect record before writing to storage

https://github.com/jcustenborder/kafka-connect-transform-archive

ContentLicense: CC BY-SA 4.0

Body:
I'm using the Kafka connect HDFS sink connector to write to HDFS from kafka, it is working fine. My messages look like this:

key: my-key
value: {
"name": "helen"
}

My use case is that in need to append the keys of my message to the events i send to HDFS.

The problem is that the key doesn't appear in the value payload so that i cannot use:

"partitioner.class":
"io.confluent.connect.hdfs.partitioner.FieldPartitioner",
"partition.field.name": "key",

My question is how can I add the key to the message I send to the HDFS or how can i partioned based on the key?


问:
How can I check the version before installing a package using 'apt-get'?
I'm thinking to install hylafax+ version 5.5.4 which was released last month on my Debian PC.

I checked dpkg -l | grep "hylafax" and found out that the current version is 5.5.3. Then I checked apt-cache search hylafax and saw the packages are available, but I can't see any version number.

How can I find the version of packages available in the apt-get?

答:
You can also just simply do the regular apt-get update and then, as per the manual, do:

apt-get -V upgrade

-V  Show verbose version numbers

Which will show you the current package vs the one which will be upgraded in a format similar to the one bellow:

```<code>~# sudo apt-get -V upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
The following packages will be upgraded:
   curl (7.38.0-4+deb8u14 => 7.38.0-4+deb8u15)
   php5 (5.6.40+dfsg-0+deb8u2 => 5.6.40+dfsg-0+deb8u3)
2 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Need to get 12.0 MB of archives.
After this operation, 567 kB of additional disk space will be used.
Do you want to continue? [Y/n]
</code>```

Body:
You can also just simply do the regular apt-get update and then, as per the manual, do:

apt-get -V upgrade

-V  Show verbose version numbers

Which will show you the current package vs the one which will be upgraded in a format similar to the one bellow:

~# sudo apt-get -V upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
The following packages will be upgraded:
   curl (7.38.0-4+deb8u14 => 7.38.0-4+deb8u15)
   php5 (5.6.40+dfsg-0+deb8u2 => 5.6.40+dfsg-0+deb8u3)
2 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Need to get 12.0 MB of archives.
After this operation, 567 kB of additional disk space will be used.
Do you want to continue? [Y/n]


问:
REQUEST_URI not matching explicit path and filename
Really stumped, because form and syntax seem fine.

RewriteCond for REQUEST_URI is not matching the explicit path and filename.  When isolated, RewriteCond for REQUEST_FILENAME matches just fine.  I have verified using phpinfo() that REQUEST_URI contains the leading slash, and have tested without the leading slash, also.

The goal here is to know that the request is for this file and, if it doesn't exist, then throw a 410.

```<code>RewriteCond %{REQUEST_URI} ^/dir1/dir2/dir3/v_9991_0726dd5b5e8dd67a214c0c243436d131_all\.css$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ - [R=410,L]
</code>```

I don't want to omit the first Cond, because I only want to do this for a handful of files similar to this one.

UPDATE I

trying to get a definitive test.  Test set-up:

testmee.txt does not exist

request is for testmee.txt in the root

verified the request_uri is matching, by redirecting to google

cannot get 410 when using only first Cond

(when using only first Cond, server serves 404, not 410)

(using both Conds, server serves 404, not 410)

CAN get 410 when using only second Cond

```<code>RewriteCond %{REQUEST_URI} ^/testmee\.txt$
#RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ - [R=410,L]
</code>```

versus

```<code>#RewriteCond %{REQUEST_URI} ^/testmee\.txt$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ - [R=410,L]
</code>```

UPDATE II

Response for MrWhite:

ughh, same symptom.  Might have to live with googlebot hitting 404s instead of a desired 410 for outdated css/js.  No biggie in the long run, probably.

Thank you for that request_uri test redirect.  Everything is working normally in those tests.  Page names, etc. are returned as expected, in the var= rewrite URL.

At this point, I think it must be some internal handling of 404s related to the file type extensions.  See clue below.  I have Prestashop shopping cart software, and it must be forcing 404s on file types.

This will redirect to google (to affirm pattern match):

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^testmee\.txt$ http://www.google.com/ [L]
(L flag is needed or else other Rules further down will interfere.)
</code>```

This will continue to return 404 instead of 410:

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^testmee\.txt$ - [NC,R=410]
</code>```

And as a control test, this will return a 410:

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*$ - [NC,R=410]
</code>```

If file type is css in the above failed test, then my custom 404 controller does not get invoked.  I just get a plain 404 Response, w/o the custom 404 that is wrapped with all my site templating.

For example:

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^testmee\.css$ - [NC,R=410]
</code>```

I'm afraid I've wasted some of your time.  My apologies.  I never imagined that Prestashop's code would be forcing 404 based on file type, but I can't see any other explanation.  I could dig into it and maybe find the spot in the Controllers that is doing it.  Gotta take a break, though.

答:
This isn't really a solid answer, more of a things to try to help debug this and to quash some myths...

I have verified using phpinfo() that REQUEST_URI contains the leading slash

Yes, the REQUEST_URI Apache server variable does indeed contain the leading slash. It contains the full URL-path.

However, the REQUEST_URI Apache server variable is not necessarily the same as the $_SERVER['REQUEST_URI'] PHP superglobal - in fact, they aren't really the same thing at all. There are some significant differences between these variables (in some ways it's perhaps a bit unfortunate they share the same name). Notably, the PHP superglobal contains the initial URL from the request and includes the query string (if any) and is not %-decoded. Whereas the Apache server variable of the same name contains the rewritten URL (not necessarily the requested URL) and does not contain the query string and is %-decoded.

So, that's why I was asking whether you have other mod_rewrite directives. You could very well have had a conflict. If another directive rewrites the URL, then the condition will never match (despite the PHP superglobal suggesting that it should).

It seemed that if I put this at the top, the Last flag would end processing for that trip through, return the 410

This directive should certainly go at the top of the .htaccess file, to avoid the URL being rewritten earlier. The L flag is actually superfluous when used with a R=410 (anything other than a 3xx) - it is implied in this case.

Then I change the result to be "throw a 410" and it throws a 404.

That can certainly be caused by a server-side override. But you are able to throw a 410 in other situations, so that would seem to rule that out. However, you can reset the error document in .htaccess if in doubt (unless you are already using a custom error document):

```<code>ErrorDocument 410 default
</code>```

```<code>RewriteCond %{REQUEST_URI} ^/dir1/dir2/dir3/v_9991_0726dd5b5e8dd67a214c0c243436d131_all\.css$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ - [R=410,L]
</code>```

Whilst this doesn't really make a difference to how the rule behaves, you don't need the first RewriteCond directive that checks against the REQUEST_URI. You should be doing this check in the RewriteRule pattern instead (which will be more efficient, since this is processed first). For example:

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^dir1/dir2/dir3/v_9991_0726dd5b5e8dd67a214c0c243436d131_all\.css$ - [NC,R=410]
</code>```

The NC flag should be superfluous.

Still, a conflict with existing directives is the most probable cause. Remove all other directives. Do you still see the same behaviour?

You can test the value of the REQUEST_URI server variable. You could either issue a redirect and pass the REQUEST_URI as a URL parameter, or set environment variables (but you will need to look out for REDIRECT_<var> for each rewrite).

For example, at the top of your .htaccess (or wherever you are trying this):

```<code>RewriteCond %{QUERY_STRING} ^$
RewriteRule ^ /test.php?var=%{REQUEST_URI} [NE,R,L]
</code>```

Created a dummy test.php file to avoid an internal subrequest to an error document.

Body:
Really stumped, because form and syntax seem fine.

RewriteCond for REQUEST_URI is not matching the explicit path and filename.  When isolated, RewriteCond for REQUEST_FILENAME matches just fine.  I have verified using phpinfo() that REQUEST_URI contains the leading slash, and have tested without the leading slash, also.

The goal here is to know that the request is for this file and, if it doesn't exist, then throw a 410.

RewriteCond %{REQUEST_URI} ^/dir1/dir2/dir3/v_9991_0726dd5b5e8dd67a214c0c243436d131_all\.css$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ - [R=410,L]

I don't want to omit the first Cond, because I only want to do this for a handful of files similar to this one.

UPDATE I

trying to get a definitive test.  Test set-up:

testmee.txt does not exist

request is for testmee.txt in the root

verified the request_uri is matching, by redirecting to google

cannot get 410 when using only first Cond

(when using only first Cond, server serves 404, not 410)

(using both Conds, server serves 404, not 410)

CAN get 410 when using only second Cond

RewriteCond %{REQUEST_URI} ^/testmee\.txt$
#RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ - [R=410,L]

versus

#RewriteCond %{REQUEST_URI} ^/testmee\.txt$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ - [R=410,L]

UPDATE II

Response for MrWhite:

ughh, same symptom.  Might have to live with googlebot hitting 404s instead of a desired 410 for outdated css/js.  No biggie in the long run, probably.

Thank you for that request_uri test redirect.  Everything is working normally in those tests.  Page names, etc. are returned as expected, in the var= rewrite URL.

At this point, I think it must be some internal handling of 404s related to the file type extensions.  See clue below.  I have Prestashop shopping cart software, and it must be forcing 404s on file types.

This will redirect to google (to affirm pattern match):

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^testmee\.txt$ http://www.google.com/ [L]
(L flag is needed or else other Rules further down will interfere.)

This will continue to return 404 instead of 410:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^testmee\.txt$ - [NC,R=410]

And as a control test, this will return a 410:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*$ - [NC,R=410]

If file type is css in the above failed test, then my custom 404 controller does not get invoked.  I just get a plain 404 Response, w/o the custom 404 that is wrapped with all my site templating.

For example:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^testmee\.css$ - [NC,R=410]

I'm afraid I've wasted some of your time.  My apologies.  I never imagined that Prestashop's code would be forcing 404 based on file type, but I can't see any other explanation.  I could dig into it and maybe find the spot in the Controllers that is doing it.  Gotta take a break, though.

Body:
This isn't really a solid answer, more of a things to try to help debug this and to quash some myths...

I have verified using phpinfo() that REQUEST_URI contains the leading slash

Yes, the REQUEST_URI Apache server variable does indeed contain the leading slash. It contains the full URL-path.

However, the REQUEST_URI Apache server variable is not necessarily the same as the $_SERVER['REQUEST_URI'] PHP superglobal - in fact, they aren't really the same thing at all. There are some significant differences between these variables (in some ways it's perhaps a bit unfortunate they share the same name). Notably, the PHP superglobal contains the initial URL from the request and includes the query string (if any) and is not %-decoded. Whereas the Apache server variable of the same name contains the rewritten URL (not necessarily the requested URL) and does not contain the query string and is %-decoded.

So, that's why I was asking whether you have other mod_rewrite directives. You could very well have had a conflict. If another directive rewrites the URL, then the condition will never match (despite the PHP superglobal suggesting that it should).

It seemed that if I put this at the top, the Last flag would end processing for that trip through, return the 410

This directive should certainly go at the top of the .htaccess file, to avoid the URL being rewritten earlier. The L flag is actually superfluous when used with a R=410 (anything other than a 3xx) - it is implied in this case.

Then I change the result to be "throw a 410" and it throws a 404.

That can certainly be caused by a server-side override. But you are able to throw a 410 in other situations, so that would seem to rule that out. However, you can reset the error document in .htaccess if in doubt (unless you are already using a custom error document):

ErrorDocument 410 default

RewriteCond %{REQUEST_URI} ^/dir1/dir2/dir3/v_9991_0726dd5b5e8dd67a214c0c243436d131_all\.css$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ - [R=410,L]

Whilst this doesn't really make a difference to how the rule behaves, you don't need the first RewriteCond directive that checks against the REQUEST_URI. You should be doing this check in the RewriteRule pattern instead (which will be more efficient, since this is processed first). For example:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^dir1/dir2/dir3/v_9991_0726dd5b5e8dd67a214c0c243436d131_all\.css$ - [NC,R=410]

The NC flag should be superfluous.

Still, a conflict with existing directives is the most probable cause. Remove all other directives. Do you still see the same behaviour?

You can test the value of the REQUEST_URI server variable. You could either issue a redirect and pass the REQUEST_URI as a URL parameter, or set environment variables (but you will need to look out for REDIRECT_<var> for each rewrite).

For example, at the top of your .htaccess (or wherever you are trying this):

RewriteCond %{QUERY_STRING} ^$
RewriteRule ^ /test.php?var=%{REQUEST_URI} [NE,R,L]

Created a dummy test.php file to avoid an internal subrequest to an error document.


问:
Date field from dataframe removes leading 0 after export
I have a Dataframe with the following date field:

463    14-05-2019
535    03-05-2019
570    11-05-2019
577    09-05-2019
628    08-08-2019
630    25-05-2019
Name: Date, dtype: object
```
<p>I have to format it as DDMMAAAA. This is what I'm doing inside a loop (<code>for idx, row in df.iterrows():</code>):</p>
<ul>
<li>I'm removing the <code>\-</code> char using regex:
<blockquote>
<p><code>df.at[idx, 'Date'] = re.sub('\-', '', df.at[idx, 'Date'])</code></p>
</blockquote>
</li>
<li>then using apply to enforce and an 8 digit string with leading zeros
<blockquote>
<p><code>df['Date'] = df['Date'].apply(lambda x: '{0:0>8}'.format(x))</code></p>
</blockquote>
</li>
</ul>
<p>But even though the df['Date'] field has the 8 digits with the leading 0 on the df, whent exporting it to csv the leading zeros are being removed on the exported file like below.</p>
```df.to_csv(path_or_buf=report, header=True, index=False, sep=';')
```
<p>field as in csv:</p>
```Dt_DDMMAAAA
30102019
12052019
7052019
26042019
3052019
22042019
25042019
2062019
```

I know I must be missing the point somewhere along the way here, but I just can't figure out what the issue (or if it's even an issue, rather then a misused method).

答:
IMO the simplest method is to use the date_format argument when writing to CSV. This means you will need to convert the "Date" column to datetime beforehand using pd.to_datetime.

```<code>(df.assign(Date=pd.to_datetime(df['Date'], errors='coerce'))
   .to_csv(path_or_buf=report, date_format='%d%m%Y', index=False))
</code>```

This prints,

```<code>Date
14052019
05032019
05112019
05092019
08082019
25052019
</code>```

More information on arguments to to_csv can be found in Writing a pandas DataFrame to CSV file.

Body:
I have a Dataframe with the following date field:

463    14-05-2019
535    03-05-2019
570    11-05-2019
577    09-05-2019
628    08-08-2019
630    25-05-2019
Name: Date, dtype: object

I have to format it as DDMMAAAA. This is what I'm doing inside a loop (for idx, row in df.iterrows():):

I'm removing the \- char using regex:

df.at[idx, 'Date'] = re.sub('\-', '', df.at[idx, 'Date'])

then using apply to enforce and an 8 digit string with leading zeros

df['Date'] = df['Date'].apply(lambda x: '{0:0>8}'.format(x))

But even though the df['Date'] field has the 8 digits with the leading 0 on the df, whent exporting it to csv the leading zeros are being removed on the exported file like below.

df.to_csv(path_or_buf=report, header=True, index=False, sep=';')

field as in csv:

Dt_DDMMAAAA
30102019
12052019
7052019
26042019
3052019
22042019
25042019
2062019

I know I must be missing the point somewhere along the way here, but I just can't figure out what the issue (or if it's even an issue, rather then a misused method).

Body:
IMO the simplest method is to use the date_format argument when writing to CSV. This means you will need to convert the "Date" column to datetime beforehand using pd.to_datetime.

(df.assign(Date=pd.to_datetime(df['Date'], errors='coerce'))
   .to_csv(path_or_buf=report, date_format='%d%m%Y', index=False))

This prints,

Date
14052019
05032019
05112019
05092019
08082019
25052019

More information on arguments to to_csv can be found in Writing a pandas DataFrame to CSV file.


问:
How to display all posts by a user in octobrcms
I am trying to display all posts by a user and have this in my code that works only when a user is signed in and displays all the user's posts.

```<code>$id =  Auth::getUser()->id;

    $this['allproducts'] = Advert::where('user_id', $id)->orderby('created_at','desc')->get();
</code>```

I want to make this visible to all signed in or not. when i logged out and try to access the url, it throws up an error

Trying to get property 'id' of non-object

答:
I want to make this visible to all signed in or not. when i logged out and try to access the url, it throws up an error

It is not clear in this context who you refer to as a User.

If you want to make the posts of 'any user' accessible to 'any other user' then your implementation is not correct.

Auth::getUser() - Retrieves the signed in User from the active session - See here - The error you posted is expected because after sign out, the Auth session is cleared and you cannot access the id property anymore.

You are basically doing $id =  null->id;

What you could do is list the registered users and let the site visitor / user decide which user's posts to display.

Body:
I am trying to display all posts by a user and have this in my code that works only when a user is signed in and displays all the user's posts.

$id =  Auth::getUser()->id;

    $this['allproducts'] = Advert::where('user_id', $id)->orderby('created_at','desc')->get();

I want to make this visible to all signed in or not. when i logged out and try to access the url, it throws up an error

Trying to get property 'id' of non-object


问:
UITableviewCell with RemoveButton
I have a one Tableview in that i added a UIButton to each Tableviewcell named it as Remove
when i click the remove button the appropriate cell data will be remove from the tableview

and i added UIButton programmatically

now i want to perform remove option.

Thanks in Advance....

答:
try this one:</p>

```<code>    - (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *s = @"cell";

        UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:s];
        AsyncImageView *asyncImage;
        UIButton *button = nil;
        if ( cell == nil ) {
            cell = [[[UITableViewCell alloc]initWithReuseIdentifier:s] autorelease];
            UIButton *removeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [button addTarget:self
                       action:@selector(remove:)
             forControlEvents:UIControlEventTouchUpInside];
            ….
            [cell addSubview:button];
        }

        …..

        return cell;
    }

    -(void)remove:(UIButton*)btn{
        UITableViewCell *cell = (UITableViewCell *)btn.superview;
        NSIndexPath* index = [self.tableView indexPathForCell:cell];
        [peopleList removeObjectAtIndex:index.row];
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:index]
                      withRowAnimation:UITableViewRowAnimationRight];
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: UITableviewCell with RemoveButton

Body:
try this one:

    - (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *s = @"cell";

        UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:s];
        AsyncImageView *asyncImage;
        UIButton *button = nil;
        if ( cell == nil ) {
            cell = [[[UITableViewCell alloc]initWithReuseIdentifier:s] autorelease];
            UIButton *removeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [button addTarget:self
                       action:@selector(remove:)
             forControlEvents:UIControlEventTouchUpInside];
            ….
            [cell addSubview:button];
        }

        …..

        return cell;
    }

    -(void)remove:(UIButton*)btn{
        UITableViewCell *cell = (UITableViewCell *)btn.superview;
        NSIndexPath* index = [self.tableView indexPathForCell:cell];
        [peopleList removeObjectAtIndex:index.row];
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:index]
                      withRowAnimation:UITableViewRowAnimationRight];
}

ContentLicense: CC BY-SA 3.0


问:
Unable to deregister service(Spring boot app) from consul
Unable to deregister the service from Consul.
Basically Consul official page said that it will deregister service automatically but in my case it won't work like said.

https://www.consul.io/docs/agent/basics.html

Hi Referring to the consul Life-cycle its says that

To prevent an accumulation of dead nodes (nodes in either failed or left states), Consul will automatically remove dead nodes out of the catalog. This process is called reaping. This is currently done on a configurable interval of 72 hours (changing the reap interval is not recommended due to its consequences during outage situations). Reaping is similar to leaving, causing all associated services to be deregistered.

This is my bootstrap.yml file

```<code>server:
 port: 8089
spring:
 application:
   name: ***-service
 cloud:
   consul:
     host: consul-ui
     port: 8500
     discovery:
       deregister: true
       instance-id: ${spring.application.name}:${random.value}
       enabled: true
       register: true
       health-check-interval: 20s
       prefer-ip-address: true
     config:
       enabled: true
       prefix: configuration
       defaultContext: shared
       format: YAML
       data-key: data
       watch:
         enabled: true
 endpoints:
   shutdown:
     enabled: true
</code>```

In Consul UI after deleting service using purge command, still shows on Consul UI. So meant that it is not been deregister from Consul

答:
That documentation is about consul nodes, not service nodes.

How exactly are you terminating the application?

Body:
Unable to deregister the service from Consul.
Basically Consul official page said that it will deregister service automatically but in my case it won't work like said.

https://www.consul.io/docs/agent/basics.html

Hi Referring to the consul Life-cycle its says that

To prevent an accumulation of dead nodes (nodes in either failed or left states), Consul will automatically remove dead nodes out of the catalog. This process is called reaping. This is currently done on a configurable interval of 72 hours (changing the reap interval is not recommended due to its consequences during outage situations). Reaping is similar to leaving, causing all associated services to be deregistered.

This is my bootstrap.yml file

server:
 port: 8089
spring:
 application:
   name: ***-service
 cloud:
   consul:
     host: consul-ui
     port: 8500
     discovery:
       deregister: true
       instance-id: ${spring.application.name}:${random.value}
       enabled: true
       register: true
       health-check-interval: 20s
       prefer-ip-address: true
     config:
       enabled: true
       prefix: configuration
       defaultContext: shared
       format: YAML
       data-key: data
       watch:
         enabled: true
 endpoints:
   shutdown:
     enabled: true

In Consul UI after deleting service using purge command, still shows on Consul UI. So meant that it is not been deregister from Consul


问:
How can i have a clear icon in the primeNg input?
Need to put a clear icon inside text box of primeNg. And on click it should clear the field.</p>

答:
You can do something like this --></p>

```<code> <input
                        type="text"
                        pInputText
                        placeholder="Type Text"
                        [(ngModel)]="text"
                        (input)="someText($event.target.value)"
                        style="width:auto"

                    />
                    <span style="margin-left:-20px;">
                        <a (click)="clearText()">
                            <i class="fa fa-times" style="color: rgb(149, 149, 153); cursor: pointer;"></i>
                        </a>
                    </span>
</code>```

Body:
You can do something like this -->

 <input
                        type="text"
                        pInputText
                        placeholder="Type Text"
                        [(ngModel)]="text"
                        (input)="someText($event.target.value)"
                        style="width:auto"

                    />
                    <span style="margin-left:-20px;">
                        <a (click)="clearText()">
                            <i class="fa fa-times" style="color: rgb(149, 149, 153); cursor: pointer;"></i>
                        </a>
                    </span>


问:
Flutter/Firebase Firestore using runTransaction do nothing
Hi I am trying to implement simple transaction using Firebase Firestore in Flutter. The process is simple just update two documents like this:

```<code>DocumentSnapshot productSnapshot = await productReference.get();
    DocumentSnapshot userSnapshot = await userReference.get();
    DocumentSnapshot userProductSnapshot = await userProductReference.get();
    if (productSnapshot.exists &&
        userSnapshot.exists &&
        userProductSnapshot.exists) {
      double price = double.parse(productSnapshot.data["productPrice"].toString());
      double money = double.parse(userSnapshot.data["money"].toString());
      double afterBuyMoney = money - price;
      if (afterBuyMoney >= 0) {
        await userReference.updateData({"money": afterBuyMoney});
        await userProductReference.updateData(({"isOwned": true}));
        response = "success";
      }
    }
</code>```

This codes already works fine and get the expected result also data is updated in cloud database, however because there is two transaction and it is possible there is error in middle transaction. I want to implement this using Firestore runTransaction so if there is error, all the transaction will be rollbacked.

This is my codes using Firestore runTransaction

```<code>await Firestore.instance.runTransaction((transaction) async {
      DocumentSnapshot productSnapshot = await transaction.get(productReference);
      DocumentSnapshot userSnapshot = await transaction.get(userReference);
      DocumentSnapshot userProductSnapshot = await transaction.get(userProductReference);
      if(productSnapshot.exists && userSnapshot.exists && userProductSnapshot.exists) {
        double price = double.parse(productSnapshot.data["productPrice"].toString());
        double money = double.parse(userSnapshot.data["money"].toString());
        double afterBuyMoney = money - price;
        if (afterBuyMoney >= 0) {
          await transaction.update(userReference, {"money": afterBuyMoney});
          await transaction.update(userProductReference,({"isOwned": true}));
          response = "success";
        }
      }
    }).then((_) {
      print("Success");
    }).catchError((error) {
      response = error.message;
    });
</code>```

This codes is also works fine and print the "Success", however in the firestore database the data is not updated and it seems the transaction doesn't work although there is no error in log. Is there any missing step or wrong in my code? How to fix this?

答: I provided a possible solution HERE which was to switch the version of Flutter you are using.  </p>

Body:
Hi I am trying to implement simple transaction using Firebase Firestore in Flutter. The process is simple just update two documents like this:

DocumentSnapshot productSnapshot = await productReference.get();
    DocumentSnapshot userSnapshot = await userReference.get();
    DocumentSnapshot userProductSnapshot = await userProductReference.get();
    if (productSnapshot.exists &&
        userSnapshot.exists &&
        userProductSnapshot.exists) {
      double price = double.parse(productSnapshot.data["productPrice"].toString());
      double money = double.parse(userSnapshot.data["money"].toString());
      double afterBuyMoney = money - price;
      if (afterBuyMoney >= 0) {
        await userReference.updateData({"money": afterBuyMoney});
        await userProductReference.updateData(({"isOwned": true}));
        response = "success";
      }
    }

This codes already works fine and get the expected result also data is updated in cloud database, however because there is two transaction and it is possible there is error in middle transaction. I want to implement this using Firestore runTransaction so if there is error, all the transaction will be rollbacked.

This is my codes using Firestore runTransaction

await Firestore.instance.runTransaction((transaction) async {
      DocumentSnapshot productSnapshot = await transaction.get(productReference);
      DocumentSnapshot userSnapshot = await transaction.get(userReference);
      DocumentSnapshot userProductSnapshot = await transaction.get(userProductReference);
      if(productSnapshot.exists && userSnapshot.exists && userProductSnapshot.exists) {
        double price = double.parse(productSnapshot.data["productPrice"].toString());
        double money = double.parse(userSnapshot.data["money"].toString());
        double afterBuyMoney = money - price;
        if (afterBuyMoney >= 0) {
          await transaction.update(userReference, {"money": afterBuyMoney});
          await transaction.update(userProductReference,({"isOwned": true}));
          response = "success";
        }
      }
    }).then((_) {
      print("Success");
    }).catchError((error) {
      response = error.message;
    });

This codes is also works fine and print the "Success", however in the firestore database the data is not updated and it seems the transaction doesn't work although there is no error in log. Is there any missing step or wrong in my code? How to fix this?


问:
Adding strings and literals, how does the order affect if you can add the strings without error
Consider the following string definitions:

```<code>string s1 = "hello", s2 = "world";
string s6 = s1 + ", " + "world";
string s7 = "hello" + ", " + s2;
</code>```

The book C++ Primer 5e states that the third line will cause the compiler to give an error because you cannot add string literals. The actual error given from the compiler is

```<code>error: invalid operands of types 'const char [6]'
and 'const char [3]' to binary 'operator+'
</code>```

But isn't the second string s6 doing the exact same thing as s7? What is the difference?

答:
Since addition associates left-to-right, s6 is parsed as (s1 + ", ") + "world".  This adds a string to a const char *, resulting in another string.  Then we add another const char * to that string, resulting in a third string that is stored in s6.

s7 is parsed as ("hello" + ", ") + s2, which tries to add a const char * to another const char *, which you can't do.  You could rewrite it as "hello" + (", " + s2) and it would then compile.

Body:
Consider the following string definitions:

string s1 = "hello", s2 = "world";
string s6 = s1 + ", " + "world";
string s7 = "hello" + ", " + s2;

The book C++ Primer 5e states that the third line will cause the compiler to give an error because you cannot add string literals. The actual error given from the compiler is

error: invalid operands of types 'const char [6]'
and 'const char [3]' to binary 'operator+'

But isn't the second string s6 doing the exact same thing as s7? What is the difference?


问:
Deserialize Json string to Enum C#
I am writing a test on a custom version of stringEnumConverter. But my test keeps throwing when I deserialize. I searched over stack overflow, but could not find what I did wrong. Following is a sample of what I'm doing:

```<code>namespace ConsoleApp2
{
    [Flags]
    [JsonConverter(typeof(StringEnumConverter))]
    enum TestEnum
    {
        none = 0,
        obj1 = 1,
        obj2 = 2
    }

    class Program
    {
        static void Main(string[] args)
        {
            var jsonString = "{none}";
            var deserializedObject = JsonConvert.DeserializeObject<TestEnum>(jsonString);
        }
    }
}
</code>```

The exception I get on the deserialize line is Unexpected token StartObject when parsing enum.

I suspect it might be because I am representing the json string wrong, I also tried "{\"none\"}", "{\"TestEnum\":\"none\"}", "{TestEnum:none}", "{none}" and "none".

答:
If you serialize TestEnum.none into JSON, the result is "none". A string is perfectly valid JSON.

Your JSON isn't even valid JSON:
* It is an object,
* containing key (but keys must be quoted with double quoted),
* that carries no value. (and an object key must have a value)

So... try something like this:

```<code>var jsonString = "\"none\"";
var deserializedObject = JsonConvert.DeserializeObject<TestEnum>(jsonString);
</code>```

But you shouldn't have to write a custom serializer. JSON.Net will do it for you. See

.NET - JSON serialization of enum as string

But if you want to deserialize an object containing your enum, you'll want something along these lines:

```<code>{
  "enumKey" : "none"
}
</code>```

Which would be something like this in your test:

```<code>var jsonString = "{ \"enumKey\" : \"none\" }";
</code>```

Title: Deserialize Json string to Enum C#

Body:
I am writing a test on a custom version of stringEnumConverter. But my test keeps throwing when I deserialize. I searched over stack overflow, but could not find what I did wrong. Following is a sample of what I'm doing:

namespace ConsoleApp2
{
    [Flags]
    [JsonConverter(typeof(StringEnumConverter))]
    enum TestEnum
    {
        none = 0,
        obj1 = 1,
        obj2 = 2
    }

    class Program
    {
        static void Main(string[] args)
        {
            var jsonString = "{none}";
            var deserializedObject = JsonConvert.DeserializeObject<TestEnum>(jsonString);
        }
    }
}

The exception I get on the deserialize line is Unexpected token StartObject when parsing enum.

I suspect it might be because I am representing the json string wrong, I also tried "{\"none\"}", "{\"TestEnum\":\"none\"}", "{TestEnum:none}", "{none}" and "none".

Body:
If you serialize TestEnum.none into JSON, the result is "none". A string is perfectly valid JSON.

Your JSON isn't even valid JSON:
* It is an object,
* containing key (but keys must be quoted with double quoted),
* that carries no value. (and an object key must have a value)

So... try something like this:

var jsonString = "\"none\"";
var deserializedObject = JsonConvert.DeserializeObject<TestEnum>(jsonString);

But you shouldn't have to write a custom serializer. JSON.Net will do it for you. See

.NET - JSON serialization of enum as string

But if you want to deserialize an object containing your enum, you'll want something along these lines:

{
  "enumKey" : "none"
}

Which would be something like this in your test:

var jsonString = "{ \"enumKey\" : \"none\" }";


答:
What i will do is using strftime + 'to_excel`, since In csv , if you open it with text , it will show the leading zero, since csv will not keeping any format when display, in that case , you can using excel

```<code>pd.to_datetime(df.Date,dayfirst=True).dt.strftime('%m%d%Y').to_excel('your.xls')
Out[722]:
463    05142019
535    05032019
570    05112019
577    05092019
628    08082019
630    05252019
Name: Date, dtype: object
</code>```

Title: Date field from dataframe removes leading 0 after export

Body:
What i will do is using strftime + 'to_excel`, since In csv , if you open it with text , it will show the leading zero, since csv will not keeping any format when display, in that case , you can using excel

pd.to_datetime(df.Date,dayfirst=True).dt.strftime('%m%d%Y').to_excel('your.xls')
Out[722]:
463    05142019
535    05032019
570    05112019
577    05092019
628    08082019
630    05252019
Name: Date, dtype: object


问:
? time delay, when using === or <=
When we use

```<code>input reg [7:0] ast, f_out;

ast === f_out ;

ast <= ast + 8'b00000001;
</code>```

for those operations " === and <= ", Have any time delay been occurred ?

EDIT: I think something small like 1 unit time, am I wrong ?

used language : verilog

答:
There will be a simulation cycle delay if you use <= - ie a nonblocking assignment. Read up on blocking vs nonblocking assignments.

Also, === is not an assignment - its an equality operator that doesn't treat x and z as don't cares

Title: ? time delay, when using === or <=

Body:
When we use

input reg [7:0] ast, f_out;

ast === f_out ;

ast <= ast + 8'b00000001;

for those operations " === and <= ", Have any time delay been occurred ?

EDIT: I think something small like 1 unit time, am I wrong ?

used language : verilog


问:
same numbers, different input methods, different outputs
While bubble sorting an array, it will give different outputs depending on the method of input, manually it sorts correctly, random it won't. Any ideas? the goal is to sort the numbers from lowest to highest

I've already tried doing the same inputs manually as it does at random but it still didn't work for random.

```<code>    valores =["20", "78", "48", "55", "4"]
</code>```

(same input in both functions)

```<code>let valores = []

function randomVals() {
    let cantidad
    valores = []

    if (rCantidad.value != '') {
        cantidad = Number(rCantidad.value)
    } else {
        cantidad = 15
    }

    for (let k = 0; k < cantidad; k++) {
        valores.push(((Math.random()) * 100).toFixed(0))
    }
    console.log(valores)
}

function agregarValor() {

    let val = Number(valor.value)

    valores.push(val)

    console.log(valores)

}

function bubbleSort(){

for (let j=0; j<valores.length; j++){
for (let i=j+1; i<valores.length; i++){
    if (valores[j]>valores[i]){
        var temp=0
        temp=valores[i]
        valores[i]=valores[j]
        valores[j]=temp
        console.log(valores)
    }
}
}
 }
</code>```

expected sorted output:

```<code>     valores=[4, 20, 48, 55, 78]
</code>```

sorted output given while using

```<code>      randomVals() valores=["20", "4", "48", "55", "78"]
</code>```

答:
toFixed() is a formatting function. It will return a string that represents the given number. Once you have strings in your array, your sorting function will use string comparison to compare them (where "20" < "4").

Make sure that the array contains numbers, e.g. by removing the formatting:

```<code>valores.push(((Math.random()) * 100))
</code>```

If you just want integers, use Math.round().

Body:
While bubble sorting an array, it will give different outputs depending on the method of input, manually it sorts correctly, random it won't. Any ideas? the goal is to sort the numbers from lowest to highest

I've already tried doing the same inputs manually as it does at random but it still didn't work for random.

    valores =["20", "78", "48", "55", "4"]

(same input in both functions)

let valores = []

function randomVals() {
    let cantidad
    valores = []

    if (rCantidad.value != '') {
        cantidad = Number(rCantidad.value)
    } else {
        cantidad = 15
    }

    for (let k = 0; k < cantidad; k++) {
        valores.push(((Math.random()) * 100).toFixed(0))
    }
    console.log(valores)
}

function agregarValor() {

    let val = Number(valor.value)

    valores.push(val)

    console.log(valores)

}

function bubbleSort(){

for (let j=0; j<valores.length; j++){
for (let i=j+1; i<valores.length; i++){
    if (valores[j]>valores[i]){
        var temp=0
        temp=valores[i]
        valores[i]=valores[j]
        valores[j]=temp
        console.log(valores)
    }
}
}
 }

expected sorted output:

     valores=[4, 20, 48, 55, 78]

sorted output given while using

      randomVals() valores=["20", "4", "48", "55", "78"]

Body:
toFixed() is a formatting function. It will return a string that represents the given number. Once you have strings in your array, your sorting function will use string comparison to compare them (where "20" < "4").

Make sure that the array contains numbers, e.g. by removing the formatting:

valores.push(((Math.random()) * 100))

If you just want integers, use Math.round().


问:
How to use codesign command
I am trying to use codesign command to sign bundle.

First of all I have got p12 file and I have imported into my keychain.

However when I try to use codesign like this:

```<code>codesign -v --force --verify --deep --verbose --sign <ID> <MyApp.app>
</code>```

It says 'no identity found'. The identity field I got it from

What am I doing wrong please?

Thanks in advance

答:
Before you run codesign command, you need to unlock your keyChain, either by clicking on unlock on the keychain app or run security unlock-keychain, otherwise you can get inconsistent result because sometimes the keychain is already unlocked, sometimes not.

You might also need to include the --keychain option in your codesign command, depending on your configuration.

You can verify if the identity is available in your current shell environment by
security find-identity -p codesigning

Title: How to use codesign command

Body:
I am trying to use codesign command to sign bundle.

First of all I have got p12 file and I have imported into my keychain.

However when I try to use codesign like this:

codesign -v --force --verify --deep --verbose --sign <ID> <MyApp.app>

It says 'no identity found'. The identity field I got it from

What am I doing wrong please?

Thanks in advance


问:
Long Press on BottomNavigationBarItem
Is there any way to handle long press on the items of BottomNavigationBar in Flutter?

I see "onTap" event handler, but nothing else and I also cannot wrap the Items into GestureDetector.

I can wrap the whole BottomNavigationBar section into the GestureDetector but in this case it's not possible to realize which Item was pressed :-/

Thanks in advance!

答:
With Flutter I recommend you to create your custom Bottom Navigation Bar as it is very easy to do.

Note: There is no way to do what you want using the default BottomNaivgationBarItem.

Title: Long Press on BottomNavigationBarItem


问:
What is the ASP.Net Core analogue of Request.AcceptTypes?
I'm probably not even asking the right question, as I know neither ASP.Net nor ASP.Net Core, but I've been tasked with porting some code over, and I'm having trouble figuring out how to adapt this logic. The goal, I think, is to check what MIME accept types the client supports, then add them to the current request's headers. </p>

答:
You want to set your Request's ContentType to one of the ContentTypes that the request specifies it accepts.

It'll be something like this

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

namespace SomeWebApplication.Controllers
{
    public class SomeController : Controller
    {
        public ActionResult SomeControllerMethod()
        {
            Response.ContentType = Request.AcceptTypes.FirstOrDefault() ?? "text/plain";
            return View();
        }
    }
}
</code>```

The FirstOrDefault() call will return the first item in Request.AcceptTypes. If Request.AcceptTypes is an empty array, it will return null, the default value of string. If it is null, the ?? operator returns "text/plain" instead of null.

Body:
You want to set your Request's ContentType to one of the ContentTypes that the request specifies it accepts.

It'll be something like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SomeWebApplication.Controllers
{
    public class SomeController : Controller
    {
        public ActionResult SomeControllerMethod()
        {
            Response.ContentType = Request.AcceptTypes.FirstOrDefault() ?? "text/plain";
            return View();
        }
    }
}

The FirstOrDefault() call will return the first item in Request.AcceptTypes. If Request.AcceptTypes is an empty array, it will return null, the default value of string. If it is null, the ?? operator returns "text/plain" instead of null.


问:
lines+=line/ TypeError: can't concat str to bytes
I need to pass the arduino data that is saved on a microSD to the sqlite database of my GUI. Anyone besides being able to fix this error, could you help me pass the data to the database?</p>

```<code>lines=b''

with serial.Serial('COM5',9600,timeout=2) as ser:
    line = ser.readline()
    line = line.decode("utf-8")
    lines+=line
</code>```

答:
The code you have posted above does not match the error. It should be

lines += line and not lines += lines

line in your code is a str object and lines is defined as byte.

So you can do this instead:
lines += bytes(line, 'utf-8') to get rid of the error.

Or you could just not call the decode on line and keep it as bytes.

Body:
I need to pass the arduino data that is saved on a microSD to the sqlite database of my GUI. Anyone besides being able to fix this error, could you help me pass the data to the database?

lines=b''

with serial.Serial('COM5',9600,timeout=2) as ser:
    line = ser.readline()
    line = line.decode("utf-8")
    lines+=line


问:
AspectJ Pointcut doesn't work on Annotations with Element.TYPE like @Component
I'm using AspectJ and I trying to Pointcut on @Component annotation.

```<code>@Pointcut("@annotation(org.springframework.stereotype.Component)")
   public void bean() {
}

@Before("bean()")
public void beforeBeanCreation(JoinPoint jp) {
    System.out.println("Works!");
}
</code>```

My configuration looks like below:

```<code>@Configuration
@ComponentScan({"com.app.pl"})
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableLoadTimeWeaving(aspectjWeaving = AspectJWeaving.ENABLED)
public class AppConfiguration{

}
</code>```

Everything works when I want to pointcut on annotation with ElementType.METHOD, or on a bean with specific name. But Pointcut on annotation with ElementType.TYPE dosen't work. I speculate that is a problem related with annotations that they are readed earlier then AspectJ proxy stand up.

Any idea how to solve this?

答:
Probably you are not using AspectJ but Spring AOP. So there are a few things to consider:

Usually Spring AOP aspects work on @Components anyway, not on non-Spring stuff. For that you would really need AspectJ. So in a way your Spring AOP aspects look for that annotation anyway.

Spring AOP aspects should be @Components too, but are excluded from aspect weaving automatically. In AspectJ you would need special precautions to exclude one aspect weaving another one bearing the same annotation as normal application code. You would need to consider that in situations where you combine Spring AOP with full AspectJ.

Now as for your AOP question, you cannot intercept joinpoints in an annotated class via @annotation() pointcut, as you already noticed. You need to use @within() instead, e.g.:

@within(org.springframework.stereotype.Component)
```

Please note that this will intercept all joinpoints in annotated classes, i.e. in the case of Spring AOP all method executions. It will not intercept bean creation, if as your log message suggests that is your goal.

Body:
I'm using AspectJ and I trying to Pointcut on @Component annotation.

@Pointcut("@annotation(org.springframework.stereotype.Component)")
   public void bean() {
}

@Before("bean()")
public void beforeBeanCreation(JoinPoint jp) {
    System.out.println("Works!");
}

My configuration looks like below:

@Configuration
@ComponentScan({"com.app.pl"})
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableLoadTimeWeaving(aspectjWeaving = AspectJWeaving.ENABLED)
public class AppConfiguration{

}

Everything works when I want to pointcut on annotation with ElementType.METHOD, or on a bean with specific name. But Pointcut on annotation with ElementType.TYPE dosen't work. I speculate that is a problem related with annotations that they are readed earlier then AspectJ proxy stand up.

Any idea how to solve this?

Body:
Probably you are not using AspectJ but Spring AOP. So there are a few things to consider:

Usually Spring AOP aspects work on @Components anyway, not on non-Spring stuff. For that you would really need AspectJ. So in a way your Spring AOP aspects look for that annotation anyway.

Spring AOP aspects should be @Components too, but are excluded from aspect weaving automatically. In AspectJ you would need special precautions to exclude one aspect weaving another one bearing the same annotation as normal application code. You would need to consider that in situations where you combine Spring AOP with full AspectJ.

Now as for your AOP question, you cannot intercept joinpoints in an annotated class via @annotation() pointcut, as you already noticed. You need to use @within() instead, e.g.:

@within(org.springframework.stereotype.Component)

Please note that this will intercept all joinpoints in annotated classes, i.e. in the case of Spring AOP all method executions. It will not intercept bean creation, if as your log message suggests that is your goal.


问:
AWS Lambda - unable to import module 'lambda_function'
Like many others before me, I'm trying to run an AWS Lambda function and when I try to test it, I get

"errorMessage": "Unable to import module 'lambda_function'"

My Handler is set to lambda_function.lambda_handler, and I indeed have a file named lambda_function.py which contains a function called lambda_handler. Here's a screenshot as proof:

Everything was working fine when I was writing snippets of code inline in the included IDE, but when I zipped my full program with all of its dependencies and uploaded it, I got the above error.

I'm using the Numpy and Scipy packages, which are quite large. My zipped directory is 34 MB, and my unzipped directory 122 MB. I think this should be fine since the limit is 50 MB for a zipped directory. It appears to be uploading fine, since I see the message:

The deployment package of your Lambda function "one-shot-image-classification" is too large to enable inline code editing. However, you can still invoke your function right now.

I've seen that some posts solve this by using virtualenv, but I'm not familiar with that technology and I'm not sure how to use it properly.

I've also seen some posts saying that sometimes dependencies have dependencies and I may need to include those, but I'm not sure how to find this out.

Here's the top portion of lambda_function.py, which should be enough to see the libraries I'm using and that I do indeed have a lambda_handler function:

```<code>import os
import boto3
import numpy as np
from scipy.ndimage import imread
from scipy.spatial.distance import cdist

def lambda_handler(event, context):

    s3 = boto3.resource('s3')
</code>```

Here a screenshot of the unzipped version of the directory I'm uploading:

I can also post the policy role that my Lambda is using if that could be an issue.

Any insight is much appreciated!

UPDATE:

Here's one solution I tried:
1. git clone https://github.com/Miserlou/lambda-packages
2. create a folder in Documents called new_lambda
3. copy my lambda_function.py and the numpy folder from the lambda-packages into new_lambda, along with the scipy library that I compiled using Docker for AWS as per the article: https://serverlesscode.com/post/scikitlearn-with-amazon-linux-container/
4. Zip the new_lambda folder by right-clicking it and selecting 'compress'

My results:

Unable to import module 'lambda_function': No module named
  'lambda_function'

To reiterate, my file is named lambda_function.py and contains a function called lambda_handler, which accepts two arguments (as seen above). This information matches that seen in Handler, also seen above.

I am using a Mac computer, if that matters.

UPDATE 2

If I follow the above steps but instead zip the files by directly selecting the files that I want to compress and then right clicking and selecting 'compress', I instead get the error

Unable to import module 'lambda_function': cannot import name 'show_config'

Also, the precompiled lambda-packages says that they are compiled for "at least Python 2.7", but my lambda runtime is 3.6. Could this be an issue?

答:
I had a similar issue:

```<code>Unable to import module 'lib/lambda_function': No module named 'lib/lambda_function'
</code>```

The fix for me and possibly for you, was to include a blank __init__.py in the same directory as lambda_function.py.

Why does __init__.py fix the issue?

I understand that it is needed for the directory (lib in my case, . in yours) to be considered a valid Python package.

Here is the reference doc I based that hypothesis on:
5.2.1. Regular packages - Python 3.7.3 documentation

Body:
Like many others before me, I'm trying to run an AWS Lambda function and when I try to test it, I get

"errorMessage": "Unable to import module 'lambda_function'"

My Handler is set to lambda_function.lambda_handler, and I indeed have a file named lambda_function.py which contains a function called lambda_handler. Here's a screenshot as proof:

Everything was working fine when I was writing snippets of code inline in the included IDE, but when I zipped my full program with all of its dependencies and uploaded it, I got the above error.

I'm using the Numpy and Scipy packages, which are quite large. My zipped directory is 34 MB, and my unzipped directory 122 MB. I think this should be fine since the limit is 50 MB for a zipped directory. It appears to be uploading fine, since I see the message:

The deployment package of your Lambda function "one-shot-image-classification" is too large to enable inline code editing. However, you can still invoke your function right now.

I've seen that some posts solve this by using virtualenv, but I'm not familiar with that technology and I'm not sure how to use it properly.

I've also seen some posts saying that sometimes dependencies have dependencies and I may need to include those, but I'm not sure how to find this out.

Here's the top portion of lambda_function.py, which should be enough to see the libraries I'm using and that I do indeed have a lambda_handler function:

import os
import boto3
import numpy as np
from scipy.ndimage import imread
from scipy.spatial.distance import cdist

def lambda_handler(event, context):

    s3 = boto3.resource('s3')

Here a screenshot of the unzipped version of the directory I'm uploading:

I can also post the policy role that my Lambda is using if that could be an issue.

Any insight is much appreciated!

UPDATE:

Here's one solution I tried:
1. git clone https://github.com/Miserlou/lambda-packages
2. create a folder in Documents called new_lambda
3. copy my lambda_function.py and the numpy folder from the lambda-packages into new_lambda, along with the scipy library that I compiled using Docker for AWS as per the article: https://serverlesscode.com/post/scikitlearn-with-amazon-linux-container/
4. Zip the new_lambda folder by right-clicking it and selecting 'compress'

My results:

Unable to import module 'lambda_function': No module named
  'lambda_function'

To reiterate, my file is named lambda_function.py and contains a function called lambda_handler, which accepts two arguments (as seen above). This information matches that seen in Handler, also seen above.

I am using a Mac computer, if that matters.

UPDATE 2

If I follow the above steps but instead zip the files by directly selecting the files that I want to compress and then right clicking and selecting 'compress', I instead get the error

Unable to import module 'lambda_function': cannot import name 'show_config'

Also, the precompiled lambda-packages says that they are compiled for "at least Python 2.7", but my lambda runtime is 3.6. Could this be an issue?

Body:
I had a similar issue:

Unable to import module 'lib/lambda_function': No module named 'lib/lambda_function'

The fix for me and possibly for you, was to include a blank __init__.py in the same directory as lambda_function.py.

Why does __init__.py fix the issue?

I understand that it is needed for the directory (lib in my case, . in yours) to be considered a valid Python package.

Here is the reference doc I based that hypothesis on:
5.2.1. Regular packages - Python 3.7.3 documentation


问:
Template for human readable date time?
{{ now }} gives: 2019-05-30 04:40:35.847147175 +0000 UTC m=+1983611.179295260

and I would like to make this more human readable by grabbing the first 2 and joining = 2019-05-30-04:40:35.847147175.

How can this be done?

Failed attempt:

```<code>time: {{ now || splitList " " | (not sure how to slice first 2) | join "-" }}
</code>```

答:
You should look through the whole list of Sprig date functions, where Sprig is a library of Go template functions that is included in Helm.

In particular you probably want the date function, which formats a time.Time value using a Go format string.  As the linked documentation says:

...take this as the base date: Mon Jan 2 15:04:05 MST 2006  Write it in the format you want.

So try something like

```<code>{{ now | date "2006-01-02 15:04:05.000000" }}
</code>```

The extended examples for the Go (*time.Time).Format function are probably relevant here too; for example, 15:04:05.999999 should drop trailing zeros if that's what you want.

Title: Template for human readable date time?

Body:
{{ now }} gives: 2019-05-30 04:40:35.847147175 +0000 UTC m=+1983611.179295260

and I would like to make this more human readable by grabbing the first 2 and joining = 2019-05-30-04:40:35.847147175.

How can this be done?

Failed attempt:

time: {{ now || splitList " " | (not sure how to slice first 2) | join "-" }}

Body:
You should look through the whole list of Sprig date functions, where Sprig is a library of Go template functions that is included in Helm.

In particular you probably want the date function, which formats a time.Time value using a Go format string.  As the linked documentation says:

...take this as the base date: Mon Jan 2 15:04:05 MST 2006  Write it in the format you want.

So try something like

{{ now | date "2006-01-02 15:04:05.000000" }}

The extended examples for the Go (*time.Time).Format function are probably relevant here too; for example, 15:04:05.999999 should drop trailing zeros if that's what you want.


问:
Join strings by space using pandas aggregate function
I have a CSV file that contains rows with some similar id's. I found a nice approach doing this with dataframe and I found the code doing this from [this] 1 post.

Sample CSV file:

```<code>    id               messages
0   11  I am not driving home
1   11      Please pick me up
2   11     I don't have money
3  103   The car already park
4  103     No need for ticket
5  104       I will buy a car
6  104       I will buy a car
</code>```

Desired output is:

Sample CSV file:

```<code>id   messages
011   I am not driving home Please pick me up I don't have money
103   The car already park No need for ticket
104   I will buy a car
</code>```

Now the code that I have so far is:

aggregation_functions = {'message':'sum'}
df_new = df.groupby(df['id']).aggregate(aggregation_functions)

```
<p>Now what I am getting with this code is:</p>
```id   messages
011   I am not driving homePlease pick me upI don't have money
103   The car already parkNo need for ticket
104   I will buy a car
```
<p>I just want to have the space between words (eg. "homePlease" > "home Please") and avoid redundancy such as having two times of <code>I will buy a car</code>.</p>
<p>I already checked the post 2 but I couldn't find my answer.</p>
<p>Also do i need to use <code>.reindex(columns=df.columns)</code> after the <code>aggregate(aggregation_functions)</code></p>
<p>Like:</p>
```df_new = df.groupby(df['id']).aggregate(aggregation_functions).reindex(columns=df.columns)
```

答:
you can better use apply with join:

```<code>>>> df
    id               messages
0   11  I am not driving home
1   11      Please pick me up
2   11     I don't have money
3  103   The car already park
4  103     No need for ticket
5  104       I will buy a car
6  104       I will buy a car

>>> df.groupby('id')['messages'].apply(lambda x: ' '.join(x))
id
11     I am not driving home Please pick me up I don'...
103              The car already park No need for ticket
104                    I will buy a car I will buy a car
Name: messages, dtype: object
</code>```

Body:
I have a CSV file that contains rows with some similar id's. I found a nice approach doing this with dataframe and I found the code doing this from [this] 1 post.

Sample CSV file:

    id               messages
0   11  I am not driving home
1   11      Please pick me up
2   11     I don't have money
3  103   The car already park
4  103     No need for ticket
5  104       I will buy a car
6  104       I will buy a car

Desired output is:

Sample CSV file:

id   messages
011   I am not driving home Please pick me up I don't have money
103   The car already park No need for ticket
104   I will buy a car

Now the code that I have so far is:

aggregation_functions = {'message':'sum'}
df_new = df.groupby(df['id']).aggregate(aggregation_functions)

Now what I am getting with this code is:

id   messages
011   I am not driving homePlease pick me upI don't have money
103   The car already parkNo need for ticket
104   I will buy a car

I just want to have the space between words (eg. "homePlease" > "home Please") and avoid redundancy such as having two times of I will buy a car.

I already checked the post 2 but I couldn't find my answer.

Also do i need to use .reindex(columns=df.columns) after the aggregate(aggregation_functions)

Like:

df_new = df.groupby(df['id']).aggregate(aggregation_functions).reindex(columns=df.columns)

Body:
you can better use apply with join:

>>> df
    id               messages
0   11  I am not driving home
1   11      Please pick me up
2   11     I don't have money
3  103   The car already park
4  103     No need for ticket
5  104       I will buy a car
6  104       I will buy a car

>>> df.groupby('id')['messages'].apply(lambda x: ' '.join(x))
id
11     I am not driving home Please pick me up I don'...
103              The car already park No need for ticket
104                    I will buy a car I will buy a car
Name: messages, dtype: object


答:
To remove redundancy, I suggest GroupBy.unique followed by str.join:

```<code>df.groupby('id')['messages'].unique().str.join(' ')
</code>```

Alternatively, using GroupBy.agg with set + ' '.join:

```<code>df.groupby('id')['messages'].agg(lambda x: ' '.join(set(x)))
</code>```

Both print,

```<code># id
# 11     I don't have money I am not driving home Pleas...
# 103              No need for ticket The car already park
# 104                                     I will buy a car
# Name: messages, dtype: object
</code>```

To return a DataFrame, call reset_index at the end... for example,

```<code>df.groupby('id')['messages'].unique().str.join(' ').reset_index()

#     id                                           messages
# 0   11  I am not driving home Please pick me up I don'...
# 1  103            The car already park No need for ticket
# 2  104                                   I will buy a car
</code>```

Title: Join strings by space using pandas aggregate function

Body:
To remove redundancy, I suggest GroupBy.unique followed by str.join:

df.groupby('id')['messages'].unique().str.join(' ')

Alternatively, using GroupBy.agg with set + ' '.join:

df.groupby('id')['messages'].agg(lambda x: ' '.join(set(x)))

Both print,

# id
# 11     I don't have money I am not driving home Pleas...
# 103              No need for ticket The car already park
# 104                                     I will buy a car
# Name: messages, dtype: object

To return a DataFrame, call reset_index at the end... for example,

df.groupby('id')['messages'].unique().str.join(' ').reset_index()

#     id                                           messages
# 0   11  I am not driving home Please pick me up I don'...
# 1  103            The car already park No need for ticket
# 2  104                                   I will buy a car


问:
What is the label attribute used for in the Navigation component?
According to the docs:

The Label field contains the name of the destination’s XML layout
  file.

Fair enough, but I can't seem to find a use for it. Why does the layout file need to be named?

```<code><fragment
    android:id="@+id/blank"
    android:name="com.example.app.BlankFragment"
    android:label="Blank"
    tools:layout="@layout/fragment_blank"/>
</code>```

Is the label attribute strictly for the internal workings of the Navigation framework, and not something I should worry about?

答:
As per the Update UI components with NavigationUI documentation:

NavigationUI contains methods that automatically update content in your top app bar as users navigate through your app. For example, NavigationUI uses the destination labels from your navigation graph to keep the title of the top app bar up-to-date.

When using NavigationUI with the top app bar methods discussed below, the label you attach to destinations can be automatically populated from the arguments provided to the destination by using the format of {argName} in your label.

Just like any other information attached to each destination, it can also be used in a custom OnDestinationChangedListener if you have other UI that needs to be updated with a label for the current destination.

Body:
According to the docs:

The Label field contains the name of the destination’s XML layout
  file.

Fair enough, but I can't seem to find a use for it. Why does the layout file need to be named?

<fragment
    android:id="@+id/blank"
    android:name="com.example.app.BlankFragment"
    android:label="Blank"
    tools:layout="@layout/fragment_blank"/>

Is the label attribute strictly for the internal workings of the Navigation framework, and not something I should worry about?


问:
MySQL Insert special characters
I had a registration form which will insert into a member table, the collation is in utf8_general_ci, and I use SET NAMES utf8 in php script, OK here is the problem, I can't insert a string other than pure alphabet, I try input 'Hélène' in a form field, after the sql query run, I check with my db table, the field is inserted as 'H', the rest of the alphabet cannot be insert whenever the string come with special alphabet such as é, ř on behind.

Can someone please help? thanks.

SOLUTION:

```<code><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

mysql_query("SET NAMES utf8");
</code>```

above two line is crucial part to accept input into database and output on a webpage.

Thanks everyone for the advise.

答:
The reason you are not able to do so is because PHP prevents a set of special characters to be sent to database to avoid things like sql injection. You can use the escape string function if you wish to escape but the best way to do so is by using the prepared statements.</p>

```<code>$connection = <"Your database connection">;
$userinput = "Special characters Hélène";
$stmt = $con->prepare("insert into `table` (`fieldname`)values(?)");
$stmt->bind_param("s",$input);
$stmt->execute();
</code>```

Title: MySQL Insert special characters

Body:
I had a registration form which will insert into a member table, the collation is in utf8_general_ci, and I use SET NAMES utf8 in php script, OK here is the problem, I can't insert a string other than pure alphabet, I try input 'Hélène' in a form field, after the sql query run, I check with my db table, the field is inserted as 'H', the rest of the alphabet cannot be insert whenever the string come with special alphabet such as é, ř on behind.

Can someone please help? thanks.

SOLUTION:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

mysql_query("SET NAMES utf8");

above two line is crucial part to accept input into database and output on a webpage.

Thanks everyone for the advise.

Body:
The reason you are not able to do so is because PHP prevents a set of special characters to be sent to database to avoid things like sql injection. You can use the escape string function if you wish to escape but the best way to do so is by using the prepared statements.

$connection = <"Your database connection">;
$userinput = "Special characters Hélène";
$stmt = $con->prepare("insert into `table` (`fieldname`)values(?)");
$stmt->bind_param("s",$input);
$stmt->execute();


问:
Instant app (app bundle) installable activity and instant activity
I struggle to define a good instant app architecture for my app.
Currently the app is in an old style instant app structure.
Right now I am converting it to dynamic modules. So far i have it working for the installable version. But I struggle to get the instant features working, because I don't know how to properly define an entry point.
The app is single activity only and uses deeplinks to navigate.
In the old instant app architecture I used to put in each feature module a seperate manifest.xml with its own activity. The installable module had something similar. Now with dynamic modules you have to point from the base manifest.xml to one single activity which should also be located in the same base module.

But this is not what I want. The installable activity is a lot different than the instant app one.

I have currently the following modules:

Base

Combined

Feature_A

Feature_B

Feature_C

The combined module is basically the installable version of the app.
It includes all the features modules and has one single activity.
It also contains lots of extra functionality which is not needed in any feature module.
Feature modules are just fragments and logic.
Base module contains all shared logic.

Now I have the following questions:

Within the manifest.xml in the base module, the default activity has to be defined. It is right now pointing to my combined (installable) module's activity.
Idealy for instant apps i want to have a different default activity. Is this possible?

I can create an activity inside the base module. But from there i cannot reach any class / activity in any module. So it is not an option to create an intermediate activity in the base module and from there, depending if its an instant or installed, load the right activity. How to deal with this?

Do I need to add entry points (url intent filters) in the base manifest or in each dynamic module?

答:
First, let me introduce you to blog: A simpler experience for instant apps, Create an instant-enabled app bundle and About Android App Bundles

dist:onDemand | dist:instant

false | true = instant-app module, will also be included in installed-app

false | false = installed-only module

true | false = "on-demand" installed-only module

Second, in the new model, you'll notice that com.android.application is now the "base". Ok, easy, your "old base", that was once a com.android.feature, will now be all inside com.android.application (confusing at first, but this is now essentially acting like a library module?? yep!)

Ok, I'm assuming your "Combined" used to be the com.android.application module? You can put that into a dynamic-feature module: false | false (installed), this will confine it to the installed-app.

Your "Feature_X" modules, previously your non-base com.android.feature modules, can now all each be a dynamic-feature module enabled for instant: false | true (instant).

Now, default activity is still the same for you, I think. Your installed-app's MainActivity is in "Combined", right? And Instant Apps has always relied on the location of the default-url for its Try Now, wherever you set that. So, I think this is still the same for you?

The "cannot reach" issue now is that none of these modules see each other, except base/application sitting at the root. Unlike before, Combined/app could at least see all the features as libraries. Now, you'll need resort to calling them by their class name or by their intent-filter/urls or etc..

Entry points? It should be a similar setup as before:

As installed-app: base + combined + a + b + c

As instant-app: base + (a , b , c)

But did I misread? Your current old-model feature modules contain only "fragments" for your MainActivity? No activity of their own or an individual activity per to hold each one? (Then as an installed-app, those activities would be ignored, and only the fragments would be collected for the single installed-app's activity?)

In any case, you could also look into exploring SplitInstall to use while as an instant app. (yes, you can also use this split install on instant modules)


问:
How to create a voice channel by reacting on embed?
I'm trying to use this code to create an embed, if you react on it a specific voice channel will be created on the server.
That's very similar to roles menu, but it will not give you a role, it will create a channel.

The code is working, but when you react on the embed the bot do nothing.

module.exports = {
    name: 'cc',
    description: 'Help!',
    execute(message) {
    const embed = {"image": {"url": `${message.author.displayAvatarURL}`}}
    message.channel.send({embed})
    .then((message) => { message.react("❤") })
    .then(() => {
        const filter = (reaction, user) => reaction.emoji.name === "❤" && user.id === message.author.id;
        const collectorForU = message.createReactionCollector(filter, {time: 1000/*time in ms*/});
        collectorForU.on("collect", () => {message.guild.createChannel("╔═════ஜ۞ஜ═════╗", "voice")})
})
}
};
```

There is no error on the console.

答: The reaction collector expires before anything can be collected; the time option is set to 1 second.

Body:
I'm trying to use this code to create an embed, if you react on it a specific voice channel will be created on the server.
That's very similar to roles menu, but it will not give you a role, it will create a channel.

The code is working, but when you react on the embed the bot do nothing.

module.exports = {
    name: 'cc',
    description: 'Help!',
    execute(message) {
    const embed = {"image": {"url": `${message.author.displayAvatarURL}`}}
    message.channel.send({embed})
    .then((message) => { message.react("❤") })
    .then(() => {
        const filter = (reaction, user) => reaction.emoji.name === "❤" && user.id === message.author.id;
        const collectorForU = message.createReactionCollector(filter, {time: 1000/*time in ms*/});
        collectorForU.on("collect", () => {message.guild.createChannel("╔═════ஜ۞ஜ═════╗", "voice")})
})
}
};

There is no error on the console.


问:
How to combine getElementById with different Id name
It is possible to combine getElementById with different id name? How to achieve it?

function onOpen(){
    var x1 = document.getElementById("header");
    var x2 = document.getElementById("menu");
    var x3 = document.getElementById("program");
    x1.style.filter = "blur(5px)"
    x2.style.filter = "blur(5px)"
    x3.style.filter = "blur(5px)"
}
```

答: Id's are unique so as far as I know you can't select more than one at a time. You can however select multiple classes with document.getElementsByClass and have one class specified for all of them.</p>


问:
How to know how often an external link is clicked?
This page: http://funds.ft.com/CityofLondon/investmentmanagement/HCEWUR contains a number of links under the section "Annual Reports & Factsheets". The content these links point at is hosted at fundslibrary.co.uk, a 3rd party supplier.

Is there any way for us to track how often these links are clicked? We don't have access to the 3rd party web server logs.

One way I'm thinking is to POST an instruction to increment a count with jQuery every time the link is clicked, but that would mean us having to maintain the count.

Is there any functionality in Google Analytics that could give us this info?

答:
I can see that you're using the old version of the GA tracking script (not the newer asynchronous version) and that you're opening the links an a new window (using target="_blank" in the  tag). Given this you just need to add code to register a page view when the link is clicked:

```<code>onClick="pageTracker._trackPageview('page_name');"
</code>```

This will register a page view against a page called page_name that will appear in reports. This type of page view is called a "virtual Page View". You should, of course, choose suitable names to put into the reports based on where the links are going. You could possibly extract the names from the href of the link.

Note that another way of doing this would be to use event tracking instead of virtual page views but the basic idea would remain the same (call it in the onClick event). Different people have different opinions about which one to use so you should read up on it to decide what's more useful for your situation.

Also note that if you weren't opening a new window/tab for the link then you would need to use a timeout to delay loading of the new page for a few milliseconds until the tracking beacon had been transmitted.

Body:
I can see that you're using the old version of the GA tracking script (not the newer asynchronous version) and that you're opening the links an a new window (using target="_blank" in the <a> tag). Given this you just need to add code to register a page view when the link is clicked:

onClick="pageTracker._trackPageview('page_name');"

This will register a page view against a page called page_name that will appear in reports. This type of page view is called a "virtual Page View". You should, of course, choose suitable names to put into the reports based on where the links are going. You could possibly extract the names from the href of the link.

Note that another way of doing this would be to use event tracking instead of virtual page views but the basic idea would remain the same (call it in the onClick event). Different people have different opinions about which one to use so you should read up on it to decide what's more useful for your situation.

Also note that if you weren't opening a new window/tab for the link then you would need to use a timeout to delay loading of the new page for a few milliseconds until the tracking beacon had been transmitted.


问:
tabindex -1 not working for child elements
I have a div tag with some content getting loaded inside it. The content inside can have buttons, anchor elements, etc. which are focusable. I do not have control over the content but I can modify the 'div' tag attributes.

My problem is the focus still goes to the content (anchor, buttons, etc.) even if I specify the tabIndex -1 to the div tag.

    ...
    <button>click me</button>

```

Is there a way to skip the entire content while tabbing ? It's certainly not working with the above code.

答:
It is possible leave an element BOTH visible and unfocusable, together with its children.

It's done via the HTML property inert: https://html.spec.whatwg.org/multipage/interaction.html#inert.

It's not widely supported yet, but there is a polyfill: https://github.com/WICG/inert.

npm install --save wicg-inert

```<code>require('wicg-inert')

<section inert>
  I am visible, but not focusable!
</section>
</code>```

Body:
I have a div tag with some content getting loaded inside it. The content inside can have buttons, anchor elements, etc. which are focusable. I do not have control over the content but I can modify the 'div' tag attributes.

My problem is the focus still goes to the content (anchor, buttons, etc.) even if I specify the tabIndex -1 to the div tag.

    ...
    <button>click me</button>

Is there a way to skip the entire content while tabbing ? It's certainly not working with the above code.

Body:
It is possible leave an element BOTH visible and unfocusable, together with its children.

It's done via the HTML property inert: https://html.spec.whatwg.org/multipage/interaction.html#inert.

It's not widely supported yet, but there is a polyfill: https://github.com/WICG/inert.

npm install --save wicg-inert

require('wicg-inert')

<section inert>
  I am visible, but not focusable!
</section>


问:
The meaning and scenario of RPC streaming?
I see the following 4 types of RPC in grpc document:

```<code> - rpc SayHello(HelloRequest) returns (HelloResponse) {...}
 - rpc LotsOfReplies(HelloRequest) returns (stream HelloResponse) {...}
 - rpc LotsOfGreetings(stream HelloRequest) returns (HelloResponse) {...}
 - rpc BidiHello(stream HelloRequest) returns (stream HelloResponse) {...}
</code>```

which means both the request and response can be single one or a sequence of message. Does the streaming request means that one can pack args of multiple invocation in the stream, implementing batch remote procedure call?

And, I'm very confused about the scenario where a stream of response is needed. What's the scenario of streaming response?

答:
There are 4 types of RPCs:

Unary: Client sends a single request to the server, and server sends a single response

Server streaming: Client sends a single message to the server. Server responds with an ordered sequence of messages. Client reads from the stream until there are no more messages.

Client streaming: Client sends an ordered sequence of message to the server. Server reads the messages from the client and sends a response.

Bidirectional streaming: Both client and server send ordered sequences of messages to each other. The client and server streams are independent of each other.

Take a look at https://grpc.io/docs/guides/concepts/ for more info.

Body:
I see the following 4 types of RPC in grpc document:

 - rpc SayHello(HelloRequest) returns (HelloResponse) {...}
 - rpc LotsOfReplies(HelloRequest) returns (stream HelloResponse) {...}
 - rpc LotsOfGreetings(stream HelloRequest) returns (HelloResponse) {...}
 - rpc BidiHello(stream HelloRequest) returns (stream HelloResponse) {...}

which means both the request and response can be single one or a sequence of message. Does the streaming request means that one can pack args of multiple invocation in the stream, implementing batch remote procedure call?

And, I'm very confused about the scenario where a stream of response is needed. What's the scenario of streaming response?