问:
setTimeout not working in Greasemonkey user script when JS disabled in browser
I'm working on a project that requires my user script be run on pages as they are rendered without executing any of the page's JavaScript. That is to say, we need to browse with JavaScript disabled.

I've encountered a problem though when I try to delay execution of a function within my script. Whenever I make a call to window.setTimeout, the function I pass in never gets executed.

I think maybe this function is actually getting called on unsafeWindow instead of window. Is there any workaround for this?

I should mention that calls to setTimeout work fine when JavaScript is enabled and everything else in my script is working fine without enabling JavaScript.

Thanks for your help!

答:
this can be patched like this:

You can say NO to NoScript + setTimeout = failed

In greasemonkey.js: find [ injectScripts ]: function..... add our GM-api.....

Add this code:

```<code>sandbox.setTimeOut = function (callback, timeout, p1,p2,p3/*....*/){
    var args = Array.prototype.slice.call(arguments,2);
    return  sandbox.window.setTimeout(function(){
        return callback.apply(sandbox, args);
    } ,timeout);
}
</code>```

or

```<code>sandbox.setInterval = function (callback, timeout, p1,p2,p3/*....*/){
    var args = Array.prototype.slice.call(arguments,2);
    return sandbox.window.setInterval(function(){
        return callback.apply(sandbox, args);
    } ,timeout);
}
</code>```

This code is working fine, I have used it since May 2010.

In user.js you can test it like this:

```<code>setTimeout(alert,1000, 'i am happy');
var loopid = setInterval(alert, 1000, 'I am happy again');
setTimeout(clearInterval, 5000, loopid);

var j=300;
for(;~j;j--){ //running perfectly!
    setTimeout(alert, 1000+20*j, 'I am happy' )
}
</code>```

Solution 2

```<code>sandbox.kk_setTimeout = function (func, timeout, repeat_type, p1,p2,p3/*....*/){
    var callback = { k100: sandbox };
    var args = Array.slice.call(arguments,3);

    // repeat_type:  0=once  1=repeatng, after fired stopped    2=always repeat
    if(repeat_type!=2){
        callback.notify = function (timer){ func.apply(this.k100,args); }
        var timerCC = Components.Constructor("@mozilla.org/timer;1", "nsITimer", 'initWithCallback');
        var R = repeat_type?1:0;
    } else {
        callback.observe = function (subject, topic, data) { func.call(this.k100); };
        var timerCC = Components.Constructor("@mozilla.org/timer;1", "nsITimer", 'init');
        var R = 2;
    }
    return new timerCC(callback, timeout, R);
}

// now have to test it:

var test100 = kk_setTimeout(alert, 1000, 0, 'i am timer');  //running = setTimeout
var test100 = kk_setTimeout(alert, 1000, 2, 'i am timer');  //running = setInterval
test100.cancal() ;   //clear it by cancel() method

kk_setTimeout(alert, 1000+20*j, 2, 'i am happy' );
var j=300;
for(;~j;j--){
    kk_setTimeout(alert, 1000+20*j, 0, 'i am happy 2' );
}

//bug:
//this solution 2 running after about 3-8 times differently stop, why bug ? i don't know.
// you will fail to use many times(over 3-8 time) kk_timeout(); or using repeat_type = 2 after fired 3-8 times timeout
//or running total time max about 20-30 seconds stop
//--- this maybe stop by option in about:config -- about [max javascript run time]
</code>```

china-kkmove patched

edit to add…

Sorry everyone,

There are still a few patches to the code that I forgot to write:

```<code>sandbox.window = sandbox._proto_; // add this line also to the solution 1#
</code>```

This error just came to my mind this morning.

Body:
this can be patched like this:

You can say NO to NoScript + setTimeout = failed

In greasemonkey.js: find [ injectScripts ]: function..... add our GM-api.....

Add this code:

sandbox.setTimeOut = function (callback, timeout, p1,p2,p3/*....*/){
    var args = Array.prototype.slice.call(arguments,2);
    return  sandbox.window.setTimeout(function(){
        return callback.apply(sandbox, args);
    } ,timeout);
}

or

sandbox.setInterval = function (callback, timeout, p1,p2,p3/*....*/){
    var args = Array.prototype.slice.call(arguments,2);
    return sandbox.window.setInterval(function(){
        return callback.apply(sandbox, args);
    } ,timeout);
}

This code is working fine, I have used it since May 2010.

In user.js you can test it like this:

setTimeout(alert,1000, 'i am happy');
var loopid = setInterval(alert, 1000, 'I am happy again');
setTimeout(clearInterval, 5000, loopid);

var j=300;
for(;~j;j--){ //running perfectly!
    setTimeout(alert, 1000+20*j, 'I am happy' )
}

Solution 2

sandbox.kk_setTimeout = function (func, timeout, repeat_type, p1,p2,p3/*....*/){
    var callback = { k100: sandbox };
    var args = Array.slice.call(arguments,3);

    // repeat_type:  0=once  1=repeatng, after fired stopped    2=always repeat
    if(repeat_type!=2){
        callback.notify = function (timer){ func.apply(this.k100,args); }
        var timerCC = Components.Constructor("@mozilla.org/timer;1", "nsITimer", 'initWithCallback');
        var R = repeat_type?1:0;
    } else {
        callback.observe = function (subject, topic, data) { func.call(this.k100); };
        var timerCC = Components.Constructor("@mozilla.org/timer;1", "nsITimer", 'init');
        var R = 2;
    }
    return new timerCC(callback, timeout, R);
}

// now have to test it:

var test100 = kk_setTimeout(alert, 1000, 0, 'i am timer');  //running = setTimeout
var test100 = kk_setTimeout(alert, 1000, 2, 'i am timer');  //running = setInterval
test100.cancal() ;   //clear it by cancel() method

kk_setTimeout(alert, 1000+20*j, 2, 'i am happy' );
var j=300;
for(;~j;j--){
    kk_setTimeout(alert, 1000+20*j, 0, 'i am happy 2' );
}

//bug:
//this solution 2 running after about 3-8 times differently stop, why bug ? i don't know.
// you will fail to use many times(over 3-8 time) kk_timeout(); or using repeat_type = 2 after fired 3-8 times timeout
//or running total time max about 20-30 seconds stop
//--- this maybe stop by option in about:config -- about [max javascript run time]

china-kkmove patched

edit to add…

Sorry everyone,

There are still a few patches to the code that I forgot to write:

sandbox.window = sandbox._proto_; // add this line also to the solution 1#

This error just came to my mind this morning.


来源: stackexchange

问:
Python requests post error.. can't decoding
```<code>api_url = "https://en.coinjinja.com/api/events/search"
headers = {'origin': 'https://en.coinjinja.com',
        'accept-encoding': 'gzip, deflate, br',
        'accept-language': 'ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7',
        'authority': 'en.coinjinja.com',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36',
        'content-type': 'application/json',
        'content-length': '126',
        'accept': '*/*',
        'referer': 'https://en.coinjinja.com/events/time/next_week/tags/hardfork+airdrop+burn+exchange+partnership'
    }
    data = {"start": "2020-02-17","end":"2020-02-24","symbol":"","types":["hardfork","airdrop","burn","exchange","partnership"]}
    api_request = requests.post(api_url, headers=headers, data=json.dumps(data))
    print(api_request.headers)
    print(api_request.encoding)
    print(api_request.content.decode('utf-8','ignore'))
</code>```

答: You need to install brotli package to work with 'Content-Encoding': 'br'. It's duplicate of unable to decode Python web request

ContentLicense: CC BY-SA 4.0


问:
Post requisition failed
I'm trying to make a POST request, to convert and download a file to pdf, but I have this error:
documento.service.ts :

```<code>  download(documento: IDocumento) {
    return this.http.post(SERVER_API_URL + "api/download/", documento).subscribe((response) => {
      saveAs(response, documento.tituloDocumento + "." + "pdf");
    });
  }
</code>```

DocumentResource

```<code>    @RequestMapping(value = "/download", method = RequestMethod.POST)
public void download(HttpServletResponse response, @RequestBody DocumentoDTO documentoDTO) throws IOException {
    File file = new File(documentoDTO.getPathorigdoc());
    response.setContentType("pdf");
    response.setHeader("Content-disposition", "attachment;" + documentoDTO.getTituloDocumento());
    response.getOutputStream().write(Files.readAllBytes(file.toPath()));
}

</code>```

```<code>Access to XMLHttpRequest at 'https://autenticacao.campogrande.ms.gov.br/auth/realms/dev/protocol/openid-connect/auth?response_type=code&client_id=web_app&scope=openid%20offline_access%20profile%20email%20address%20phone%20roles%20web-origins%20jhipster&state=DooRYbdfmKCip2apn-NOTWQOqWBGkeh-AigMtoJVfcM%3D&redirect_uri=http://localhost:9000/login/oauth2/code/oidc' (redirected from 'http://localhost:9000/api/download/') from origin 'http://localhost:9000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
autenticacao.campogrande.ms.gov.br/auth/realms/dev/protocol/openid-connect/auth?response_type=code&client_id=web_app&scope=openid%20offline_access%20profile%20email%20address%20phone%20roles%20web-origins%20jhipster&state=DooRYbdfmKCip2apn-NOTWQOqWBGkeh-AigMtoJVfcM%3D&redirect_uri=http://localhost:9000/login/oauth2/code/oidc:1 Failed to load resource: net::ERR_FAILED
webpack-internal:///./node_modules/@angular/core/fesm5/core.js:6249 ERROR HttpErrorResponse
</code>```

答:
I don't know what server are you using, but you need to modify the headers value in the service ( an example in java)

How to handle CORS using JAX-RS with Jersey

Title: Post requisition failed

Body:
I'm trying to make a POST request, to convert and download a file to pdf, but I have this error:
documento.service.ts :

  download(documento: IDocumento) {
    return this.http.post(SERVER_API_URL + "api/download/", documento).subscribe((response) => {
      saveAs(response, documento.tituloDocumento + "." + "pdf");
    });
  }

DocumentResource

    @RequestMapping(value = "/download", method = RequestMethod.POST)
public void download(HttpServletResponse response, @RequestBody DocumentoDTO documentoDTO) throws IOException {
    File file = new File(documentoDTO.getPathorigdoc());
    response.setContentType("pdf");
    response.setHeader("Content-disposition", "attachment;" + documentoDTO.getTituloDocumento());
    response.getOutputStream().write(Files.readAllBytes(file.toPath()));
}

Access to XMLHttpRequest at 'https://autenticacao.campogrande.ms.gov.br/auth/realms/dev/protocol/openid-connect/auth?response_type=code&client_id=web_app&scope=openid%20offline_access%20profile%20email%20address%20phone%20roles%20web-origins%20jhipster&state=DooRYbdfmKCip2apn-NOTWQOqWBGkeh-AigMtoJVfcM%3D&redirect_uri=http://localhost:9000/login/oauth2/code/oidc' (redirected from 'http://localhost:9000/api/download/') from origin 'http://localhost:9000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
autenticacao.campogrande.ms.gov.br/auth/realms/dev/protocol/openid-connect/auth?response_type=code&client_id=web_app&scope=openid%20offline_access%20profile%20email%20address%20phone%20roles%20web-origins%20jhipster&state=DooRYbdfmKCip2apn-NOTWQOqWBGkeh-AigMtoJVfcM%3D&redirect_uri=http://localhost:9000/login/oauth2/code/oidc:1 Failed to load resource: net::ERR_FAILED
webpack-internal:///./node_modules/@angular/core/fesm5/core.js:6249 ERROR HttpErrorResponse


问:
crash app when upload the image from gallery to firebase storage
when the app is crashing , it says :

```<code>"java.lang.NoSuchMethodError: No virtual method getToken(Z)Lcom/google/android/gms/tasks/Task; in class Lcom/google/firebase/FirebaseApp; or its super classes (declaration of 'com.google.firebase.FirebaseApp' appears in /data/app/com.example.minisign-uZwwNJVtsjlOVpgpqIRyHQ==/base.apk)at com.google.firebase.storage.internal.Util.getCurrentAuthToken(com.google.firebase:firebase-storage@@16.0.4:148)"
</code>```

I have tried many things but didn't solve it .
My code :

```<code>final StorageReference fileReference=storageReference.child(imageuri.getLastPathSegment()+"."+getfileExtension(imageuri));
            uploadTask=fileReference.putFile(imageuri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    // Get a URL to the uploaded content
                    //Uri downloadUrl = taskSnapshot.getUploadSessionUri();
                    //pd.dismiss();
                    Toast.makeText(SettingsActivity.this, "Image Uploaded!!", Toast.LENGTH_SHORT).show();
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    Toast.makeText(SettingsActivity.this,"Failed!",Toast.LENGTH_SHORT).show();
                    //pd.dismiss();
                }
            });
           }
</code>```

and for my gradle :

```<code>{implementation 'com.google.firebase:firebase-analytics:17.2.2'
implementation 'com.google.firebase:firebase-storage:16.0.4'

implementation 'com.firebaseui:firebase-ui-database:1.2.0'

implementation 'com.google.firebase:firebase-auth:19.2.0'

implementation 'com.google.firebase:firebase-database:19.2.0'}
</code>```

答: Always make sure you are using the latest versions of all the libraries, as shown in the release notes.  You are also very behind on the version of Firebase-UI.  The latest is 6.2.0.</p>

Body:
when the app is crashing , it says :

"java.lang.NoSuchMethodError: No virtual method getToken(Z)Lcom/google/android/gms/tasks/Task; in class Lcom/google/firebase/FirebaseApp; or its super classes (declaration of 'com.google.firebase.FirebaseApp' appears in /data/app/com.example.minisign-uZwwNJVtsjlOVpgpqIRyHQ==/base.apk)at com.google.firebase.storage.internal.Util.getCurrentAuthToken(com.google.firebase:firebase-storage@@16.0.4:148)"

I have tried many things but didn't solve it .
My code :

final StorageReference fileReference=storageReference.child(imageuri.getLastPathSegment()+"."+getfileExtension(imageuri));
            uploadTask=fileReference.putFile(imageuri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    // Get a URL to the uploaded content
                    //Uri downloadUrl = taskSnapshot.getUploadSessionUri();
                    //pd.dismiss();
                    Toast.makeText(SettingsActivity.this, "Image Uploaded!!", Toast.LENGTH_SHORT).show();
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    Toast.makeText(SettingsActivity.this,"Failed!",Toast.LENGTH_SHORT).show();
                    //pd.dismiss();
                }
            });
           }

and for my gradle :

{implementation 'com.google.firebase:firebase-analytics:17.2.2'
implementation 'com.google.firebase:firebase-storage:16.0.4'

implementation 'com.firebaseui:firebase-ui-database:1.2.0'

implementation 'com.google.firebase:firebase-auth:19.2.0'

implementation 'com.google.firebase:firebase-database:19.2.0'}


问:
How to make a select on different table in function of an argument?
In function of myVariable, this select is made from a different table.

```<code>select
     *
from
    table(decode(myVariable,1,sys.odcinumberlist(1,2),sys.odcinumberlist(3)))
</code>```

result

if myVAriable =1 then 1,2
else                  3

I would like to to make the same thing but instead of having sys.odcinumberlist, I would like to have the list of all integer inferior than 100.

I have tried a lot of way to do that. This for instance, but none has worked

```<code>select *
from
    table(decode(myvariable,1,table(select level from dual connect by level<100),sys.odcinumberlist(3)))
</code>```

wanted result:

myvariable =1  then 1,2,3....99
else                 3

答:
You have to cast this subquery as odcinumberlist:

```<code>select * from
    table(decode(myvariable, 1,
                   cast(multiset(
                        select level from dual connect by level<100)
                        as sys.odcinumberlist),
                   sys.odcinumberlist(3)))
</code>```

Body:
In function of myVariable, this select is made from a different table.

select
     *
from
    table(decode(myVariable,1,sys.odcinumberlist(1,2),sys.odcinumberlist(3)))

result

if myVAriable =1 then 1,2
else                  3

I would like to to make the same thing but instead of having sys.odcinumberlist, I would like to have the list of all integer inferior than 100.

I have tried a lot of way to do that. This for instance, but none has worked

select *
from
    table(decode(myvariable,1,table(select level from dual connect by level<100),sys.odcinumberlist(3)))

wanted result:

myvariable =1  then 1,2,3....99
else                 3

Body:
You have to cast this subquery as odcinumberlist:

select * from
    table(decode(myvariable, 1,
                   cast(multiset(
                        select level from dual connect by level<100)
                        as sys.odcinumberlist),
                   sys.odcinumberlist(3)))


问:
direct Global viable access using an "Application" class?
i want to setup a global variable class holder extending "Application" like this one here:

http://trace.adityalesmana.com/2010/08/declare-global-variable-in-android-via-android-app-application/

my question is it possible to access the viable directly instead of calling a method?

(going by the link's example) can "islogin" be declared as:

```<code>public boolean isLogin = true;
</code>```

then accessed like this?:

```<code>if (!combankDroid.isLogin) {
</code>```

答:
You can do what you want: global variables on Application objects work just fine.

The actual solution to your issue is to make the MediaPlayer instance a variable of a Service and then connect to that to fetch/control the MediaPlayer.

ContentLicense: CC BY-SA 3.0

Body:
i want to setup a global variable class holder extending "Application" like this one here:

http://trace.adityalesmana.com/2010/08/declare-global-variable-in-android-via-android-app-application/

my question is it possible to access the viable directly instead of calling a method?

(going by the link's example) can "islogin" be declared as:

public boolean isLogin = true;

then accessed like this?:

if (!combankDroid.isLogin) {


问:
Match two sequences
This may be a trivial question but could you please assist me with that.

There are two sequences with the same length.

var a = new[] {10, 20, 30, 40, 50}

var b = new[] {1, 2, 3, 4, 5}
How to get in result such sequence:

var result = {10 - 1, 20 - 2, 30 - 3, 40 - 4, 50 - 5}

It is desirable to you selectMany or whatever.

Thank you!

Title: Match two sequences

Body:
You are describing Zip:

var a = new[] {10, 20, 30, 40, 50};
var b = new[] {1, 2, 3, 4, 5};

var result = a.Zip(b, (x,y)=> new {X=x, Y=y});


问:
Embedded tomcat giving failed to scan jars from classloader hierarchy
I am newly trying out Embedded tomcat version 8.0.15. Downloaded the maven dependency into my project.

Create the necessary context and instances. Tomcat server is coming up fine.
But I am getting the below warnings

```<code>Jun 17, 2017 9:50:44 PM org.apache.tomcat.util.scan.StandardJarScanner scan
WARNING: Failed to scan  [file:/C:/Users/raghavender.n/.m2/repository/xalan/xalan/2.7.2/xercesImpl.jar] from classloader hierarchy
java.io.FileNotFoundException:C:\Users\raghavender.n\.m2\repository\xalan\xalan\2.7.2\xercesImpl.jar (The system cannot find the file specified)
WARNING: Failed to scan [file:/C:/Users/raghavender.n/.m2/repository/xalan/xalan/2.7.2/xml-apis.jar] from classloader hierarchy
java.io.FileNotFoundException: C:\Users\raghavender.n\.m2\repository\xalan\xalan\2.7.2\xml-apis.jar (The system cannot find the file specified)

<!-- https://mvnrepository.com/artifact/org.apache.tomcat.embed/tomcat-embed-core -->
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-core</artifactId>
    <version>8.5.15</version>
</dependency>
</code>```

How can i disable/avoid the warnings from embedded tomcat jar?

答:
For workaround, in catalina.properties file put the following line:</p>

```<code>tomcat.util.scan.StandardJarScanFilter.jarsToSkip=*.jar
</code>```

Body:
I am newly trying out Embedded tomcat version 8.0.15. Downloaded the maven dependency into my project.

Create the necessary context and instances. Tomcat server is coming up fine.
But I am getting the below warnings

Jun 17, 2017 9:50:44 PM org.apache.tomcat.util.scan.StandardJarScanner scan
WARNING: Failed to scan  [file:/C:/Users/raghavender.n/.m2/repository/xalan/xalan/2.7.2/xercesImpl.jar] from classloader hierarchy
java.io.FileNotFoundException:C:\Users\raghavender.n\.m2\repository\xalan\xalan\2.7.2\xercesImpl.jar (The system cannot find the file specified)
WARNING: Failed to scan [file:/C:/Users/raghavender.n/.m2/repository/xalan/xalan/2.7.2/xml-apis.jar] from classloader hierarchy
java.io.FileNotFoundException: C:\Users\raghavender.n\.m2\repository\xalan\xalan\2.7.2\xml-apis.jar (The system cannot find the file specified)

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-core</artifactId>
    <version>8.5.15</version>
</dependency>

How can i disable/avoid the warnings from embedded tomcat jar?

Body:
For workaround, in catalina.properties file put the following line:

tomcat.util.scan.StandardJarScanFilter.jarsToSkip=*.jar


问:
How can I group and sum multiple columns in CSV file?
I'm still new to python and pandas and currently trying to get sum of multiple columns in a CSV file.

I have a CSV file with columns that I want to sum unitCount, orderCount, invoiceCount:

```<code>     date       id   name   unitCount   orderCount   invoiceCount
 2020-02-12     1   Guitar     200          100           200
 2020-02-12     2   Drums      300          200           100
 2020-02-12     3   Piano      400          700           300
 2020-02-11     1   Guitar     100          500           300
 2020-02-11     2   Drums      200          400           400
 2020-02-11     3   Piano      300          300           100
</code>```

My desired output would be a CSV file with sum of those last 3 columns (grouped by ID) and linked to the latest date only:

```<code>     date       id   name   total_unitCount   total_orderCount   total_invoiceCount
 2020-02-12     1   Guitar        300              600                   500
 2020-02-12     2   Drums         500              600                   500
 2020-02-12     3   Piano         700              1000                  400
</code>```

Would someone be able to help?

so far I was trying the below, but it doesn't work for me. Would be possible to add groupby to the first line of the below code? Or I started completely wrong? Thanks!

```<code>df = pd.read_csv(r'path/to/myfile.csv', sep=';').sum()
df.to_csv(r'path/to/myfile_sum.csv')
</code>```

答:
You can do with somewhat manual agg:

```<code>(df.groupby('id', as_index=False)
   .agg({'date':'max', 'name':'first',
         'unitCount':'sum',
         'orderCount':'sum',
         'invoiceCount':'sum'})
   .to_csv('file.csv')
)
</code>```

Body:
I'm still new to python and pandas and currently trying to get sum of multiple columns in a CSV file.

I have a CSV file with columns that I want to sum unitCount, orderCount, invoiceCount:

     date       id   name   unitCount   orderCount   invoiceCount
 2020-02-12     1   Guitar     200          100           200
 2020-02-12     2   Drums      300          200           100
 2020-02-12     3   Piano      400          700           300
 2020-02-11     1   Guitar     100          500           300
 2020-02-11     2   Drums      200          400           400
 2020-02-11     3   Piano      300          300           100

My desired output would be a CSV file with sum of those last 3 columns (grouped by ID) and linked to the latest date only:

     date       id   name   total_unitCount   total_orderCount   total_invoiceCount
 2020-02-12     1   Guitar        300              600                   500
 2020-02-12     2   Drums         500              600                   500
 2020-02-12     3   Piano         700              1000                  400

Would someone be able to help?

so far I was trying the below, but it doesn't work for me. Would be possible to add groupby to the first line of the below code? Or I started completely wrong? Thanks!

df = pd.read_csv(r'path/to/myfile.csv', sep=';').sum()
df.to_csv(r'path/to/myfile_sum.csv')

Body:
You can do with somewhat manual agg:

(df.groupby('id', as_index=False)
   .agg({'date':'max', 'name':'first',
         'unitCount':'sum',
         'orderCount':'sum',
         'invoiceCount':'sum'})
   .to_csv('file.csv')
)


问:
RabbitMQ Message Consumption ID based (c# API)
i would like to publish/produce a message with some message id, like each message has a particular id..

And at the consumer end i would like to retrieve the messages by prividing the ID.
suppose we have multiple consumers than each one should get only those messages which they requested through the message ids. (i hope i am clear enough).

答:
Although its not by design and its better to use a database for that there is a way to do this using rabbitmq:

Publish a message with id:

```<code>var message = "some message";
var messageId = Guid.NewGuid().ToString();
var factory = new ConnectionFactory { HostName = "localhost" };

using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
    IBasicProperties props = channel.CreateBasicProperties();
    props.MessageId = messageId;

    byte[] messageBodyBytes = Encoding.UTF8.GetBytes(message);

    channel.BasicPublish("", "queueName", true, props, messageBodyBytes);
}
</code>```

Get a message by id:

```<code>var messageId = "id";
var factory = new ConnectionFactory { HostName = "localhost" };

using (var connection = _factory.CreateConnection())
using (var channel = connection.CreateModel())
{
    var queueDeclareResponse = channel.QueueDeclare("queueName", true, true, false, null);

    for (int i = 0; i < queueDeclareResponse.MessageCount; i++)
    {
        var result = channel.BasicGet("queueName", false);
        var id = result.BasicProperties.MessageId;

        if (id == messageId)
        {
            var body = result.Body;
            var message = Encoding.UTF8.GetString(body);

            //Do something with the message

            channel.BasicAck(result.DeliveryTag, false);
            break;
        }
    }
}
</code>```

After channel is disposed all messages that was not acked will requeue.

ContentLicense: CC BY-SA 2.5

Body:
Although its not by design and its better to use a database for that there is a way to do this using rabbitmq:

Publish a message with id:

var message = "some message";
var messageId = Guid.NewGuid().ToString();
var factory = new ConnectionFactory { HostName = "localhost" };

using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
    IBasicProperties props = channel.CreateBasicProperties();
    props.MessageId = messageId;

    byte[] messageBodyBytes = Encoding.UTF8.GetBytes(message);

    channel.BasicPublish("", "queueName", true, props, messageBodyBytes);
}

Get a message by id:

var messageId = "id";
var factory = new ConnectionFactory { HostName = "localhost" };

using (var connection = _factory.CreateConnection())
using (var channel = connection.CreateModel())
{
    var queueDeclareResponse = channel.QueueDeclare("queueName", true, true, false, null);

    for (int i = 0; i < queueDeclareResponse.MessageCount; i++)
    {
        var result = channel.BasicGet("queueName", false);
        var id = result.BasicProperties.MessageId;

        if (id == messageId)
        {
            var body = result.Body;
            var message = Encoding.UTF8.GetString(body);

            //Do something with the message

            channel.BasicAck(result.DeliveryTag, false);
            break;
        }
    }
}

After channel is disposed all messages that was not acked will requeue.


问:
Convert entire column from integer to datetime using SQL
I have a table with an entire column that contains integers. I know that these integers were previously datetime values. I want to update all values in this column to be datetimes. There are 1000+ plus rows. I've altered this column from an INT to varchar since all the errors I received didn't like me going from an INT to DATETIME but I am having the same issue with the varchar data type.

Example values in the column: 43873, 40706, 43873, ect

I have tried the following queries:

```<code>UPDATE WORKER SET INT_TIME = DATEFROMPARTS(INT_TIME,1,1);

UPDATE WORKER SET INT_TIME = CONVERT(datetime,INT_TIME,107);
</code>```

I receive errors like

Conversion failed when converting date and/or time from character
  string.

INT_TIME is the column I am trying to update all values to a datetime:

答:
These look like Excel format.  That suggests something like:</p>

```<code>select dateadd(day, col, '1899-12-30')
</code>```

Body:
I have a table with an entire column that contains integers. I know that these integers were previously datetime values. I want to update all values in this column to be datetimes. There are 1000+ plus rows. I've altered this column from an INT to varchar since all the errors I received didn't like me going from an INT to DATETIME but I am having the same issue with the varchar data type.

Example values in the column: 43873, 40706, 43873, ect

I have tried the following queries:

UPDATE WORKER SET INT_TIME = DATEFROMPARTS(INT_TIME,1,1);

UPDATE WORKER SET INT_TIME = CONVERT(datetime,INT_TIME,107);

I receive errors like

Conversion failed when converting date and/or time from character
  string.

INT_TIME is the column I am trying to update all values to a datetime:

Body:
These look like Excel format.  That suggests something like:

select dateadd(day, col, '1899-12-30')


问:
Read multiple .gz file and return it in one tensor
I am trying to read multiple .gz file and return its content in one tensor as follows:

```<code>with ReadHelper('ark: gunzip -c /home/mnabih/kaldi/egs/timit/s5/exp/mono_ali/*.gz|') as reader:
    for key, b in reader:
        #print(type(b))
        c = torch.from_numpy(b)
        labels = torch.cat(c)
</code>```

Unfortunately, it gives me this error:

cat(): argument 'tensors' (position 1) must be tuple of Tensors, not Tensor

答:
As the error message explains, c is a tensor. To use torch.cat() you must pass a group of tensors or a list. To solve your problem you may use:

```<code>temp = list()
for key, b in reader:
    temp.append(torch.from_numpy(b))
labels = torch.cat(temp)
</code>```

For more, you can check the manual here

Body:
I am trying to read multiple .gz file and return its content in one tensor as follows:

with ReadHelper('ark: gunzip -c /home/mnabih/kaldi/egs/timit/s5/exp/mono_ali/*.gz|') as reader:
    for key, b in reader:
        #print(type(b))
        c = torch.from_numpy(b)
        labels = torch.cat(c)

Unfortunately, it gives me this error:

cat(): argument 'tensors' (position 1) must be tuple of Tensors, not Tensor

Body:
As the error message explains, c is a tensor. To use torch.cat() you must pass a group of tensors or a list. To solve your problem you may use:

temp = list()
for key, b in reader:
    temp.append(torch.from_numpy(b))
labels = torch.cat(temp)

For more, you can check the manual here


问:
enable_if on conversion constructor (static cast, is_base_of)
I am working on an implementation of a shared pointer. (using C++17, in case it matters)

The only issue is the conversion constructor. I want to be able to static cast a smart_ptr to a smart_ptr of base type.

```<code>template<typename U>
inline smart_ptr(const smart_ptr<U>& rhs)
{
    ...
}
</code>```

It works, but it will also try to cast a smart_ptr to a smart_ptr of any other type. For example, if I have an overloaded function that can take different kinds of smart_ptr's of unrelated type, I get a compiler error about ambiguous overload. So, I only want the conversion from smart_ptr -> smart_ptr if U is a derived class of T.

This looks like it should work. It compiles, but it does the opposite. It prevents the valid static upcasts from working, but still allows the casting to unrelated types:

```<code>template<typename U>
inline local_shared_ptr(typename enable_if<is_base_of<T,U>::value, const  local_shared_ptr<U>&>::type rhs)
{
    ...
}
</code>```

EDIT:

Got it working, thanks for the help. I choose jarod's solution, since I find template <typename U, enable_if_t<is_base_of<T,U>::value, int> = 0> the most concise. I didn't realize SFINAE could be that concise.

Also, since it was mentioned by Nathan:

Funnily enough, one of the issues I encountered is that I expected the template copy constructor to be called when the right-hand-side is the same type. Apparently, the compiler doesn't consider it an implementation of the copy constructor, and instead the auto-generated copy constructor was being called instead. Same issue for the move constructor and operator=. Not sure if that's a bug with MSVC2019.

答:
U is non deducible with

```<code>template<typename U>
local_shared_ptr(enable_if_t<is_base_of<T,U>::value, const  local_shared_ptr<U>&> rhs)
{
// ...
}
</code>```

And as it is a constructor, you even cannot provide template explicitly.
So that constructor is useless.

You can use instead:

Default parameter (the most similar to your attempt IMO):

```<code>template <typename U>
local_shared_ptr(const local_shared_ptr<U>& rhs, enable_if_t<is_base_of<T,U>::value, int> = 0)
{
// ...
}
</code>```

default template parameter (preferred way):

```<code>template <typename U, enable_if_t<is_base_of<T,U>::value, int> = 0>
local_shared_ptr(const local_shared_ptr<U>& rhs)
{
// ...
}
</code>```

And as you use constructor, you cannot use return value.

Body:
I am working on an implementation of a shared pointer. (using C++17, in case it matters)

The only issue is the conversion constructor. I want to be able to static cast a smart_ptr to a smart_ptr of base type.

template<typename U>
inline smart_ptr(const smart_ptr& rhs)
{
    ...
}

It works, but it will also try to cast a smart_ptr to a smart_ptr of any other type. For example, if I have an overloaded function that can take different kinds of smart_ptr's of unrelated type, I get a compiler error about ambiguous overload. So, I only want the conversion from smart_ptr -> smart_ptr if U is a derived class of T.

This looks like it should work. It compiles, but it does the opposite. It prevents the valid static upcasts from working, but still allows the casting to unrelated types:

template<typename U>
inline local_shared_ptr(typename enable_if<is_base_of<T,U>::value, const  local_shared_ptr&>::type rhs)
{
    ...
}

EDIT:

Got it working, thanks for the help. I choose jarod's solution, since I find template <typename U, enable_if_t<is_base_of<T,U>::value, int> = 0> the most concise. I didn't realize SFINAE could be that concise.

Also, since it was mentioned by Nathan:

Funnily enough, one of the issues I encountered is that I expected the template copy constructor to be called when the right-hand-side is the same type. Apparently, the compiler doesn't consider it an implementation of the copy constructor, and instead the auto-generated copy constructor was being called instead. Same issue for the move constructor and operator=. Not sure if that's a bug with MSVC2019.

Body:
U is non deducible with

template<typename U>
local_shared_ptr(enable_if_t<is_base_of<T,U>::value, const  local_shared_ptr<U>&> rhs)
{
// ...
}

And as it is a constructor, you even cannot provide template explicitly.
So that constructor is useless.

You can use instead:

Default parameter (the most similar to your attempt IMO):

template <typename U>
local_shared_ptr(const local_shared_ptr<U>& rhs, enable_if_t<is_base_of<T,U>::value, int> = 0)
{
// ...
}

default template parameter (preferred way):

template <typename U, enable_if_t<is_base_of<T,U>::value, int> = 0>
local_shared_ptr(const local_shared_ptr<U>& rhs)
{
// ...
}

And as you use constructor, you cannot use return value.


问:
What is the point of using OpenAPI at all?
I didn't come from a background using OpenAPI or anything like it, even though I built and used REST APIs in my day job over and over again. In my current role, we always have OpenAPI specs defined, and it seems to be an assumed part of the process. The team treats it as very important.

However, I cannot for the life of me recognize a single benefit to it. I'm trying to understand better.

Of the things I know it can do, none of them appear to be beneficial, imho, but I have to be missing something.

OpenAPI specs can generate documentation, but documentation is for humans to read and should be written by human, in my opinion. Generated docs might include all the bits, but none of the context and nuance of using the API as a whole.

OpenAPI specs can generate client code in many languages for a single API. These are just going to map the REST URL structure to method names, usually. Is that really helpful? It means I might do client.books.get(title="Moby Dick") instead of client.get("/books", {'title': 'Moby Dick'}). All its doing is shifting around the same names, not making anything necessarily easier or more concise. So, again, what's the point? A generated client doesn't seem to actually add anything at all.

Can anyone enlighten me?

答:
OpenAPI specs are not a beneficial thing by themselves. In my experience they are a huge benefit in micro service environments where a lot of services interact with each other.

Like all interfaces, RESTful interfaces can be considered as contracts between service providers and service consumers.

The provider promises to offer a certain set of operations and the consumer can subscribe to these operations and their respective endpoints.

The OpenAPI spec in this case is the contract bill on which the participants can agree on. If they don't agree in the first place, they have the api spec to negotiate over.

This is a non technical aspect, of course.

Among the more technical aspects there are three that I find quite useful

1. Generate code and documentation from one single source

There are a couple of ugly truths when it comes to documentation: No one likes to write it, no one likes to read it and most of the time, it is outdated.

With OpenAPI spec and other similar tools, you have the spec that is used to generate the actual code and at the same time the documentation. The chances are a little bit higher that neither of them get out of date. However, the chances still are not 100%.

2. No need to write boilerplate code

With OpenAPI spec, there is no longer the need to manually implement data classes, and simple client- and server code. For a lot of use cases, you can omit setting up your project -- you don't need to write a spring-boot-server or the java data transfer objects. If you have the api spec, the generator will do that for you.

This is not a big thing when you are dealing with a simple api that only offers a handful of endpoints and data objects. But as soon as you are facing several hundreds of endpoints and data classes (as I have), things get a lot easier with a good written api spec at hand.

3. Tooling

A lot of tools exist in the open api ecosystem (see this list). It is not just the code generator.

There is an awesome in-browser editor for spec files, there are data validators, test data generators etc.

TL;DR

You are right of course. Basically OpenAPI and the whole tool suite behind it will generate client- and server- code and act as a mapper between the rest endpoints and that generated code.

But writing mapping code can be tedious and error prone. Better let some tool do it for you.

Additionally, a machine readable api spec can serve as an api contract bill. It can be versioned on a git repository and distributed over a nexus repo.

If used right, it can make your life a lot easier.


问:
SwiftUI: List does not update automatically after deleting all Core Data Entity entries
I know SwiftUI uses state-driven rendering. So I was assuming, when I delete Core Data Entity entries, that my List with Core Data elements gets refreshed immediately.
I use this code, which gets my Entity cleaned succesfully:

```<code>func deleteAll()
{
    let fetchRequest: NSFetchRequest<NSFetchRequestResult> = ToDoItem.fetchRequest()
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)

    let persistentContainer = (UIApplication.shared.delegate as! AppDelegate).persistentContainer

    do {
        try persistentContainer.viewContext.execute(deleteRequest)
    } catch let error as NSError {
        print(error)
    }
}
</code>```

To get the List in my View visually empty I have to leave the View afterwards (for example with " self.presentationMode.wrappedValue.dismiss()") and open it again. As if the values are still stored somewhere in the memory or something.
This is of course not user-friendly and I am sure I just oversee something that refreshes the List immediately.
Maybe someone can help.

答:
No need to force a refresh, this is IMO not a clean solution.

As you correctly mentioned in your question, there are still elements in memory. The solution is to update your in-memory objects after the execution with mergeChanges.

This blog post explains the solution in detail under "Updating in-memory objects".

There, the author provides an extension to NSBatchDeleteRequest as follows

```<code>extension NSManagedObjectContext {

    /// Executes the given `NSBatchDeleteRequest` and directly merges the changes to bring the given managed object context up to date.
    ///
    /// - Parameter batchDeleteRequest: The `NSBatchDeleteRequest` to execute.
    /// - Throws: An error if anything went wrong executing the batch deletion.
    public func executeAndMergeChanges(using batchDeleteRequest: NSBatchDeleteRequest) throws {
        batchDeleteRequest.resultType = .resultTypeObjectIDs
        let result = try execute(batchDeleteRequest) as? NSBatchDeleteResult
        let changes: [AnyHashable: Any] = [NSDeletedObjectsKey: result?.result as? [NSManagedObjectID] ?? []]
        NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [self])
    }
}
</code>```

Here is an update to your code on how to call it:

```<code>func deleteAll() {
    let fetchRequest: NSFetchRequest<NSFetchRequestResult> = ToDoItem.fetchRequest()
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)

    let persistentContainer = (UIApplication.shared.delegate as! AppDelegate).persistentContainer

    do {
        try persistentContainer.viewContext.executeAndMergeChanges(deleteRequest)
    } catch let error as NSError {
        print(error)
    }
}
</code>```

Some more info also here under this link: Core Data NSBatchDeleteRequest appears to leave objects in context.

Body:
I know SwiftUI uses state-driven rendering. So I was assuming, when I delete Core Data Entity entries, that my List with Core Data elements gets refreshed immediately.
I use this code, which gets my Entity cleaned succesfully:

func deleteAll()
{
    let fetchRequest: NSFetchRequest<NSFetchRequestResult> = ToDoItem.fetchRequest()
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)

    let persistentContainer = (UIApplication.shared.delegate as! AppDelegate).persistentContainer

    do {
        try persistentContainer.viewContext.execute(deleteRequest)
    } catch let error as NSError {
        print(error)
    }
}

To get the List in my View visually empty I have to leave the View afterwards (for example with " self.presentationMode.wrappedValue.dismiss()") and open it again. As if the values are still stored somewhere in the memory or something.
This is of course not user-friendly and I am sure I just oversee something that refreshes the List immediately.
Maybe someone can help.

Body:
No need to force a refresh, this is IMO not a clean solution.

As you correctly mentioned in your question, there are still elements in memory. The solution is to update your in-memory objects after the execution with mergeChanges.

This blog post explains the solution in detail under "Updating in-memory objects".

There, the author provides an extension to NSBatchDeleteRequest as follows

extension NSManagedObjectContext {

    /// Executes the given `NSBatchDeleteRequest` and directly merges the changes to bring the given managed object context up to date.
    ///
    /// - Parameter batchDeleteRequest: The `NSBatchDeleteRequest` to execute.
    /// - Throws: An error if anything went wrong executing the batch deletion.
    public func executeAndMergeChanges(using batchDeleteRequest: NSBatchDeleteRequest) throws {
        batchDeleteRequest.resultType = .resultTypeObjectIDs
        let result = try execute(batchDeleteRequest) as? NSBatchDeleteResult
        let changes: [AnyHashable: Any] = [NSDeletedObjectsKey: result?.result as? [NSManagedObjectID] ?? []]
        NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [self])
    }
}

Here is an update to your code on how to call it:

func deleteAll() {
    let fetchRequest: NSFetchRequest<NSFetchRequestResult> = ToDoItem.fetchRequest()
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)

    let persistentContainer = (UIApplication.shared.delegate as! AppDelegate).persistentContainer

    do {
        try persistentContainer.viewContext.executeAndMergeChanges(deleteRequest)
    } catch let error as NSError {
        print(error)
    }
}

Some more info also here under this link: Core Data NSBatchDeleteRequest appears to leave objects in context.


问:
E/RecyclerView: No adapter attached; skipping layout when using searchview

Adapter Class

Currently trying to implement a search for my recycler view. When i try running the searching i get an error of "E/RecyclerView: No adapter attached; skipping layout". I have tried using notifyDatasetChanged() but still not working. When I print the filtered list I can see it contains the correct amount of items it should return however it is not being updated. Thanks

```<code>public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements Filterable {

        Context context;
         ArrayList<New> fullList;
        ArrayList<New> list;

        public RecyclerViewAdapter(Context context, ArrayList<New> fullList) {
            this.fullList = fullList;
            this.list  = new ArrayList<>(fullList);
            this.context = context;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rows, parent, false);
            ViewHolder viewHolder = new ViewHolder(view);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {

            New studentDetails = fullList.get(position);
            holder.setTitle(studentDetails.getType().toString());

        }
        @Override
        public int getItemCount() {

            return fullList.size();
        }

        @Override
        public Filter getFilter() {
            return exampleFilter;
        }

        private Filter exampleFilter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                List<New> filteredList = new ArrayList<>();
                if(constraint == null || constraint.length()==0)
                {
                    filteredList.addAll(list);
                }
                else
                {
                    String filterPattern = constraint.toString().toLowerCase().trim();

                    for(New item: fullList)
                    {
                        if(item.getType().toString().toLowerCase().contains(filterPattern))
                        {
                            filteredList.add(item);
                        }
                    }
                }
                FilterResults results= new FilterResults();
                results.values = filteredList;
                System.out.println("filtered " + filteredList.toString());
                return results;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {

                list.clear();
                list.addAll((List)results.values);
                notifyDataSetChanged();
            }
        };
</code>```

Fragment

```<code>@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        // Do something that differs the Activity's menu here
        MenuItem searchItem = menu.findItem(R.id.search);
        SearchView searchView = (SearchView)searchItem.getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }
            @Override
            public boolean onQueryTextChange(String newText) {
                System.out.println("before" + list);
                adapter.getFilter().filter(newText);
                System.out.println("after" + list);
                return false;
            }

        });

    }
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView= inflater.inflate(R.layout.fragment_shown,container,false);
        myRecycler=(RecyclerView)mView.findViewById(R.id.recycler);
        myRecycler.setHasFixedSize(true);
        myRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
        mDatabase = FirebaseDatabase.getInstance().getReference().child("Student");

        mDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                    New studentDetails = dataSnapshot.getValue(New.class);
                    Map<String, String> map = (Map) dataSnapshot.getValue();
                    String message = map.get("name");
                    if(message.equals("studentname"))
                    {
                        list.add(studentDetails);
                    }

                }

                adapter = new RecyclerViewAdapter(getActivity(), list);
                myRecycler.setAdapter(adapter);
                adapter.notifyDataSetChanged();

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        return mView;
    }
</code>```

答:
The issue is that you aren't creating an adapter until you get an update from the database. You should set the adapter outside of the listener, and updated it as needed:

```<code> public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    mView= inflater.inflate(R.layout.fragment_shown,container,false);
    myRecycler=(RecyclerView)mView.findViewById(R.id.recycler);
    myRecycler.setHasFixedSize(true);
    myRecycler.setLayoutManager(new LinearLayoutManager(getContext()));

 //set your adapter when you create the view
 adapter = new RecyclerViewAdapter(getActivity(), list);
                myRecycler.setAdapter(adapter);
    mDatabase = FirebaseDatabase.getInstance().getReference().child("Student");

    mDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                New studentDetails = dataSnapshot.getValue(New.class);
                Map<String, String> map = (Map) dataSnapshot.getValue();
                String message = map.get("name");
                if(message.equals("studentname"))
                {
                    list.add(studentDetails);
                }

            }

            adapter.notifyDataSetChanged();

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    return mView;
}
</code>```

You will also need to update your data set. You can do something like this in your adapter class:

```<code>public void updateData(List<New> myData){
     list = myData;
     notifyDataSetChanged()
}
</code>```

Then instead of calling adapter.notifyDataSetChanged()you call adapter.updateData(list).

Body:
Adapter Class

Currently trying to implement a search for my recycler view. When i try running the searching i get an error of "E/RecyclerView: No adapter attached; skipping layout". I have tried using notifyDatasetChanged() but still not working. When I print the filtered list I can see it contains the correct amount of items it should return however it is not being updated. Thanks

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements Filterable {

        Context context;
         ArrayList<New> fullList;
        ArrayList<New> list;

        public RecyclerViewAdapter(Context context, ArrayList<New> fullList) {
            this.fullList = fullList;
            this.list  = new ArrayList<>(fullList);
            this.context = context;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rows, parent, false);
            ViewHolder viewHolder = new ViewHolder(view);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {

            New studentDetails = fullList.get(position);
            holder.setTitle(studentDetails.getType().toString());

        }
        @Override
        public int getItemCount() {

            return fullList.size();
        }

        @Override
        public Filter getFilter() {
            return exampleFilter;
        }

        private Filter exampleFilter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                List<New> filteredList = new ArrayList<>();
                if(constraint == null || constraint.length()==0)
                {
                    filteredList.addAll(list);
                }
                else
                {
                    String filterPattern = constraint.toString().toLowerCase().trim();

                    for(New item: fullList)
                    {
                        if(item.getType().toString().toLowerCase().contains(filterPattern))
                        {
                            filteredList.add(item);
                        }
                    }
                }
                FilterResults results= new FilterResults();
                results.values = filteredList;
                System.out.println("filtered " + filteredList.toString());
                return results;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {

                list.clear();
                list.addAll((List)results.values);
                notifyDataSetChanged();
            }
        };

Fragment

@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        // Do something that differs the Activity's menu here
        MenuItem searchItem = menu.findItem(R.id.search);
        SearchView searchView = (SearchView)searchItem.getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }
            @Override
            public boolean onQueryTextChange(String newText) {
                System.out.println("before" + list);
                adapter.getFilter().filter(newText);
                System.out.println("after" + list);
                return false;
            }

        });

    }
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView= inflater.inflate(R.layout.fragment_shown,container,false);
        myRecycler=(RecyclerView)mView.findViewById(R.id.recycler);
        myRecycler.setHasFixedSize(true);
        myRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
        mDatabase = FirebaseDatabase.getInstance().getReference().child("Student");

        mDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                    New studentDetails = dataSnapshot.getValue(New.class);
                    Map<String, String> map = (Map) dataSnapshot.getValue();
                    String message = map.get("name");
                    if(message.equals("studentname"))
                    {
                        list.add(studentDetails);
                    }

                }

                adapter = new RecyclerViewAdapter(getActivity(), list);
                myRecycler.setAdapter(adapter);
                adapter.notifyDataSetChanged();

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        return mView;
    }

Body:
The issue is that you aren't creating an adapter until you get an update from the database. You should set the adapter outside of the listener, and updated it as needed:

 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    mView= inflater.inflate(R.layout.fragment_shown,container,false);
    myRecycler=(RecyclerView)mView.findViewById(R.id.recycler);
    myRecycler.setHasFixedSize(true);
    myRecycler.setLayoutManager(new LinearLayoutManager(getContext()));

 //set your adapter when you create the view
 adapter = new RecyclerViewAdapter(getActivity(), list);
                myRecycler.setAdapter(adapter);
    mDatabase = FirebaseDatabase.getInstance().getReference().child("Student");

    mDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                New studentDetails = dataSnapshot.getValue(New.class);
                Map<String, String> map = (Map) dataSnapshot.getValue();
                String message = map.get("name");
                if(message.equals("studentname"))
                {
                    list.add(studentDetails);
                }

            }

            adapter.notifyDataSetChanged();

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    return mView;
}

You will also need to update your data set. You can do something like this in your adapter class:

public void updateData(List<New> myData){
     list = myData;
     notifyDataSetChanged()
}

Then instead of calling adapter.notifyDataSetChanged()you call adapter.updateData(list).


问:
Prompt asking for password then redirecting
I'm very new to PHP and JavaScript and I'm stuck. I spent a good 7 hours so far trying to figure this one out but I just do not know what or how to do it. So in my application, when you try to add a new row to my table, I have a html form to get the data. When you enter the data into the form, and press submit, it prompts for a password, and if the correct password is put in, it submits the form. It work just as I wanted it, here is what I have:

```<code><button onclick="password()" type="button">Create New Hero</button>
    <div>
        <a id="discl">*-Required Fields</a>
    </div>
    <script>
        function password(){
            var password = prompt("Please Enter the Admin Password");
            if(password != "shaun"){
                alert("Wrong Password");
            }
            else{
                if(validation()){
                document.getElementById("form_id").submit();
                }
                else{
                    alert("One or more required fields were left empty, or tried to use <script>");
                }
            }
        }
        function validation(){
            var f = document.getElementById("f_name").value;
            var l = document.getElementById("l_name").value;
            var d = document.getElementById("dob").value;
            var a = document.getElementById("alias").value;
            if(f == "" || l == "" || d == "" || f.includes("<script>") || l.includes("<script>") || a.includes("<script>")){
                return false;
            }
            else{
                return true;
            }
        }
    </script>
</code>```

Now I also have an edit and delete on my table. My problem is that with edit and delete, they are in  tags with an href, and they are not buttons. This is how they originally looked when it worked without asking for a password:

```<code>               echo "<a href='./edit.php?id={$row['id']}'>edit</a>";
</code>```

So based on which row of the table it was, where you clicked edit or delete, based on the row's id from the database, it would edit or delete that table. Now my problem is I don't know how to properly set up the function so it asks for the password and redirect to the right url. This is what I have right now:

```<code>           foreach($results as $row){
            echo "<tr>";
            echo "<td>{$row['first_name']}</td>";
            echo "<td>{$row['last_name']}</td>";
            echo "<td>{$row['date_of_birth']}</td>";
            echo "<td>{$row['alias']}</td>";
            echo "<td>{$row['active']}</td>";
            echo "<td>{$row['hero']}</td>";
            echo "<td>";
            echo "<a href='./edit.php?id={$row['id']}'>edit</a>";
            echo " | ";
            echo "<a  href='javascript: password()'>delete</a>";
            echo "</td>";
            echo "</tr>";
        }
        ?>
        <script type="text/javascript">
        function password(){
            var password = prompt("Please Enter the Admin Password");
            if(password != "shaun"){
                alert("Wrong Password");
            }
            else{
                window.location.replace("./delete.php?id=<?php echo $row['id']; ?>");
            }
        }
    </script>
</code>```

The problem with this is that no matter which delete I click on on my table, it always deletes the last one, because the ID it's getting out after the url is the last available ID from my database. I'm not sure if I'm just missing something small, or I'm completely on the wrong path but any help would be appreciated because I'm very lost. Thank you

答:
Will not comment on any security issues here, just the logic. You need to pass $row['id'] during PHP loop to your JS password() function that you want to use afterwards:

```<code><?php
    foreach ($results as $row) {
        echo "<tr>";
        echo "<td>{$row['first_name']}</td>";
        echo "<td>{$row['last_name']}</td>";
        echo "<td>{$row['date_of_birth']}</td>";
        echo "<td>{$row['alias']}</td>";
        echo "<td>{$row['active']}</td>";
        echo "<td>{$row['hero']}</td>";
        echo "<td>";
        echo "<a href='./edit.php?id={$row['id']}'>edit</a>";
        echo " | ";
        echo "<a  href='javascript: password(".$row['id'].")'>delete</a>";
        echo "</td>";
        echo "</tr>";
    }
?>
<script type="text/javascript">
    function password(delId) {
        var password = prompt("Please Enter the Admin Password");
        if (password != "shaun") {
            alert("Wrong Password");
        } else {
            window.location.replace("./delete.php?id="+delId);
        }
    }
</script>
</code>```

Body:
I'm very new to PHP and JavaScript and I'm stuck. I spent a good 7 hours so far trying to figure this one out but I just do not know what or how to do it. So in my application, when you try to add a new row to my table, I have a html form to get the data. When you enter the data into the form, and press submit, it prompts for a password, and if the correct password is put in, it submits the form. It work just as I wanted it, here is what I have:

<button onclick="password()" type="button">Create New Hero</button>

        *-Required Fields

Now I also have an edit and delete on my table. My problem is that with edit and delete, they are in  tags with an href, and they are not buttons. This is how they originally looked when it worked without asking for a password:

               echo "edit";

So based on which row of the table it was, where you clicked edit or delete, based on the row's id from the database, it would edit or delete that table. Now my problem is I don't know how to properly set up the function so it asks for the password and redirect to the right url. This is what I have right now:

           foreach($results as $row){
            echo "
";
            echo "{$row['first_name']}	";
            echo "{$row['last_name']}	";
            echo "{$row['date_of_birth']}	";
            echo "{$row['alias']}	";
            echo "{$row['active']}	";
            echo "{$row['hero']}	";
            echo "";
            echo "edit";
            echo " | ";
            echo "delete";
            echo "	";
            echo "
";
        }
        ?>

The problem with this is that no matter which delete I click on on my table, it always deletes the last one, because the ID it's getting out after the url is the last available ID from my database. I'm not sure if I'm just missing something small, or I'm completely on the wrong path but any help would be appreciated because I'm very lost. Thank you

Body:
Will not comment on any security issues here, just the logic. You need to pass $row['id'] during PHP loop to your JS password() function that you want to use afterwards:

<?php
    foreach ($results as $row) {
        echo "<tr>";
        echo "<td>{$row['first_name']}</td>";
        echo "<td>{$row['last_name']}</td>";
        echo "<td>{$row['date_of_birth']}</td>";
        echo "<td>{$row['alias']}</td>";
        echo "<td>{$row['active']}</td>";
        echo "<td>{$row['hero']}</td>";
        echo "<td>";
        echo "<a href='./edit.php?id={$row['id']}'>edit</a>";
        echo " | ";
        echo "<a  href='javascript: password(".$row['id'].")'>delete</a>";
        echo "</td>";
        echo "</tr>";
    }
?>
<script type="text/javascript">
    function password(delId) {
        var password = prompt("Please Enter the Admin Password");
        if (password != "shaun") {
            alert("Wrong Password");
        } else {
            window.location.replace("./delete.php?id="+delId);
        }
    }
</script>


问:
How to do cache warmup in TYPO3
In another question, there is the recommendation to setup a cache_clearAtMidnight via TypoScript and do a subsequent cache warmup.

I would like to know how to do this cache warmup because I did not find a scheduler task to do it.

(Clearing the entire cache once a day seems excessive, but the cache warmup seems like a good idea to me in any case.)

答:
As I don't know whether there is an internal mechanism in TYPO3 for cache warming, I built my own little cache warmer based around a simple PHP script (can actually be anything – Python, PHP, Bash,...). The script reads the sitemap.xml and requests each page via cURL.

I use a custom user agent to exclude these requests from statistics.

```<code>curl_setopt($ch, CURLOPT_USERAGENT, 'cache warming - TYPO3');
</code>```

Title: How to do cache warmup in TYPO3

Body:
As I don't know whether there is an internal mechanism in TYPO3 for cache warming, I built my own little cache warmer based around a simple PHP script (can actually be anything – Python, PHP, Bash,...). The script reads the sitemap.xml and requests each page via cURL.

I use a custom user agent to exclude these requests from statistics.

curl_setopt($ch, CURLOPT_USERAGENT, 'cache warming - TYPO3');


问:
Target is not a JDK Root. Java executable was not found jdk 13.0.2 eclipse 2019
I have reinstalled java, jdk and eclipse many times but i am still not able to add my jdk13 into my eclipse.
 I downloaded the eclipse-java-2019-12-R-macosx-cocoa-x86_64.dmg file
This is my java (version 8)

My JRE

My JDK

But yet this still occurs

Please help :'(((( I have no idea what went wrong when I followed guides and steps.

答:
On macOS the directory for Installed JREs is

/Library/Java/JavaVirtualMachines/jdk-13.0.2.jdk/Contents/Home
```

(I am using the Oracle Java 13.0.2).

Body:
On macOS the directory for Installed JREs is

/Library/Java/JavaVirtualMachines/jdk-13.0.2.jdk/Contents/Home

(I am using the Oracle Java 13.0.2).


问:
Unable to retrieve Sharepoint List Item With Workflow attached (In Progress, completed etc.) on it
I am using share point 2010, and using LINQ which is generated by SPMETAL.EXE.
I am facing a weird issue which is mentioned below by sequence:

1: Inserted a new item (XX) in list (Listname)
2: On insertion a Workflow get starts and the item (XX) status becomes "In Progress" in ALL Items window.
3: If I access this row with LINQ, it threw an exception "Specified cast not valid"
[NullReferenceException: Object reference not set to an instance of an object.]
   Microsoft.Office.Server.WebControls.MetaDataNavTree.OnUnload(EventArgs e) +40
   System.Web.UI.Control.UnloadRecursive(Boolean dispose) +153
   System.Web.UI.Control.UnloadRecursive(Boolean dispose) +306
   System.Web.UI.Control.UnloadRecursive(Boolean dispose) +306
   System.Web.UI.Control.UnloadRecursive(Boolean dispose) +306
   System.Web.UI.Control.UnloadRecursive(Boolean dispose) +306
   System.Web.UI.Control.UnloadRecursive(Boolean dispose) +306
   System.Web.UI.Control.UnloadRecursive(Boolean dispose) +306
   System.Web.UI.Control.UnloadRecursive(Boolean dispose) +306
   System.Web.UI.Control.UnloadRecursive(Boolean dispose) +306
   System.Web.UI.Control.UnloadRecursive(Boolean dispose) +306
   System.Web.UI.Page.UnloadRecursive(Boolean dispose) +23
   System.Web.UI.Page.ProcessRequestCleanup() +54
   System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +11045194
   System.Web.UI.Page.ProcessRequest() +91
   System.Web.UI.Page.ProcessRequest(HttpContext context) +240
   ASP.FORM_ASPX__331913002.ProcessRequest(HttpContext context) in c:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\ccd70a06\451bebbc\App_Web_form.aspx_-331913002.nurxfpml.0.cs:0
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +599
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +171

4: While If I access items on which their is no entry for work flow (i.e. when I didnt start my work flow from work flow settings) It works fine.

THE ABOVE MENTIONED ISSUE IS NOT WITH OBJECT MODEL APPROACH. THAT WORKS FINE. I THINK ISSUE IS WITH LINQ

PLEASE HELP TO GET RID OF THIS ISSUE.  AS I CANT SWITCH FROM LINQ.

答:
I had the same problem, and this is what I did:

Generate the code using SPMetal (with or without the Workflow attached: does not matter)

Edit the generated code to change the type of the field that represents the workflow status column from the list, to object. In my case, the changed code looks like:

[System.Runtime.Serialization.DataMemberAttribute()]
        private object _designCompany_SetCompanyAndFullName;

```<code>    [Microsoft.SharePoint.Linq.ColumnAttribute(Name = "SetCompa", Storage = "_designCompany_SetCompanyAndFullName", ReadOnly = true, FieldType = "WorkflowStatus")]
    public System.Nullable<int> DesignCompany_SetCompanyAndFullName
    {
        get
        {
            return null; //removed all code - but this may be unnecessary
        }
        set
        {
            //removed all code - but this may be unnecessary
        }
    }
</code>```

Compile and deploy.

The error 'specified cast..' should not occur anymore.

The reason for this is that (I believe) SPMetal has a bug and generates System.Nullable type fields in the generated code to represent workflow status columns. I checked out the code for Microsoft.Sharepoint.Linq.dll in Reflector, to find that it uses a dynamically generated method to set the field value directly and just before setting the field it tries to cast the value from object to whatever the field type is.

MSDN specifies that the type mapping for the 'WorkflowStatus' type in Sharepoint is 'object' in .NET : http://msdn.microsoft.com/en-us/library/ee536245.aspx

Now, atleast  I don't get this error anymore.

Krishna

Body:
I had the same problem, and this is what I did:

Generate the code using SPMetal (with or without the Workflow attached: does not matter)

Edit the generated code to change the type of the field that represents the workflow status column from the list, to object. In my case, the changed code looks like:

[System.Runtime.Serialization.DataMemberAttribute()]
        private object _designCompany_SetCompanyAndFullName;

    [Microsoft.SharePoint.Linq.ColumnAttribute(Name = "SetCompa", Storage = "_designCompany_SetCompanyAndFullName", ReadOnly = true, FieldType = "WorkflowStatus")]
    public System.Nullable<int> DesignCompany_SetCompanyAndFullName
    {
        get
        {
            return null; //removed all code - but this may be unnecessary
        }
        set
        {
            //removed all code - but this may be unnecessary
        }
    }

Compile and deploy.

The error 'specified cast..' should not occur anymore.

The reason for this is that (I believe) SPMetal has a bug and generates System.Nullable type fields in the generated code to represent workflow status columns. I checked out the code for Microsoft.Sharepoint.Linq.dll in Reflector, to find that it uses a dynamically generated method to set the field value directly and just before setting the field it tries to cast the value from object to whatever the field type is.

MSDN specifies that the type mapping for the 'WorkflowStatus' type in Sharepoint is 'object' in .NET : http://msdn.microsoft.com/en-us/library/ee536245.aspx

Now, atleast  I don't get this error anymore.

Krishna


问:
Switch android x86 screen resolution
I would like to use Android-x86 2.2 as an emulator on my Windows 7. I have downloaded VirtualBox and the ISO, and I've made a virtual machine with it, but I can't set the resolution to 320x480 or something similar.

The following tutorial "Using the Android-x86 Port as your Emulator" suggests to insert:

<ExtraDataItem name="CustomVideoMode2" value="320x480x16" />
```

to my .vbox file and I did it. Then I added UVESA_MODE=320x480 and vga=ask to the boot config. When it boots, I have to press Enter to see the available options, but there is no 320x480 among them.  How can I get it to work?

答:
Set resolution in android x86

Libvirt/qemu

Temporarily

Add nomodeset and vga=ask to android x86 grub entry's kernel loading options;

Find your best resolution and note the code you used.

Permanently

Convert that code to decimal from hex;

Add vga=decimal_code to your preferred entry in /mnt/grub/menu.lst (mounted if android is started in debug mode).

Title: Switch android x86 screen resolution

Body:
I would like to use Android-x86 2.2 as an emulator on my Windows 7. I have downloaded VirtualBox and the ISO, and I've made a virtual machine with it, but I can't set the resolution to 320x480 or something similar.

The following tutorial "Using the Android-x86 Port as your Emulator" suggests to insert:

<ExtraDataItem name="CustomVideoMode2" value="320x480x16" />

to my .vbox file and I did it. Then I added UVESA_MODE=320x480 and vga=ask to the boot config. When it boots, I have to press Enter to see the available options, but there is no 320x480 among them.  How can I get it to work?


问:
How to add external js file in Nuxt for a specific page?
How do I load an external file in Nuxt for a specific page?

I have followed this guide: https://nuxtjs.org/faq/#local-settings and it works if I load the page with server side rendering (i.e. visting the URL directly).

However, if I go to the page using a link (from vue router) the script will not exist.

答:
I realized, after creating a sandbox, that it does indeed load the script when you navigate to it. The problem is if you try to load that external libraries methods/functions/variables before the script is actually loaded (e.g. on a mounted() call). I solved it like this:

As an example, if you'd wish to load jQuery for a specific page, this will fail:

```<code>mounted () {
    jQuery('.element').hide();
}
</code>```

However, you can set up an interval to check whenever jQuery is loaded in, like so:

```<code>mounted () {
    const awaitScriptInterval = setInterval(() => { // set an interval to check when script is loaded
        if (typeof jQuery === 'undefined') { // script is not yet loaded in
            return;
        }

        clearTimeout(awaitScriptInterval); // clear the interval, so we don't continuously check

        jQuery('.element').hide(); // use your external library
    }, 500); // the interval in milliseconds to check
}
</code>```

See this article on how to load an external script/style: https://nuxtjs.org/faq/#local-settings

Body:
I realized, after creating a sandbox, that it does indeed load the script when you navigate to it. The problem is if you try to load that external libraries methods/functions/variables before the script is actually loaded (e.g. on a mounted() call). I solved it like this:

As an example, if you'd wish to load jQuery for a specific page, this will fail:

mounted () {
    jQuery('.element').hide();
}

However, you can set up an interval to check whenever jQuery is loaded in, like so:

mounted () {
    const awaitScriptInterval = setInterval(() => { // set an interval to check when script is loaded
        if (typeof jQuery === 'undefined') { // script is not yet loaded in
            return;
        }

        clearTimeout(awaitScriptInterval); // clear the interval, so we don't continuously check

        jQuery('.element').hide(); // use your external library
    }, 500); // the interval in milliseconds to check
}

See this article on how to load an external script/style: https://nuxtjs.org/faq/#local-settings


问:
Get value from Instance in Flutter
I am making a search request on the List with the Provider pattern.

```<code>List<Device> _devices = [
    Device(one: 'Apple', two: 'iphone'),
    Device(one: 'Samsung', two: 'Galaxy')
];
</code>```

And Query is like this

```<code>List<Device> queryQuery(String value) {
return _devices
    .where((device) => device.one.toLowerCase().contains(value.toLowerCase()))
    .toList();
</code>```

the result I expect to get is iphone when I passed the value Apple.

But the result on the screen that I got is [instance of ‘Device’]
when I code like this

```<code>child: Text('${deviceData.getDevice('Apple')}'
</code>```

I do know I should be using some kind of key using two... but I have no idea :-(

答:
By the look of [Instance of 'Device'], it seems the function is returning a list so it is a good idea to check if the list is empty or not. if it is not empty, one of the elements is still needed to be selected. I guess it should be Text('${chordData.chordExpand('Apple')[0].two}') in case the list is not empty.

To summarize, use something like this to handle the case when list is empty

```<code>// Inside your build method before returning the widget
var l = chordData.chordExpand('Apple'); // Returns a list of devices
String textToWrite; // Here we will store the text that needs to be written
if(l.isEmpty) textToWrite = 'No results'; // If the filter resulted in an empty list
else textToWrite = l[0].two; // l[0] is an instance of a device which has a property called two. You can select any instance from the list provided it exists

return <Your Widget>(
.....
Text(textToWrite),
.....
);
</code>```

Title: Get value from Instance in Flutter

Body:
I am making a search request on the List with the Provider pattern.

List<Device> _devices = [
    Device(one: 'Apple', two: 'iphone'),
    Device(one: 'Samsung', two: 'Galaxy')
];

And Query is like this

List<Device> queryQuery(String value) {
return _devices
    .where((device) => device.one.toLowerCase().contains(value.toLowerCase()))
    .toList();

the result I expect to get is iphone when I passed the value Apple.

But the result on the screen that I got is [instance of ‘Device’]
when I code like this

child: Text('${deviceData.getDevice('Apple')}'

I do know I should be using some kind of key using two... but I have no idea :-(

Body:
By the look of [Instance of 'Device'], it seems the function is returning a list so it is a good idea to check if the list is empty or not. if it is not empty, one of the elements is still needed to be selected. I guess it should be Text('${chordData.chordExpand('Apple')[0].two}') in case the list is not empty.

To summarize, use something like this to handle the case when list is empty

// Inside your build method before returning the widget
var l = chordData.chordExpand('Apple'); // Returns a list of devices
String textToWrite; // Here we will store the text that needs to be written
if(l.isEmpty) textToWrite = 'No results'; // If the filter resulted in an empty list
else textToWrite = l[0].two; // l[0] is an instance of a device which has a property called two. You can select any instance from the list provided it exists

return <Your Widget>(
.....
Text(textToWrite),
.....
);


问:
WPF - How to combine DataTrigger and Trigger?

NOTE I have asked the related question: How to combine DataTrigger and EventTrigger?

I have a list box containing several items.  The item's class implements INotifyPropertyChanged and has a property IsAvailable.  I use that property to indicate unavailable options in the list using a different colour.

However, if a selected item is not available, then the foreground colour should be red.

```<code><ListBox>
  <ListBox.Resources>
    <DataTemplate DataType="{x:Type local:InstitutionViewModel}">
      <TextBlock Name="Name" Text="{Binding Name}"/>
      <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding IsAvailable}" Value="False">
          <Setter TargetName="Name" Property="Foreground" Value="#888"/>
        </DataTrigger>
      </DataTemplate.Triggers>
    </DataTemplate>
  </ListBox.Resources>
</ListBox>
</code>```

I use the above data trigger to grey out unavailable items.

The problem I'm facing is that the fact that the item is selected has nothing to do with the underlying data to which the template is bound.  What I really want is some kind of multi-trigger that supports both a regular Trigger on a dependency property (ListBoxItem.IsSelected) along with a DataTrigger on the bound data item.

Can this be done without introducing the concept of selection into my view model?

For anyone wondering why I do not disable unavailable items, understand that it is a requirement of the application that unavailable options may be selected.  There are actually a few list boxes, and selection in one effects what's available in the others.  I cannot disable the items as the user would not be able to change their minds or explore different combinations if items were disabled based upon earlier selections.

答:
For anyone else who's up against this problem, I found a solution that works for me.  Of course, I'm still interested to see other interesting answers.

Here's what I did:

```<code><MultiDataTrigger>
  <MultiDataTrigger.Conditions>
    <Condition Binding="{Binding
      RelativeSource={
        RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}},
        Path=IsSelected}" Value="True"/>
    <Condition Binding="{Binding IsAvailable}" Value="False"/>
  </MultiDataTrigger.Conditions>
  <Setter TargetName="Name" Property="Foreground" Value="#F00"/>
</MultiDataTrigger>
</code>```

There's nothing special about this being a multi trigger though.  If you just wanted to style the selected item differently in your data template, you could use:

```<code><DataTrigger Binding="{Binding
  RelativeSource={
    RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}},
    Path=IsSelected}" Value="True">
  <Setter TargetName="Name" Property="Foreground" Value="#888"/>
</DataTrigger>
</code>```

OwnerDisplayName: Drew Noakes

Body:
NOTE I have asked the related question: How to combine DataTrigger and EventTrigger?

I have a list box containing several items.  The item's class implements INotifyPropertyChanged and has a property IsAvailable.  I use that property to indicate unavailable options in the list using a different colour.

However, if a selected item is not available, then the foreground colour should be red.

<ListBox>
  <ListBox.Resources>
    <DataTemplate DataType="{x:Type local:InstitutionViewModel}">
      <TextBlock Name="Name" Text="{Binding Name}"/>
      <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding IsAvailable}" Value="False">
          <Setter TargetName="Name" Property="Foreground" Value="#888"/>
        </DataTrigger>
      </DataTemplate.Triggers>
    </DataTemplate>
  </ListBox.Resources>
</ListBox>

I use the above data trigger to grey out unavailable items.

The problem I'm facing is that the fact that the item is selected has nothing to do with the underlying data to which the template is bound.  What I really want is some kind of multi-trigger that supports both a regular Trigger on a dependency property (ListBoxItem.IsSelected) along with a DataTrigger on the bound data item.

Can this be done without introducing the concept of selection into my view model?

For anyone wondering why I do not disable unavailable items, understand that it is a requirement of the application that unavailable options may be selected.  There are actually a few list boxes, and selection in one effects what's available in the others.  I cannot disable the items as the user would not be able to change their minds or explore different combinations if items were disabled based upon earlier selections.

LastEditorDisplayName: Drew Noakes

Body:
For anyone else who's up against this problem, I found a solution that works for me.  Of course, I'm still interested to see other interesting answers.

Here's what I did:

<MultiDataTrigger>
  <MultiDataTrigger.Conditions>
    <Condition Binding="{Binding
      RelativeSource={
        RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}},
        Path=IsSelected}" Value="True"/>
    <Condition Binding="{Binding IsAvailable}" Value="False"/>
  </MultiDataTrigger.Conditions>
  <Setter TargetName="Name" Property="Foreground" Value="#F00"/>
</MultiDataTrigger>

There's nothing special about this being a multi trigger though.  If you just wanted to style the selected item differently in your data template, you could use:

<DataTrigger Binding="{Binding
  RelativeSource={
    RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}},
    Path=IsSelected}" Value="True">
  <Setter TargetName="Name" Property="Foreground" Value="#888"/>
</DataTrigger>


问:
git add, commit and push commands in one?
Is there any way to use these three commands in one?

```<code>git add .
git commit -a -m "commit" (do not need commit message either)
git push
</code>```

Sometimes I'm changing only one letter, CSS padding or something. Still, I have to write all three commands to push the changes. There are many projects where I'm only one pusher, so this command would be awesome!

答:
If you're using a Mac:

Start up Terminal and input cd ~/ to go to your home folder

Type touch .bash_profile to create your new file.

Edit .bash_profile with your favourite editor (or you can just type
open -e .bash_profile to open it in TextEdit).

Copy & Paste the below into the file:

```<code>function lazygit() {
    git add .
    git commit -a -m "$1"
    git push
}
</code>```

After this, restart your terminal and simply add, commit and push in one easy command, example:

```<code>lazygit "This is my commit message"
</code>```

Body:
Is there any way to use these three commands in one?

git add .
git commit -a -m "commit" (do not need commit message either)
git push

Sometimes I'm changing only one letter, CSS padding or something. Still, I have to write all three commands to push the changes. There are many projects where I'm only one pusher, so this command would be awesome!

Body:
If you're using a Mac:

Start up Terminal and input cd ~/ to go to your home folder

Type touch .bash_profile to create your new file.

Edit .bash_profile with your favourite editor (or you can just type
open -e .bash_profile to open it in TextEdit).

Copy & Paste the below into the file:

function lazygit() {
    git add .
    git commit -a -m "$1"
    git push
}

After this, restart your terminal and simply add, commit and push in one easy command, example:

lazygit "This is my commit message"


问:
Flink timer async
I have a question regarding Flink and its timer service.

I have a keyBy stream which uses a timer,
When the timer is called I need to send an http request which might take time to respond.
My question is, should I make the http call async?
or flink is making the timer call already as a new thread with async per key?

Thanks in advance

答:
If You are asking if the onTimer method is invoked in a separate thread for each key, then I am pretty sure that it is not. So, You would need to invoke the HTTP call asynchronously in this case.

But to be completely honest, I don't think this is a good idea, in general, to use the onTimer function to perform HTTP calls. I don't know anything about Your use-case, but I think You should consider using different mechanisms like creating side-output and then using the Flink Async operator. Using asynchronous calls inside the onTimer can be tricky, especially if You consider things like retries, timeouts and possible failures.

So according to comment the use-case is to make a call to service each X mins and then post something to Kafka. So, what You could do is to simply have a process function that schedules timers. Each time the timer is fired You then generate some output record with data needed for request if there is any data needed. Then You use the Async operator to actually perform the requests, parse the response and based on the response generate some output record that can be then saved to Kafka.

Title: Flink timer async


问:
How to highlight a word in shinydashboard in R?
I've found some suggestions of how to highlight a word in other contexts but these didn't work for my problem. Here's my code:

```<code>
data<-data.frame(X=c("This is an example", "This is not"))
wordlist<-c("This","example","not")

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(sidebarMenu(selectInput("stemmedw", label="Find A Word : ",wordlist))
  ),
  dashboardBody("Title", tabPanel("News",uiOutput("news")))
)

server <- function(input, output) {
  output$news <- renderUI({
    pos<-unlist(gregexpr(input$stemmedw,data$X,fixed=TRUE))!=-1
    base<-data.frame(X=data[pos,], stringsAsFactors = FALSE)
    m2 <- data.frame(X=data[pos,], stringsAsFactors = FALSE)
    n<-dim(m2)[1]

    a2 <- list()
    for(i in seq_len(n)) {
      a2[[i]] <- valueBox(i,lapply(m2, "[[", i),  width = 100,color="blue")
    }
    tagList(a2)
  })
}

shinyApp(ui = ui, server = server)
</code>```

I would like to highlight only the selected word in the text in valueBox. Maybe a different background color, bold style and/or a underline.
Ths

答:
Here is one way of using bold with HTML, just complete with the htmls tags you want:

```<code>data<-data.frame(X=c("This is an example", "This is not"))
wordlist<-c("This","example","not")

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(sidebarMenu(selectInput("stemmedw", label="Find A Word : ",wordlist))
  ),
  dashboardBody("Title", tabPanel("News",uiOutput("news")))
)

server <- function(input, output) {
  output$news <- renderUI({
    pos<-unlist(gregexpr(input$stemmedw,data$X,fixed=TRUE))!=-1
    base<-data.frame(X=data[pos,], stringsAsFactors = FALSE)
    m2 <- data.frame(X=data[pos,], stringsAsFactors = FALSE)
    n<-dim(m2)[1]

    a2 <- list()

    for(i in seq_len(n)) {
      a2[[i]] <- valueBox(i, HTML(gsub(input$stemmedw, paste0("<b>", input$stemmedw, "</b>"), m2$X[[i]], fixed = TRUE)), width = 100, color = "blue")
    }
    tagList(a2)
  })
}

shinyApp(ui = ui, server = server)
</code>```

Body:
I've found some suggestions of how to highlight a word in other contexts but these didn't work for my problem. Here's my code:

data<-data.frame(X=c("This is an example", "This is not"))
wordlist<-c("This","example","not")

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(sidebarMenu(selectInput("stemmedw", label="Find A Word : ",wordlist))
  ),
  dashboardBody("Title", tabPanel("News",uiOutput("news")))
)

server <- function(input, output) {
  output$news <- renderUI({
    pos<-unlist(gregexpr(input$stemmedw,data$X,fixed=TRUE))!=-1
    base<-data.frame(X=data[pos,], stringsAsFactors = FALSE)
    m2 <- data.frame(X=data[pos,], stringsAsFactors = FALSE)
    n<-dim(m2)[1]

    a2 <- list()
    for(i in seq_len(n)) {
      a2[[i]] <- valueBox(i,lapply(m2, "[[", i),  width = 100,color="blue")
    }
    tagList(a2)
  })
}

shinyApp(ui = ui, server = server)

I would like to highlight only the selected word in the text in valueBox. Maybe a different background color, bold style and/or a underline.
Ths

Body:
Here is one way of using bold with HTML, just complete with the htmls tags you want:

data<-data.frame(X=c("This is an example", "This is not"))
wordlist<-c("This","example","not")

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(sidebarMenu(selectInput("stemmedw", label="Find A Word : ",wordlist))
  ),
  dashboardBody("Title", tabPanel("News",uiOutput("news")))
)

server <- function(input, output) {
  output$news <- renderUI({
    pos<-unlist(gregexpr(input$stemmedw,data$X,fixed=TRUE))!=-1
    base<-data.frame(X=data[pos,], stringsAsFactors = FALSE)
    m2 <- data.frame(X=data[pos,], stringsAsFactors = FALSE)
    n<-dim(m2)[1]

    a2 <- list()

    for(i in seq_len(n)) {
      a2[[i]] <- valueBox(i, HTML(gsub(input$stemmedw, paste0("<b>", input$stemmedw, "</b>"), m2$X[[i]], fixed = TRUE)), width = 100, color = "blue")
    }
    tagList(a2)
  })
}

shinyApp(ui = ui, server = server)