问:
DocuSign API - How to get callback response after user authentication?
I'm trying to implement the Implicit Grant REST API of DocuSign. I'm confused as to what needs to happen right after the user logs in. This is a stand-alone native Windows desktop application, not a web service or page.

I got as far as to open an embedded browser window, navigating to the correct URI for login, and the user is able to successfully login. I further have an HTTP server running in this application as well which is to receive the callback. In fact, the callback does work, I do get an incoming HTTP GET command. However, there is nothing usable in this callback response. No special headers, parameters, body, nothing.

Before I tried the Implicit Grant API, I first tried the JWT Grant method, before realizing it wasn't the right approach. But my point is, at least I had a code parameter in the callback command. But after shifting over to use the Implicit Grant method, this response is empty.

According to the documentation:

After consent has been granted, the Authentication Service verifies that the client application is valid and has access to the requested scope. If so, it redirects the access token to the provided callback URI in a hash fragment.

The response contains the following hash fragment parameters:

.......

It even shows an example response:

```<code>http://localhost/#access_token=eyJ0eXAi.....9LyiFrUqvdw&expires_in=28800&token_type=bearer&state=a39fh23hnf23
</code>```

But, as mentioned, the callback response I receive has nothing of notable value. It's essentially just empty.

What am I missing here? What's the correct approach to complete the authentication process and proceed to actually using the API?

NOTE: I'm using Delphi, so none of the examples provided by DocuSign are compatible.

答:
I discovered what I was doing wrong. It was some confusion and terminology mix-ups. When I stated that my callback URI does in fact work, that's in reference to it triggering my HTTP server listening from within the app - but had no usable data.

However, what I actually need to do is not capture the request in the HTTP server, but rather catch the URI that the embedded browser navigates to after user authentication. Once I sniffed into this browser's URI after successful login, now I can in fact see access_token.

So callback uri and redirect uri are the exact same thing, but can be easily misinterpreted. I kinda have two different definitions of them, where callback is to respond to original caller, and redirect means to navigate from one page to another automatically.

Now I'm curious whether I should even need an HTTP server, or if I could just blindly throw any arbitrary redirect URI (of course registered in the account) and just grab the URI after the embedded browser navigates.

As to why my HTTP server didn't see this data, but the embedded browser did, is beyond me. It should match in both sides.

Just for reference, the embedded browser I'm using is Chromium (DCEF3), and the HTTP server is Indy's TIdHTTPServer component.

UPDATE

As noted in the comments, the HTTP Server does not receive the "bookmark" portion of the URI by design, because the bookmark is a client-side only thing. There's no reason at all why it should ever be sent to the server. Hence the level of security - since that information will ONLY be used by the client, and not the server, it would be risky to send the access_token to the server, over the web. So it keeps it local to the client-side browser. That's why I saw this data on the browser, and not the HTTP server request handler.

Body:
I'm trying to implement the Implicit Grant REST API of DocuSign. I'm confused as to what needs to happen right after the user logs in. This is a stand-alone native Windows desktop application, not a web service or page.

I got as far as to open an embedded browser window, navigating to the correct URI for login, and the user is able to successfully login. I further have an HTTP server running in this application as well which is to receive the callback. In fact, the callback does work, I do get an incoming HTTP GET command. However, there is nothing usable in this callback response. No special headers, parameters, body, nothing.

Before I tried the Implicit Grant API, I first tried the JWT Grant method, before realizing it wasn't the right approach. But my point is, at least I had a code parameter in the callback command. But after shifting over to use the Implicit Grant method, this response is empty.

According to the documentation:

After consent has been granted, the Authentication Service verifies that the client application is valid and has access to the requested scope. If so, it redirects the access token to the provided callback URI in a hash fragment.

The response contains the following hash fragment parameters:

.......

It even shows an example response:

http://localhost/#access_token=eyJ0eXAi.....9LyiFrUqvdw&expires_in=28800&token_type=bearer&state=a39fh23hnf23

But, as mentioned, the callback response I receive has nothing of notable value. It's essentially just empty.

What am I missing here? What's the correct approach to complete the authentication process and proceed to actually using the API?

NOTE: I'm using Delphi, so none of the examples provided by DocuSign are compatible.


来源: stackexchange

问:
Use Object as Parameter with SignalR
I am trying to send an object from the client to the server and then from the server to the client(s). This is using the example code provided by Microsoft that I have slightly modified to use an object instead of a primitive, the code is below. The callback function on the client is never getting called after the connection.send from the JS client.

Hub class:

```<code>public class Chat : Hub
{
    public void BroadcastMessage(MessageModel message)
    {
        Clients.All.SendAsync("broadcastMessage", message);
    }
}
</code>```

Model Class:

```<code>public class MessageModel
{
    [JsonProperty("to")]
    public string _to = "";

    [JsonProperty("from")]
    public string _from = "";

    [JsonProperty("message")]
    public string _message = "";

    public MessageModel(string to, string from, string message)
    {
        _to = to;
        _from = from;
        _message = message;
    }
}
</code>```

Client Side JS (where I think the problem is...):

```<code><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/@aspnet/signalr@1.0.0/dist/browser/signalr.min.js">

function onConnected(connection) {
            console.log('connection started');
            //connection.send('broadcastMessage', '_SYSTEM_', username + ' JOINED');

            document.getElementById('sendmessage').addEventListener('click', function (event) {
                // Call the broadcastMessage method on the hub.
                if (messageInput.value) {
                    var msgObject = { to: 'Sally', from: 'Jonny', message: 'this is message' };
                    var myJSON = JSON.stringify(msgObject);
                    console.log(myJSON);

                    //neither object or stringify work
                    connection.send('broadcastMessage', msgObject);
                }

                // Clear text box and reset focus for next comment.
                messageInput.value = '';
                messageInput.focus();
                event.preventDefault();
            });
        }

function bindConnectionMessage(connection)
        {
            var messageCallback = function (message)
            {
                console.log('Never hits here...');

                if (!message) return;

                // Html encode display name and message.
                var encodedName = message.from;
                var encodedMsg = message.message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
                var messageEntry = createMessageEntry(encodedName, encodedMsg);

                var messageBox = document.getElementById('messages');
                messageBox.appendChild(messageEntry);
                messageBox.scrollTop = messageBox.scrollHeight;
            };

            // Create a function that the hub can call to broadcast messages.
            connection.on('broadcastMessage', messageCallback);
            connection.on('echo', messageCallback);
            connection.onclose(onConnectionError);
        }
</code>```

I've been at this for ages and can't figure out why it is so difficult.  I suspect it's something really obvious but could really use some help.  Thank you!

答:
I believe that you should user the Invoke method insted of Send like:

connection.invoke('BroadcastMessage', msgObject);
```

Note: the method name is case sensitive, so if your hub has BroadcastMessage on the client it should be the same and not broadcastMessage.

ContentLicense: CC BY-SA 4.0

Title: Use Object as Parameter with SignalR

Body:
I am trying to send an object from the client to the server and then from the server to the client(s). This is using the example code provided by Microsoft that I have slightly modified to use an object instead of a primitive, the code is below. The callback function on the client is never getting called after the connection.send from the JS client.

Hub class:

public class Chat : Hub
{
    public void BroadcastMessage(MessageModel message)
    {
        Clients.All.SendAsync("broadcastMessage", message);
    }
}

Model Class:

public class MessageModel
{
    [JsonProperty("to")]
    public string _to = "";

    [JsonProperty("from")]
    public string _from = "";

    [JsonProperty("message")]
    public string _message = "";

    public MessageModel(string to, string from, string message)
    {
        _to = to;
        _from = from;
        _message = message;
    }
}

Client Side JS (where I think the problem is...):

Body:
I believe that you should user the Invoke method insted of Send like:

connection.invoke('BroadcastMessage', msgObject);

Note: the method name is case sensitive, so if your hub has BroadcastMessage on the client it should be the same and not broadcastMessage.


问:
Sql Server get row closest (in the future) to today
I have a table that contains a history of items with a startdate (datetime) - it should only allow one single item against a date.  There's a validation procedure that will take a date and return a code (success/failure reason code) along with the 'next' historical item closest to today.

If this is the table data (id date title):

```<code>1 16/05/2010 'item 1'
2 17/05/2010 'item 2'
3 20/05/2010 'item 3'
</code>```

I want to validate an entry:

```<code>exec Validate '18/05/2010' 'item 4'
</code>```

Would return me: 'item 4' because the entry is valid and although the data hasn't been committed, it returns my new entry as the next available item because it's closest (in the future) to today.

```<code>exec Validate '24/05/2010' 'item 5'
</code>```

Should return me: 'Item 3'.  The date is also valid, but there is a record earlier then then new date, but later than today.

答:
Probably you can base your checks on next query:

```<code>select min(startdate)
from itemstable
where datediff(d, getdate(), startdate)>0
    and datediff(d, startdate, @datetocheck)>=0
</code>```

First clause checks for future startdates, second clause for startdates before or same as your supplied one.

(It's possible that some comparisons are wrong - happens always with date problems :))

ContentLicense: CC BY-SA 3.0

Body:
I have a table that contains a history of items with a startdate (datetime) - it should only allow one single item against a date.  There's a validation procedure that will take a date and return a code (success/failure reason code) along with the 'next' historical item closest to today.

If this is the table data (id date title):

1 16/05/2010 'item 1'
2 17/05/2010 'item 2'
3 20/05/2010 'item 3'

I want to validate an entry:

exec Validate '18/05/2010' 'item 4'

Would return me: 'item 4' because the entry is valid and although the data hasn't been committed, it returns my new entry as the next available item because it's closest (in the future) to today.

exec Validate '24/05/2010' 'item 5'

Should return me: 'Item 3'.  The date is also valid, but there is a record earlier then then new date, but later than today.

Body:
Probably you can base your checks on next query:

select min(startdate)
from itemstable
where datediff(d, getdate(), startdate)>0
    and datediff(d, startdate, @datetocheck)>=0

First clause checks for future startdates, second clause for startdates before or same as your supplied one.

(It's possible that some comparisons are wrong - happens always with date problems :))


问:
Pyspark - Regex - Extract value from last brackets
I created the following regular expression with the idea of extracting the last element in brackets. See that if I only have one parenthesis it works fine, but if I have 2 parenthesis it extracts the first one (which is a mistake) or extract with the brackets .

Do you know how to solve it?

```<code>    tmp= spark.createDataFrame(
    [
        (1, 'foo (123) oiashdj (hi)'),
        (2, 'bar oiashdj (hi)'),
    ],
    ['id', 'txt']
)

tmp = tmp.withColumn("old", regexp_extract(col("txt"), "(?<=\().+?(?=\))", 0));

tmp = tmp.withColumn("new", regexp_extract(col("txt"), "\(([^)]+)\)?$", 0));

tmp.show()

+---+--------------------+---+----+
| id|                 txt|old| new| needed
+---+--------------------+---+----+
|  1|foo (123) oiashdj...|123|(hi)|  hi
|  2|    bar oiashdj (hi)| hi|(hi)|  hi
+---+--------------------+---+----+
</code>```

答:
This should work. Use it with the single line flag.

```<code>\([^\(\)]*?\)(?!.*\([^\(\)]*?\))
</code>```

https://regex101.com/r/Qrnlf3/1

Body:
I created the following regular expression with the idea of extracting the last element in brackets. See that if I only have one parenthesis it works fine, but if I have 2 parenthesis it extracts the first one (which is a mistake) or extract with the brackets .

Do you know how to solve it?

    tmp= spark.createDataFrame(
    [
        (1, 'foo (123) oiashdj (hi)'),
        (2, 'bar oiashdj (hi)'),
    ],
    ['id', 'txt']
)

tmp = tmp.withColumn("old", regexp_extract(col("txt"), "(?<=\().+?(?=\))", 0));

tmp = tmp.withColumn("new", regexp_extract(col("txt"), "\(([^)]+)\)?$", 0));

tmp.show()

+---+--------------------+---+----+
| id|                 txt|old| new| needed
+---+--------------------+---+----+
|  1|foo (123) oiashdj...|123|(hi)|  hi
|  2|    bar oiashdj (hi)| hi|(hi)|  hi
+---+--------------------+---+----+

Body:
This should work. Use it with the single line flag.

\([^\(\)]*?\)(?!.*\([^\(\)]*?\))

https://regex101.com/r/Qrnlf3/1


问:
Conditional formatting formula for MAX value across filtered table in Google Sheets
A friend of mine is big into Final Fantasy XIV and asked me to build him a spreadsheet that would help him build a better gear set. I'm not very experienced with Google docs, so please forgive me if I have something mistaken.

https://drive.google.com/open?id=1loz2ARF42Dr_2sNqB4bGNkCbJ-TXnsD7o5LJ6RAmomQ

Objective: Select "head" and "strength" and ONLY the highest strength value from all of the 'head' slots would be highlighted.

The formula I am using is Format cell if Greater than or equal to

```<code>=if(and(and($B$2<>"",$F$2<>""),MAX(B11,B29,B46,B63)),0)
</code>```

(if the 'head' and 'strength' boxes are filled in, return the highest value of the list, then highlight the box if it is greater or equal to that value) and this rule is applied to each of the 'head' boxes.

I know this formula works, however, I am having an odd issue. I have been using conditional formatting to apply the above formula to each "head - strength" box, but when you update a different value to be higher, the previously highest value remains highlighted, even if you change the current highest value to be lower, it remains highlighted.

example: currently box b63 is the highest of the 4 values, if you change any of the other values to a high number (900) the box you changed will become highlighted, but box 63 still remains highlighted, even though it is no longer the highest value, even when changing b63 to 0, the box remains highlighted.

This method does work if the 'conditional formatting' rule is applied to each box INDIVIDUALLY, but with > 200 boxes, that is incredibly tedious. I'm wondering if I have somehow gotten the formula mistaken?

Otherwise, if there is another solution or way to do this, I'm open to suggestions.
Thank you for your time.

Body:
A friend of mine is big into Final Fantasy XIV and asked me to build him a spreadsheet that would help him build a better gear set. I'm not very experienced with Google docs, so please forgive me if I have something mistaken.

https://drive.google.com/open?id=1loz2ARF42Dr_2sNqB4bGNkCbJ-TXnsD7o5LJ6RAmomQ

Objective: Select "head" and "strength" and ONLY the highest strength value from all of the 'head' slots would be highlighted.

The formula I am using is Format cell if Greater than or equal to

=if(and(and($B$2<>"",$F$2<>""),MAX(B11,B29,B46,B63)),0)

(if the 'head' and 'strength' boxes are filled in, return the highest value of the list, then highlight the box if it is greater or equal to that value) and this rule is applied to each of the 'head' boxes.

I know this formula works, however, I am having an odd issue. I have been using conditional formatting to apply the above formula to each "head - strength" box, but when you update a different value to be higher, the previously highest value remains highlighted, even if you change the current highest value to be lower, it remains highlighted.

example: currently box b63 is the highest of the 4 values, if you change any of the other values to a high number (900) the box you changed will become highlighted, but box 63 still remains highlighted, even though it is no longer the highest value, even when changing b63 to 0, the box remains highlighted.

This method does work if the 'conditional formatting' rule is applied to each box INDIVIDUALLY, but with > 200 boxes, that is incredibly tedious. I'm wondering if I have somehow gotten the formula mistaken?

Otherwise, if there is another solution or way to do this, I'm open to suggestions.
Thank you for your time.

Body:
use:

=(B11=MAX(FILTER(INDIRECT(ADDRESS(11,
 MATCH(INDEX(FILTER($E$2:$E$7, $F$2:$F$7="x"), 1, 1), $A$10:$G$10, 0))&":"&
 ADDRESS(ROWS($A:$A),
 MATCH(INDEX(FILTER($E$2:$E$7, $F$2:$F$7="x"), 1, 1), $A$10:$G$10, 0))), $A$11:$A=
 INDEX(FILTER({$A$2:$A$7;$C$2:$C$7}, {$B$2:$B$7;$D$2:$D$7}="x"), 1, 1))))*($A11=
 INDEX(FILTER({$A$2:$A$7;$C$2:$C$7}, {$B$2:$B$7;$D$2:$D$7}="x"), 1, 1))

spreadsheet demo


问:
Create and append a table to databricks using nested data from json
I am generating a series of data nested in json and would like to append these files automatically to a table within the databricks. I don't have her schema ... this data will go to azure storage.

```<code>%python
# !/usr/bin/python
# -*- coding: utf-8 -*-

from pyspark.sql import SparkSession
from pyspark.sql.functions import *
import sys
import json
import os
import pandas as pd

def create_table():
    qry = """
    CREATE TEMPORARY TABLE vsts
    USING json
    OPTIONS (path 'dbfs:/mnt/lake/vsts/*.json')
    """
    return spark.sql(qry)

if __name__ == "__main__":
    create_table()
</code>```

I tried to create a temporary table and then put the new data into a permanent table but this process did not work. Basically I need to insert the hundreds of files that will be created with data nested in a single table.

```<code>from pyspark.sql import SparkSession
from pyspark.sql.functions import *
import sys
import json
import os

def get_clear_default():
    qry_default = """
    select * from vsts
    """
    return spark.sql(qry_default)

def create_table():
    qry = """
    CREATE TABLE IF NOT EXISTS `db_sandbox`.`tst_vsts`
    USING JSON
    OPTIONS (
    path 'dbfs:/mnt/lake/vsts/*.json'
    )
    """
    return spark.sql(qry)

if __name__ == "__main__":
    create_table()
</code>```

答:
We can probably try this route.

```<code>df=spark.read.option("multiline", "true").json("<Azure_Path>")

df.createOrReplaceTempView("test")
</code>```

Then you can start using this 'test' table in set of Spark SQLs for creating table.

If in case you want to split down the array of elements in nested JSON then try POS Explode for denormalizing them into table.

```<code>        spark.sql("SELECT \
              n.pos AS position, \
              n.<unique_field> AS <unique_field>, \
              <field1>[pos] AS <field1>, \
              <field2>[pos] AS <field2>, \
              <field3>[pos] AS <field3>\
       FROM \
              test \
       LATERAL VIEW POSEXPLODE(<parent_field>.<unique_field>) n AS pos, <unique_field>").show()
</code>```

Body:
I am generating a series of data nested in json and would like to append these files automatically to a table within the databricks. I don't have her schema ... this data will go to azure storage.

%python
# !/usr/bin/python
# -*- coding: utf-8 -*-

from pyspark.sql import SparkSession
from pyspark.sql.functions import *
import sys
import json
import os
import pandas as pd

def create_table():
    qry = """
    CREATE TEMPORARY TABLE vsts
    USING json
    OPTIONS (path 'dbfs:/mnt/lake/vsts/*.json')
    """
    return spark.sql(qry)

if __name__ == "__main__":
    create_table()

I tried to create a temporary table and then put the new data into a permanent table but this process did not work. Basically I need to insert the hundreds of files that will be created with data nested in a single table.

from pyspark.sql import SparkSession
from pyspark.sql.functions import *
import sys
import json
import os

def get_clear_default():
    qry_default = """
    select * from vsts
    """
    return spark.sql(qry_default)

def create_table():
    qry = """
    CREATE TABLE IF NOT EXISTS `db_sandbox`.`tst_vsts`
    USING JSON
    OPTIONS (
    path 'dbfs:/mnt/lake/vsts/*.json'
    )
    """
    return spark.sql(qry)

if __name__ == "__main__":
    create_table()

Body:
We can probably try this route.

df=spark.read.option("multiline", "true").json("<Azure_Path>")

df.createOrReplaceTempView("test")

Then you can start using this 'test' table in set of Spark SQLs for creating table.

If in case you want to split down the array of elements in nested JSON then try POS Explode for denormalizing them into table.

        spark.sql("SELECT \
              n.pos AS position, \
              n.<unique_field> AS <unique_field>, \
              <field1>[pos] AS <field1>, \
              <field2>[pos] AS <field2>, \
              <field3>[pos] AS <field3>\
       FROM \
              test \
       LATERAL VIEW POSEXPLODE(<parent_field>.<unique_field>) n AS pos, <unique_field>").show()


问:
Java Database Entity Inheritance
In my database, I have 2 table is Categories and Products.

The Products table has a reference key references to CategoryId in the Categories table.

And in my Java Project, I have 2 entities: Category and Product.

So I wonder does the Product class have to extends Category class?

答:
In your case you need to add Category like a attribut in your Product Class.
You can add a list of Product in your Category class for biderctionnal relation.</p>

Title: Java Database Entity Inheritance


答:
To extract the substring between parentheses with no other parentheses inside at the end of the string you may use

```<code>tmp = tmp.withColumn("new", regexp_extract(col("txt"), r"\(([^()]+)\)$", 1));
</code>```

Details

\( - matches (

([^()]+) - captures into Group 1 any 1+ chars other than ( and )

\) - a ) char

$ - at the end of the string.

The 1 argument tells the regexp_extract to extract Group 1 value.

See the regex demo online.

NOTE: To allow trailing whitespace, add \s* right before $: r"\(([^()]+)\)\s*$"

NOTE2: To match the last occurrence of such a substring in a longer string, with exactly the same code as above, use

```<code>r"(?s).*\(([^()]+)\)"
</code>```

The .* will grab all the text up to the end, and then backtracking will do the job.

Title: Pyspark - Regex - Extract value from last brackets

Body:
To extract the substring between parentheses with no other parentheses inside at the end of the string you may use

tmp = tmp.withColumn("new", regexp_extract(col("txt"), r"\(([^()]+)\)$", 1));

Details

\( - matches (

([^()]+) - captures into Group 1 any 1+ chars other than ( and )

\) - a ) char

$ - at the end of the string.

The 1 argument tells the regexp_extract to extract Group 1 value.

See the regex demo online.

NOTE: To allow trailing whitespace, add \s* right before $: r"\(([^()]+)\)\s*$"

NOTE2: To match the last occurrence of such a substring in a longer string, with exactly the same code as above, use

r"(?s).*\(([^()]+)\)"

The .* will grab all the text up to the end, and then backtracking will do the job.


问:
c / interrupted system call / fork vs. thread
I discovered an issue with thread implementation, that is strange to me. Maybe some of you can explain it to me, would be great.

I am working on something like a proxy, a program (running on different machines) that receives packets over eth0 and sends it through ath0 (wireless) to another machine which is doing the exactly same thing. Actually I am not at all sure what is causing my problem, that's because I am new to everything, linux and c programming.

I start two threads,

one is listening (socket) on eth0 for incoming packets and sends it out through ath0 (also socket)

and the other thread is listening on ath0 and sends through eth0.

If I use threads, I get an error like that:

```<code>sh-2.05b# ./socketex
Failed to send network header packet.
: Interrupted system call
</code>```

If I use fork(), the program works as expected.
Can someone explain that behaviour to me?

Just to show the sender implementation here comes its code snippet:

```<code>while(keep_going) {
    memset(&buffer[0], '\0', sizeof(buffer));

    recvlen = recvfrom(sockfd_in, buffer, BUFLEN, 0, (struct sockaddr *) &incoming, &ilen);
    if(recvlen < 0) {
        perror("something went wrong / incoming\n");
        exit(-1);
    }

    strcpy(msg, buffer);
    buflen = strlen(msg);

    sentlen = ath_sendto(sfd, &btpinfo, &addrnwh, &nwh,  buflen, msg, &selpv2, &depv);

    if(sentlen == E_ERR) {
        perror("Failed to send network header packet.\n");
        exit(-1);
    }
}
</code>```

UPDATE: my main file, starting either threads or processes (fork)

```<code>int main(void) {

port_config pConfig;

memset(&pConfig, 0, sizeof(pConfig));
pConfig.inPort = 2002;
pConfig.outPort = 2003;

pid_t retval = fork();

if(retval == 0) {
    // child process
    pc2wsuThread((void *) &pConfig);
} else if (retval < 0) {
    perror("fork not successful\n");
} else {
    // parent process
    wsu2pcThread((void *) &pConfig);
}

/*
wint8 rc1, rc2 = 0;

pthread_t pc2wsu;
pthread_t wsu2pc;

rc1 = pthread_create(&pc2wsu, NULL, pc2wsuThread, (void *) &pConfig);
rc2 = pthread_create(&wsu2pc, NULL, wsu2pcThread, (void *) &pConfig);

if(rc1) {
    printf("error: pthread_create() is %d\n", rc1);
    return(-1);
}

if(rc2) {
    printf("error: pthread_create() is %d\n", rc2);
    return(-1);
}

pthread_join(pc2wsu, NULL);
pthread_join(wsu2pc, NULL);
*/
return 0;
}
</code>```

Does it help?

update 05/30/2011

```<code>-sh-2.05b# ./wsuproxy 192.168.1.100
mgmtsrvc
mgmtsrvc
Failed to send network header packet.
: Interrupted system call
13.254158,75.165482,DATAAAAAAmgmtsrvc
mgmtsrvc
mgmtsrvc
</code>```

Still get the interrupted system call, as you can see above.
I blocked all signals as followed:

```<code>sigset_t signal_mask;
sigfillset(&signal_mask);
sigprocmask(SIG_BLOCK, &signal_mask, NULL);
</code>```

The two threads are working on the same interfaces, but on different ports. The problem seems to appear still in the same place (please find it in the first code snippet). I can't go further and have not enough knowledge of how to solve that problem. Maybe some of you can help me here again.

Thanks in advance.

答:
EINTR does not itself indicate an error. It means that your process received a signal while it was in the sendto syscall, and that syscall hadn't sent any data yet (that's important).

You could retry the send in this case, but a good thing would be to figure out what signal caused the interruption. If this is reproducible, try using strace.

If you're the one sending the signal, well, you know what to do :-)

Note that on linux, you can receive EINTR on sendto (and some other functions) even if you haven't installed a handler yourself. This can happen if:

 the process is stopped (via SIGSTOP for example) and restarted (with SIGCONT)

 you have set a send timeout on the socket (via SO_SNDTIMEO)

See the signal(7) man page (at the very bottom) for more details.

So if you're "suspending" your service (or something else is), that EINTR is expected and you should restart the call.

Body:
I discovered an issue with thread implementation, that is strange to me. Maybe some of you can explain it to me, would be great.

I am working on something like a proxy, a program (running on different machines) that receives packets over eth0 and sends it through ath0 (wireless) to another machine which is doing the exactly same thing. Actually I am not at all sure what is causing my problem, that's because I am new to everything, linux and c programming.

I start two threads,

one is listening (socket) on eth0 for incoming packets and sends it out through ath0 (also socket)

and the other thread is listening on ath0 and sends through eth0.

If I use threads, I get an error like that:

sh-2.05b# ./socketex
Failed to send network header packet.
: Interrupted system call

If I use fork(), the program works as expected.
Can someone explain that behaviour to me?

Just to show the sender implementation here comes its code snippet:

while(keep_going) {
    memset(&buffer[0], '\0', sizeof(buffer));

    recvlen = recvfrom(sockfd_in, buffer, BUFLEN, 0, (struct sockaddr *) &incoming, &ilen);
    if(recvlen < 0) {
        perror("something went wrong / incoming\n");
        exit(-1);
    }

    strcpy(msg, buffer);
    buflen = strlen(msg);

    sentlen = ath_sendto(sfd, &btpinfo, &addrnwh, &nwh,  buflen, msg, &selpv2, &depv);

    if(sentlen == E_ERR) {
        perror("Failed to send network header packet.\n");
        exit(-1);
    }
}

UPDATE: my main file, starting either threads or processes (fork)

int main(void) {

port_config pConfig;

memset(&pConfig, 0, sizeof(pConfig));
pConfig.inPort = 2002;
pConfig.outPort = 2003;

pid_t retval = fork();

if(retval == 0) {
    // child process
    pc2wsuThread((void *) &pConfig);
} else if (retval < 0) {
    perror("fork not successful\n");
} else {
    // parent process
    wsu2pcThread((void *) &pConfig);
}

/*
wint8 rc1, rc2 = 0;

pthread_t pc2wsu;
pthread_t wsu2pc;

rc1 = pthread_create(&pc2wsu, NULL, pc2wsuThread, (void *) &pConfig);
rc2 = pthread_create(&wsu2pc, NULL, wsu2pcThread, (void *) &pConfig);

if(rc1) {
    printf("error: pthread_create() is %d\n", rc1);
    return(-1);
}

if(rc2) {
    printf("error: pthread_create() is %d\n", rc2);
    return(-1);
}

pthread_join(pc2wsu, NULL);
pthread_join(wsu2pc, NULL);
*/
return 0;
}

Does it help?

update 05/30/2011

-sh-2.05b# ./wsuproxy 192.168.1.100
mgmtsrvc
mgmtsrvc
Failed to send network header packet.
: Interrupted system call
13.254158,75.165482,DATAAAAAAmgmtsrvc
mgmtsrvc
mgmtsrvc

Still get the interrupted system call, as you can see above.
I blocked all signals as followed:

sigset_t signal_mask;
sigfillset(&signal_mask);
sigprocmask(SIG_BLOCK, &signal_mask, NULL);

The two threads are working on the same interfaces, but on different ports. The problem seems to appear still in the same place (please find it in the first code snippet). I can't go further and have not enough knowledge of how to solve that problem. Maybe some of you can help me here again.

Thanks in advance.


问:
How to convert datetime to integer in python
How can I convert YYYY-MM-DD hh:mm:ss format to integer in python?
for example 2014-02-12 20:51:14 -> to integer.

I only know how to convert hh:mm:ss but not yyyy-mm-dd hh:mm:ss

```<code>def time_to_num(time_str):
    hh, mm , ss = map(int, time_str.split(':'))
    return ss + 60*(mm + 60*hh)
</code>```

答:
When converting datetime to integers one must keep in mind the tens, hundreds and thousands.... like
"2018-11-03" must be like 20181103 in int
for that you have to
2018*10000 + 100* 11 + 3

Similarly another example,
"2018-11-03 10:02:05" must be like 20181103100205 in int

Explanatory Code

```<code>dt = datetime(2018,11,3,10,2,5)
print (dt)

#print (dt.timestamp()) # unix representation ... not useful when converting to int

print (dt.strftime("%Y-%m-%d"))
print (dt.year*10000 + dt.month* 100  + dt.day)
print (int(dt.strftime("%Y%m%d")))

print (dt.strftime("%Y-%m-%d %H:%M:%S"))
print (dt.year*10000000000 + dt.month* 100000000 +dt.day * 1000000 + dt.hour*10000  +  dt.minute*100 + dt.second)
print (int(dt.strftime("%Y%m%d%H%M%S")))
</code>```

General Function

To avoid that doing manually use below function

```<code>def datetime_to_int(dt):
    return int(dt.strftime("%Y%m%d%H%M%S"))
</code>```

Body:
How can I convert YYYY-MM-DD hh:mm:ss format to integer in python?
for example 2014-02-12 20:51:14 -> to integer.

I only know how to convert hh:mm:ss but not yyyy-mm-dd hh:mm:ss

def time_to_num(time_str):
    hh, mm , ss = map(int, time_str.split(':'))
    return ss + 60*(mm + 60*hh)

Body:
When converting datetime to integers one must keep in mind the tens, hundreds and thousands.... like
"2018-11-03" must be like 20181103 in int
for that you have to
2018*10000 + 100* 11 + 3

Similarly another example,
"2018-11-03 10:02:05" must be like 20181103100205 in int

Explanatory Code

dt = datetime(2018,11,3,10,2,5)
print (dt)

#print (dt.timestamp()) # unix representation ... not useful when converting to int

print (dt.strftime("%Y-%m-%d"))
print (dt.year*10000 + dt.month* 100  + dt.day)
print (int(dt.strftime("%Y%m%d")))

print (dt.strftime("%Y-%m-%d %H:%M:%S"))
print (dt.year*10000000000 + dt.month* 100000000 +dt.day * 1000000 + dt.hour*10000  +  dt.minute*100 + dt.second)
print (int(dt.strftime("%Y%m%d%H%M%S")))

General Function

To avoid that doing manually use below function

def datetime_to_int(dt):
    return int(dt.strftime("%Y%m%d%H%M%S"))


问:
OpenFace CoreML model. No face detection
I'm learning all I can about machine learning specifically on iOS. I found the OpenFace model converted into a .mlmodel and I can successfully run it through vision and get a 128 vector space representation of each face.

First, I make the Vision model object from the core ML Model that is in my project's file system. I also construct the VNCoreMLRequest from that model and assign a function for the completion.

```<code>let openFaceModel = try! VNCoreMLModel(for: OpenFace().model)
var request: VNCoreMLRequest = VNCoreMLRequest(model: self.openFaceModel, completionHandler: self.visionResults)
</code>```

Second, I get the CMSampleBuffer delivered to me from the camera. I use it to perform the request.

```<code>func stream(_ pixelBuffer: CMSampleBuffer) {
    guard let cvBuffer = CMSampleBufferGetImageBuffer(buffer) else {
        throw CMBufferProcessorError.cvPixelBufferConversionFailed
    }

    let handler = VNImageRequestHandler(cvPixelBuffer: cvBuffer, options: [:])

    do {
        try handler.perform([self.request])
    }catch{
        print(error)
    }

}
</code>```

Finally, my function that was assigned as the completion handle for the VNCoreMLRequest gets called with the results.

```<code>func visionResults(request: VNRequest, error: Error?) {
    guard let features = request.results as? [VNCoreMLFeatureValueObservation] else {
        print("No Results")
        return
    }

    print("Feature Count: \(features.count)")

    for feature in features {
        quickLog(title: "Feature Type", message: "\(feature.featureValue.type.rawValue)")
        quickLog(title: "Feature Value", message: "\(feature.featureValue.multiArrayValue)")
    }
}
</code>```

I'm successfully retrieving the 128 dimension multi array. Now I have three questions based on two observations.

I observed that I get a unique vector back even when there are no faces in the frame.

1) Is this desired behavior? If so how do I filter for a multi array result that represents the absence of a face?

I observed that I only ever get back one results even if there are multiple faces in the frame.

2) Is this expected behavior for this model?

Thank you for the help!

答:
OpenFace works on a single face image, that's what it has been trained for. It doesn't check whether there is a face or not in the input image. It also needs the cropped face images to be aligned according to eyes and nose so that in each image the eyes and noses are in the same place.

OpenFace normalizes each face before training so each face image that goes into the model has the eyes and nose at the same location. This allows it to be trainable with fewer images. It has fewer parameters than FaceNet, which means it runs faster and requires less space on the disk.

OpenFace model work in this way: it takes face image as input and creates 128 valued vector as output. These vectors can be used to compare and identify faces and it's unique for each face. Imagine it like to put every face in a unique location in a cube(3d) but in 128 dimensions. This way you can check the distance between faces and if it's very close to each other (threshold value 0.99) you can say the two picture belongs to same person, if it's higher than the threshold you can say images belong two different people. The distance measure is nothing but the sum of the squared differences of dots (Euclidean distance).

Body:
I'm learning all I can about machine learning specifically on iOS. I found the OpenFace model converted into a .mlmodel and I can successfully run it through vision and get a 128 vector space representation of each face.

First, I make the Vision model object from the core ML Model that is in my project's file system. I also construct the VNCoreMLRequest from that model and assign a function for the completion.

let openFaceModel = try! VNCoreMLModel(for: OpenFace().model)
var request: VNCoreMLRequest = VNCoreMLRequest(model: self.openFaceModel, completionHandler: self.visionResults)

Second, I get the CMSampleBuffer delivered to me from the camera. I use it to perform the request.

func stream(_ pixelBuffer: CMSampleBuffer) {
    guard let cvBuffer = CMSampleBufferGetImageBuffer(buffer) else {
        throw CMBufferProcessorError.cvPixelBufferConversionFailed
    }

    let handler = VNImageRequestHandler(cvPixelBuffer: cvBuffer, options: [:])

    do {
        try handler.perform([self.request])
    }catch{
        print(error)
    }

}

Finally, my function that was assigned as the completion handle for the VNCoreMLRequest gets called with the results.

func visionResults(request: VNRequest, error: Error?) {
    guard let features = request.results as? [VNCoreMLFeatureValueObservation] else {
        print("No Results")
        return
    }

    print("Feature Count: \(features.count)")

    for feature in features {
        quickLog(title: "Feature Type", message: "\(feature.featureValue.type.rawValue)")
        quickLog(title: "Feature Value", message: "\(feature.featureValue.multiArrayValue)")
    }
}

I'm successfully retrieving the 128 dimension multi array. Now I have three questions based on two observations.

I observed that I get a unique vector back even when there are no faces in the frame.

1) Is this desired behavior? If so how do I filter for a multi array result that represents the absence of a face?

I observed that I only ever get back one results even if there are multiple faces in the frame.

2) Is this expected behavior for this model?

Thank you for the help!


问:
How can I filter `git cherry` output?
I ran the below command,

```<code>git cherry main dev
</code>```

The output for above command is like,

```<code>+ d86f3e25f42b546af008b774c2649d585cc48310
- 1d90a12b91b461f857eb373d69372a2864b9e651
+ 4194aa6d206225242e881d2128e59981b8826eeb
</code>```

I want to see only commits which are not yet cherry-picked. i.e. (+ signed sha only).

Expected output,

```<code>+ d86f3e25f42b546af008b774c2649d585cc48310
+ 4194aa6d206225242e881d2128e59981b8826eeb
</code>```

How can I do so?

答:
This will do it :

```<code>git cherry main dev | grep '^+'
</code>```

Regards!

Title: How can I filter `git cherry` output?

Body:
I ran the below command,

git cherry main dev

The output for above command is like,

+ d86f3e25f42b546af008b774c2649d585cc48310
- 1d90a12b91b461f857eb373d69372a2864b9e651
+ 4194aa6d206225242e881d2128e59981b8826eeb

I want to see only commits which are not yet cherry-picked. i.e. (+ signed sha only).

Expected output,

+ d86f3e25f42b546af008b774c2649d585cc48310
+ 4194aa6d206225242e881d2128e59981b8826eeb

How can I do so?

Body:
This will do it :

git cherry main dev | grep '^+'

Regards!


问:
Laravel: Undefined variable Posts
I am trying to display data using a foreach statement within my system. Now i am passing through the variable 'posts' into my view however i keep receiving the error: Undefined variable: posts (View:.

Search.blade.php

```<code> @foreach($posts as $post)
  <option value="{{$post->distance}}">{{ $post->distance}}</option>

 @endforeach
</code>```

SearchController.php

```<code>     public function index()
    {
       $posts = Post::all();
       return view('pages.Search')->with('posts', $posts);

     }
</code>```

Now in my PostsController.php i have similar code which returns all the posts.

PostsController.php

```<code>  public function index()
   {
    $posts = Post::all();
    return view('posts.index')->with('posts', $posts);

}
</code>```

Is this going to cause the error, i didnt think it would cause its returning to a completely separate page.

答:
you could probably do it this way:</p>

```<code>public function index()
   {
    $data['posts'] = Post::all();
    return view('posts.index',$data);

}
</code>```

Title: Laravel: Undefined variable Posts

Body:
I am trying to display data using a foreach statement within my system. Now i am passing through the variable 'posts' into my view however i keep receiving the error: Undefined variable: posts (View:.

Search.blade.php

 @foreach($posts as $post)
  <option value="{{$post->distance}}">{{ $post->distance}}</option>

 @endforeach

SearchController.php

     public function index()
    {
       $posts = Post::all();
       return view('pages.Search')->with('posts', $posts);

     }

Now in my PostsController.php i have similar code which returns all the posts.

PostsController.php

  public function index()
   {
    $posts = Post::all();
    return view('posts.index')->with('posts', $posts);

}

Is this going to cause the error, i didnt think it would cause its returning to a completely separate page.

Body:
you could probably do it this way:

public function index()
   {
    $data['posts'] = Post::all();
    return view('posts.index',$data);

}


问:
Database in celery task is out dated
I have Django==2.2.8 and celery==4.3.0, redis as broker.

Have very simple drf view to create BankEntry.

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        instance = serializer.save()
        bank_entry = BankEntries.objects.get(pk=instance.id)
        async_task = async_create_transactions.delay(bank_entry.pk) <--- celery task
```

<pre class="lang-py prettyprint-override"><code>@celery_app.task()
def async_create_transactions(entry_id):
    bank_entry = BankEntries.objects.filter(pk=entry_id).first()
    if bank_entry: <---- HERE SOMETIMES BANK_ENTRY IS NONE, But why, we just created it
        return bank_entry.create_entries()

</code>```

Have no idea why, but in async_create_transactions I can get just created BankEntry.
I'm sure that celery setup use same database, because in a next async_create_transactions call, I can see previous BankEntry but not the current one.

I don't have, hooks, signals, postgresql functions and other side effects.

答:
What is most likely happening is that your background task is trying to access the database entry before the serializer.save() has been completed fully. I have run into a similar problem before.

What you can do is add a short delay after you invoke your async_create_transactions which will give time for the record saving to be complete. So you could do something like this:

```<code>from time import sleep

@celery_app.task()
def async_create_transactions(entry_id):
    sleep(1)
    bank_entry = BankEntries.objects.filter(pk=entry_id).first()
    if bank_entry:
        return bank_entry.create_entries()
</code>```

This may not be the most elegant solution, but it has worked for me in many cases.

Title: Database in celery task is out dated

Body:
I have Django==2.2.8 and celery==4.3.0, redis as broker.

Have very simple drf view to create BankEntry.

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        instance = serializer.save()
        bank_entry = BankEntries.objects.get(pk=instance.id)
        async_task = async_create_transactions.delay(bank_entry.pk) <--- celery task

@celery_app.task()
def async_create_transactions(entry_id):
    bank_entry = BankEntries.objects.filter(pk=entry_id).first()
    if bank_entry: <---- HERE SOMETIMES BANK_ENTRY IS NONE, But why, we just created it
        return bank_entry.create_entries()

Have no idea why, but in async_create_transactions I can get just created BankEntry.
I'm sure that celery setup use same database, because in a next async_create_transactions call, I can see previous BankEntry but not the current one.

I don't have, hooks, signals, postgresql functions and other side effects.

Body:
What is most likely happening is that your background task is trying to access the database entry before the serializer.save() has been completed fully. I have run into a similar problem before.

What you can do is add a short delay after you invoke your async_create_transactions which will give time for the record saving to be complete. So you could do something like this:

from time import sleep

@celery_app.task()
def async_create_transactions(entry_id):
    sleep(1)
    bank_entry = BankEntries.objects.filter(pk=entry_id).first()
    if bank_entry:
        return bank_entry.create_entries()

This may not be the most elegant solution, but it has worked for me in many cases.


问:
Return column 1 only if column 2 is NULL in all rows with the same column 1
I'm sure this is SQL-101 but I can't figure it out nor can I come up with the correct verbiage to find any useful results in web searches.

Example table:

```<code>id      ext             nr
289979  111-000-1002    529
392959  111-000-1002    NULL
449707  111-000-1002    335
400151  999-555-1212    NULL
456902  999-555-1212    NULL
471001  999-555-1212    NULL

</code>```

I am trying to format a query to return the ext if the nr on all rows is NULL so the query would return 999-555-1212 but not 111-000-1002.

答:
Is this what you want?</p>

```<code>select ext
from t
group by ext
having max(nr) is null;
</code>```

Body:
I'm sure this is SQL-101 but I can't figure it out nor can I come up with the correct verbiage to find any useful results in web searches.

Example table:

id      ext             nr
289979  111-000-1002    529
392959  111-000-1002    NULL
449707  111-000-1002    335
400151  999-555-1212    NULL
456902  999-555-1212    NULL
471001  999-555-1212    NULL

I am trying to format a query to return the ext if the nr on all rows is NULL so the query would return 999-555-1212 but not 111-000-1002.

Body:
Is this what you want?

select ext
from t
group by ext
having max(nr) is null;


问:
Android: Retrieving shared preferences of other application
I have a settings application from which i have to retrieve other applications preferences, but i don't have the details of keys in them, how can i retrieve all the available keys and values in that preference?

Thanks,
Swathi

答:
Assuming the preference are WORLD_READABLE, this might work:

final ArrayList<HashMap<String,String>> LIST = new ArrayList<HashMap<String,String>>();
// where com.example is the owning  app containing the preferences
Context myContext = createPackageContext("com.example", Context.MODE_WORLD_WRITEABLE);
SharedPreferences testPrefs = myContext.getSharedPreferences("test_prefs", Context.MODE_WORLD_READABLE);
Map<String, ?> items = testPrefs .getAll();
for(String s : items.keySet()) {
  // do something like String value = items.get(s).toString());
}
```


问:
How can I load and use jsgrid lib in React?
I have problem with jsgrid lib. I try to load it to React project. I included libraries to project, like in instructions on npmjs.

My code loooks:

index.html

<!DOCTYPE html>

    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css" />
    <link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css" />
    <title>React App</title>

    You need to enable JavaScript to run this app.

```

<p>app.js</p>

<pre class="lang-js prettyprint-override"><code>import React from 'react';
import logo from './logo.svg';
import './App.css';
import * as JSGRID from 'jsgrid'

export default class App extends React.Component {
  componentDidMount() {

    window.$("#jsGrid").JSGRID.jsGrid({
      width: "100%",
      height: "400px",

      filtering: true,
      editing: true,
      sorting: true,
      paging: true,

      fields: [
          { name: "Name", type: "text", width: 150 },
          { name: "Age", type: "number", width: 50 },
          { name: "Address", type: "text", width: 200 },
          { name: "Country", type: "select", items: 0, valueField: "Id", textField: "Name" },
          { name: "Married", type: "checkbox", title: "Is Married", sorting: false },
          { type: "control" }
      ]
  });
  }

  render() {
    return (
      <div id="jsGrid">

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

Still have some errors:

I wasted some time on it, Is any instructions how include jquery projects like this to React? Or maybe somebody faced with problem like this and know how to fix it.

答:
dont use any prefix at all, just $("#jsGrid").jsGrid(...

and import jquery

import $ from 'jquery';

also, read this

How to use JQuery with ReactJS

Body:
I have problem with jsgrid lib. I try to load it to React project. I included libraries to project, like in instructions on npmjs.

My code loooks:

index.html

<!DOCTYPE html>

    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css" />
    <link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css" />
    <title>React App</title>

    You need to enable JavaScript to run this app.

app.js

import React from 'react';
import logo from './logo.svg';
import './App.css';
import * as JSGRID from 'jsgrid'

export default class App extends React.Component {
  componentDidMount() {

    window.$("#jsGrid").JSGRID.jsGrid({
      width: "100%",
      height: "400px",

      filtering: true,
      editing: true,
      sorting: true,
      paging: true,

      fields: [
          { name: "Name", type: "text", width: 150 },
          { name: "Age", type: "number", width: 50 },
          { name: "Address", type: "text", width: 200 },
          { name: "Country", type: "select", items: 0, valueField: "Id", textField: "Name" },
          { name: "Married", type: "checkbox", title: "Is Married", sorting: false },
          { type: "control" }
      ]
  });
  }

  render() {
    return (

    );
    }
}

Still have some errors:

I wasted some time on it, Is any instructions how include jquery projects like this to React? Or maybe somebody faced with problem like this and know how to fix it.


答:
A possibel alternative using a data.table-join:

```<code>final_dt[initial_dt
         , on = .(IID)
         , ind_frist := c("", "top","hop")[1L + (Dates > TARGET & Dates <= max_finish_target_date) +
                                             Dates %between% .(ENTRY, max_finish_target_date)]][]
</code>```

which gives:

```<code>    IID      Dates ind_frist
 1:   1 2020-02-10
 2:   1 2020-02-11       top
 3:   1 2020-02-12       top
 4:   1 2020-02-13       top
 5:   1 2020-02-14       top
 6:   1 2020-02-15       top
 7:   1 2020-02-16       hop
 8:   1 2020-02-17       hop
 9:   1 2020-02-18       hop
10:   1 2020-02-19       hop
11:   2 2020-02-10
12:   2 2020-02-11
13:   2 2020-02-12
14:   2 2020-02-13       top
15:   2 2020-02-14       top
16:   2 2020-02-15       top
17:   2 2020-02-16       top
18:   2 2020-02-17       top
19:   2 2020-02-18       top
20:   2 2020-02-19       top
21:   3 2020-02-10
22:   3 2020-02-11
23:   3 2020-02-12
24:   3 2020-02-13
25:   3 2020-02-14
26:   3 2020-02-15       top
27:   3 2020-02-16       top
28:   3 2020-02-17       hop
29:   3 2020-02-18       hop
30:   3 2020-02-19       hop
</code>```

This is the same as the output of the for-loop.

Some explanation: the part 1L + (Dates > TARGET & Dates <= max_finish_target_date) + Dates %between% .(ENTRY, max_finish_target_date) creates an index vector of one's, two's and three's of equal length as the number of rows of final_dt; if you put that between square brackets after c("", "top","hop"), for each one you will get an empty string, for each two you will get "top" and for each three you will get "hop".

Title: Increasing code execution time-efficiency using data.table and for-loop

Body:
Problem: How can I make the for-loop in below code run more time-efficiently? For this toy example it works in a reasonable amount of time. However, unique_ids will be a vector of approximately 8000 entries and the for-loop slows down heavily the computation. Any ideas? Many thanks!

Purpose:
Cluster retrospectively IIDs for each day into hop and top based on calculation logic in for-loop.

Initial Data:

   IID      ENTRY     FINISH     TARGET max_finish_target_date
1:      1 2020-02-11 2020-02-19 2020-02-15             2020-02-19
2:      2 2020-02-13 2020-02-17 2020-02-19             2020-02-19

Final (Target) Data:

 IID      Dates    ind_frist
 1:      1 2020-02-10
 2:      1 2020-02-11 hop
 3:      1 2020-02-12 hop
 4:      1 2020-02-13 hop
 5:      1 2020-02-14 hop
 6:      1 2020-02-15 hop
 7:      1 2020-02-16 top
 8:      1 2020-02-17 top
 9:      1 2020-02-18 top
10:      1 2020-02-19 top
11:      2 2020-02-10
12:      2 2020-02-11
13:      2 2020-02-12
14:      2 2020-02-13 hop
15:      2 2020-02-14 hop
16:      2 2020-02-15 hop
17:      2 2020-02-16 hop
18:      2 2020-02-17 hop
19:      2 2020-02-18
20:      2 2020-02-19
21:      3 2020-02-10
22:      3 2020-02-11
23:      3 2020-02-12
24:      3 2020-02-13
25:      3 2020-02-14
26:      3 2020-02-15 hop
27:      3 2020-02-16 hop
28:      3 2020-02-17 top
29:      3 2020-02-18 top
30:      3 2020-02-19 top

Code

rm(list = ls())

library(data.table)

# Some sample start data
initial_dt <- data.table(IID = c(1, 2, 3),
                         ENTRY = c("2020-02-11", "2020-02-13", "2020-02-15"),
                         FINISH = c("2020-02-19", "2020-02-17", ""),
                         TARGET = c("2020-02-15", "2020-02-19", "2020-02-16"))

initial_dt[, ":="(ENTRY = ymd(ENTRY),
                  FINISH = ymd(FINISH),
                  TARGET = ymd(TARGET))]

initial_dt[is.na(FINISH), FINISH := as.Date(ymd_hms(Sys.time()), format = "%Y-%m-%d")]

initial_dt[, max_finish_target_date := pmax(FINISH, TARGET)]

# Specify target data shape and output format
unique_ids <- c(1, 2, 3)

dts <- seq(as.Date("2020-02-10", format = "%Y-%m-%d"), as.Date(ymd_hms(Sys.time()), format = "%Y-%m-%d"), by = "days")

ids <- rep(unique_ids, each = length(dts))
len <- length(unique_ids)

final_dt <- data.table(IID = ids,
                       Dates = rep(dts, times = len))

# Calculation logic
# QUESTION: How can I make this part below run more efficiently and less time costly?
for (d_id in unique_ids){
  final_dt[(IID == d_id) & (Dates %between% c(initial_dt[IID == d_id, ENTRY], initial_dt[IID == d_id, max_finish_target_date])),
                ind_frist := ifelse((Dates > initial_dt[IID == d_id, TARGET]) & (Dates <= initial_dt[IID == d_id, max_finish_target_date]),
                                    "hop",
                                    "top")]
}

Body:
A possibel alternative using a data.table-join:

final_dt[initial_dt
         , on = .(IID)
         , ind_frist := c("", "top","hop")[1L + (Dates > TARGET & Dates <= max_finish_target_date) +
                                             Dates %between% .(ENTRY, max_finish_target_date)]][]

which gives:

    IID      Dates ind_frist
 1:   1 2020-02-10
 2:   1 2020-02-11       top
 3:   1 2020-02-12       top
 4:   1 2020-02-13       top
 5:   1 2020-02-14       top
 6:   1 2020-02-15       top
 7:   1 2020-02-16       hop
 8:   1 2020-02-17       hop
 9:   1 2020-02-18       hop
10:   1 2020-02-19       hop
11:   2 2020-02-10
12:   2 2020-02-11
13:   2 2020-02-12
14:   2 2020-02-13       top
15:   2 2020-02-14       top
16:   2 2020-02-15       top
17:   2 2020-02-16       top
18:   2 2020-02-17       top
19:   2 2020-02-18       top
20:   2 2020-02-19       top
21:   3 2020-02-10
22:   3 2020-02-11
23:   3 2020-02-12
24:   3 2020-02-13
25:   3 2020-02-14
26:   3 2020-02-15       top
27:   3 2020-02-16       top
28:   3 2020-02-17       hop
29:   3 2020-02-18       hop
30:   3 2020-02-19       hop

This is the same as the output of the for-loop.

Some explanation: the part 1L + (Dates > TARGET & Dates <= max_finish_target_date) + Dates %between% .(ENTRY, max_finish_target_date) creates an index vector of one's, two's and three's of equal length as the number of rows of final_dt; if you put that between square brackets after c("", "top","hop"), for each one you will get an empty string, for each two you will get "top" and for each three you will get "hop".


问:
Usage cytoscape-popper extension in Angular 5
I would like to add the tooltip for my graph, but I have a problem with using popper-extension with cytoscape.js. I can't import this extension, because still I receive an error: "Cannot read property 'use' of undefined" when I try to call "use" function. I installed cytoscape and cytoscape-popper using: npm install cytoscape and npm install cytoscape-popper.

Below is part of my code - it's look like in the https://github.com/cytoscape/cytoscape.js-popper

```<code>import cytoscape from 'cytoscape';
import popper from 'cytoscape-popper';
cytoscape.use( popper );
</code>```

Do you have any ideas, what I do wrong?

答:
I know it's an old thread, but in case somebody encounteres this problem again...

In order to not have compilation errors, use the suggested import structure

```<code>import * as cytoscape from 'cytoscape';
import * as popper from 'cytoscape-popper';
cytoscape.use(popper);
</code>```

Later, use the "array notation" to access the popper function registered with cytoscape (https://github.com/cytoscape/cytoscape.js-popper):

```<code>let popper1 = cy.nodes()[0].['popper']({
  content: () => {
    let div = document.createElement('div');

    div.innerHTML = 'Popper content';

    document.body.appendChild(div);

    return div;
  },
  popper: {} // my popper options here
});
</code>```

Body:
I would like to add the tooltip for my graph, but I have a problem with using popper-extension with cytoscape.js. I can't import this extension, because still I receive an error: "Cannot read property 'use' of undefined" when I try to call "use" function. I installed cytoscape and cytoscape-popper using: npm install cytoscape and npm install cytoscape-popper.

Below is part of my code - it's look like in the https://github.com/cytoscape/cytoscape.js-popper

import cytoscape from 'cytoscape';
import popper from 'cytoscape-popper';
cytoscape.use( popper );

Do you have any ideas, what I do wrong?

Body:
I know it's an old thread, but in case somebody encounteres this problem again...

In order to not have compilation errors, use the suggested import structure

import * as cytoscape from 'cytoscape';
import * as popper from 'cytoscape-popper';
cytoscape.use(popper);

Later, use the "array notation" to access the popper function registered with cytoscape (https://github.com/cytoscape/cytoscape.js-popper):

let popper1 = cy.nodes()[0].['popper']({
  content: () => {
    let div = document.createElement('div');

    div.innerHTML = 'Popper content';

    document.body.appendChild(div);

    return div;
  },
  popper: {} // my popper options here
});


问:
I have two tuple comparison. Almost the same data. Why this error:
```<code>print( ('abc', 1, 2) > ('aaa', 777, 'ssst..') )

print( ('abc', 1, 2) > ('abc', 1, 'ssst..') )
</code>```

Result:

```<code>True

Traceback (most recent call last):
  File "//frserv-bu.playtika.local/users$/constantinio/Documents/Python_course/Sedinta3/ex.py", line 33, in <module>
    print( ('abc', 1, 2) > ('abc', 1, 'ssst..') )
TypeError: '>' not supported between instances of 'int' and 'str'

Process finished with exit code 1
</code>```

答:
Comparisons of tuples proceed element by element, from the left, until a comparison of non-equal values can be made. That is,

```<code>(a, b, c) > (x, y, z)
</code>```

is equivalent to (with some redundant parentheses)

```<code>(a > x) if (a != x) else ((b > y) if (b != y) else (c > z))
</code>```

or in statement form

```<code># result = (a, b, c) > (x, y, z)
if a != x:
    result = a > x
elif b != y:
    result = b > y
else:
    result = c > z
</code>```

In your example, the comparisons a > x and b > y are valid, but c > z is not, since only values of the same type can be ordered. Because comparisons are only made if necessary, the error is only raised when a == x and b == y.

Body:
print( ('abc', 1, 2) > ('aaa', 777, 'ssst..') )

print( ('abc', 1, 2) > ('abc', 1, 'ssst..') )

Result:

True

Traceback (most recent call last):
  File "//frserv-bu.playtika.local/users$/constantinio/Documents/Python_course/Sedinta3/ex.py", line 33, in <module>
    print( ('abc', 1, 2) > ('abc', 1, 'ssst..') )
TypeError: '>' not supported between instances of 'int' and 'str'

Process finished with exit code 1

Body:
Comparisons of tuples proceed element by element, from the left, until a comparison of non-equal values can be made. That is,

(a, b, c) > (x, y, z)

is equivalent to (with some redundant parentheses)

(a > x) if (a != x) else ((b > y) if (b != y) else (c > z))

or in statement form

# result = (a, b, c) > (x, y, z)
if a != x:
    result = a > x
elif b != y:
    result = b > y
else:
    result = c > z

In your example, the comparisons a > x and b > y are valid, but c > z is not, since only values of the same type can be ordered. Because comparisons are only made if necessary, the error is only raised when a == x and b == y.


答:
```<code>return view('posts.index')->with(['posts' => $posts]);
</code>```

Should do the work

Title: Laravel: Undefined variable Posts

Body:
return view('posts.index')->with(['posts' => $posts]);

Should do the work


问:
Convert 2D List to 2D ArrayList in Java
I am trying to convert a 2D List to a 2D ArrayList in Java
I will then convert the 2D ArrayList to a 2D Array and implement for loops to return the absolute difference of the 2 diagonals of the matrix.

How would I convert the 2D ArrayList arr to a 2D ArrayList?

Here is my work so far in attempting to convert the input List to an ArrayList:

```<code>    public static int diagonalDifference(List<List<Integer>> arr) {

    //first: 2D List --> 2D ArrayList
    int[][] a = new int[arr.size()][];
    for (int i=0; i<arr.size(); i++) {
        List<Integer> row = arr.get(i);
        a[i] = row.toArray(new int[row.size()]);

    //second: 2D ArrayList --> int[][]

    //third: nested for loop through int[][]to difference between diagonals of 2d array
    }
</code>```

Here is my full code so far.

```<code> public static int diagonalDifference(List<List<Integer>> arr) {
    List<List<Intger>> arrList = new ArrayList<>();

    int[][] a = new int[arr.size()][];
    for (int i=0; i<arr.size(); i++) {
        List<Integer> row = arr.get(i);
        a[i] = row.toArray(new int[row.size()]);
    }

        int pri = 0;
        int sec =0;

    for(int i=0; i<a.length; i++) {
        for(int j=0; j <a.length; j++) {

            if (a[i] == a[j]) {
                pri += a[i];
            }

            if (i == a.length - j - 1) {
                sec += a[i];
            }

        }
    }
    return Math.abs(pri - sec);

}
</code>```

答:
I think you are looking for :</p>

```<code>public static int[][] diagonalDifference(List<List<Integer>> arr) {
    return arr.stream()
            .map(a -> a.stream().mapToInt(Integer::valueOf).toArray())
            .toArray(int[][]::new);
}
</code>```

Title: Convert 2D List to 2D ArrayList in Java

Body:
I am trying to convert a 2D List to a 2D ArrayList in Java
I will then convert the 2D ArrayList to a 2D Array and implement for loops to return the absolute difference of the 2 diagonals of the matrix.

How would I convert the 2D ArrayList arr to a 2D ArrayList?

Here is my work so far in attempting to convert the input List to an ArrayList:

    public static int diagonalDifference(List<List<Integer>> arr) {

    //first: 2D List --> 2D ArrayList
    int[][] a = new int[arr.size()][];
    for (int i=0; i<arr.size(); i++) {
        List<Integer> row = arr.get(i);
        a[i] = row.toArray(new int[row.size()]);

    //second: 2D ArrayList --> int[][]

    //third: nested for loop through int[][]to difference between diagonals of 2d array
    }

Here is my full code so far.

 public static int diagonalDifference(List<List<Integer>> arr) {
    List<List<Intger>> arrList = new ArrayList<>();

    int[][] a = new int[arr.size()][];
    for (int i=0; i<arr.size(); i++) {
        List<Integer> row = arr.get(i);
        a[i] = row.toArray(new int[row.size()]);
    }

        int pri = 0;
        int sec =0;

    for(int i=0; i<a.length; i++) {
        for(int j=0; j <a.length; j++) {

            if (a[i] == a[j]) {
                pri += a[i];
            }

            if (i == a.length - j - 1) {
                sec += a[i];
            }

        }
    }
    return Math.abs(pri - sec);

}

Body:
I think you are looking for :

public static int[][] diagonalDifference(List<List<Integer>> arr) {
    return arr.stream()
            .map(a -> a.stream().mapToInt(Integer::valueOf).toArray())
            .toArray(int[][]::new);
}


问:
How to retrieve the exact time when IMPORTRANGE updated the data in the google sheets?
In sheet 1, I import data from another spreadsheet - "source" using IMPORTRANGE. The source sheet retrieves data from Google Analytics. The source sheet is updated with new data.  This is also reflected in sheet 1. The new data could have duplicates from the previous data. What I want is to retrieve the unique data comparing it to previous data or in other words, next time importrange updates I need unique links(data) that were not there at previous impotrrange update.

One way of doing it would be to create a backlog of data between the daily stamps and then do a unique on it. but this bombards the spreadsheet with loads of data and since this is a continuous process, the backlog spreadsheet will append to limit in a few weeks.

Is there a script that can catch the importrange update time and perform a unique at it comparing the previous data?

答:
data > source spreadsheet > (via importrange) destination spreadsheet sheet_1 & new data  into destination spreadsheet sheet_2?

If that is what you mean:

```<code>function doSomeThing(){

var ss = SpreadsheetApp.getActiveSpreadsheet();

var sheetOne = ss.getSheetByName("AAA");
var dataOne = sheetOne.getRange(1,1,sheetOne.getMaxRows(),sheetOne.getMaxColumns()).getValues();

var sheetTwo = ss.getSheetByName("BBB");

var colNumberDataToCompare = 5; //for example
var dataToCompare = sheetTwo.getRange(1,colNumberDataToCompare,sheetTwo.getLastRow(),1).map(function(cell){return cell[0]});
var hlpArray = [];

  for(var i=0;i<dataOne.length;i++){

    if(dataToCompare.indexOf(dataOne[i][colNumberDataToCompare]) == -1){

      hlpArray.push([dataOne[i]])

    }

  }
  if(hlpArray[0]){

    sheetTwo.getRange(sheetTwo.getLastRow()+1,1,hlpArray.length,hlpArray[0].length);

  }

}
</code>```

If not, sorry.

Body:
data > source spreadsheet > (via importrange) destination spreadsheet sheet_1 & new data  into destination spreadsheet sheet_2?

If that is what you mean:

function doSomeThing(){

var ss = SpreadsheetApp.getActiveSpreadsheet();

var sheetOne = ss.getSheetByName("AAA");
var dataOne = sheetOne.getRange(1,1,sheetOne.getMaxRows(),sheetOne.getMaxColumns()).getValues();

var sheetTwo = ss.getSheetByName("BBB");

var colNumberDataToCompare = 5; //for example
var dataToCompare = sheetTwo.getRange(1,colNumberDataToCompare,sheetTwo.getLastRow(),1).map(function(cell){return cell[0]});
var hlpArray = [];

  for(var i=0;i<dataOne.length;i++){

    if(dataToCompare.indexOf(dataOne[i][colNumberDataToCompare]) == -1){

      hlpArray.push([dataOne[i]])

    }

  }
  if(hlpArray[0]){

    sheetTwo.getRange(sheetTwo.getLastRow()+1,1,hlpArray.length,hlpArray[0].length);

  }

}

If not, sorry.


问:
Cypher Query in Neo4j to ORDER BY some data
I got a spring application with a query that looks like that.

```<code>MATCH (d:Drug) WHERE toLower(d.tradingName) CONTAINS toLower({0}) OR toLower(d.expire) CONTAINS
toLower({0}) RETURN (d)-[]-() ORDER BY d.expire
</code>```

d.expire is a string in my pojos so the query i posted sorts everyting alphabetical. Thats not what i want.

How is it possible to parse d.expire as a date and order the results as Dates ?

答:
```<code>MATCH (d:Drug)
WHERE toLower(d.tradingName) CONTAINS toLower({0}) OR toLower(d.expire) CONTAINS
toLower({0})
WITH d , datetime(d.expire) as expiryDate
RETURN (d)-[]-() ORDER BY expiryDate
</code>```

Body:
I got a spring application with a query that looks like that.

MATCH (d:Drug) WHERE toLower(d.tradingName) CONTAINS toLower({0}) OR toLower(d.expire) CONTAINS
toLower({0}) RETURN (d)-[]-() ORDER BY d.expire

d.expire is a string in my pojos so the query i posted sorts everyting alphabetical. Thats not what i want.

How is it possible to parse d.expire as a date and order the results as Dates ?


问:
Collapsing rows using two vectors as indicators
This is my first time posting; please let me know if I'm doing any beginner mistakes. In my specific case I have a vector of strings, and I want to collapse some adjacent rows. I have one vector indicating the starting position and one indicating the last element. How can I do this?

Here is some sample code and my approach that does not work:

```<code>text <- c("cat", "dog", "house", "mouse", "street")
x <- c(1,3)
y <- c(2,5)
result <- as.data.frame(paste(text[x:y],sep = " ",collapse = ""))
</code>```

In case it's not clear, the result I want is a data frame consisting of two strings: "cat dog" and "house mouse street".

答:
Not sure this is the best option, but it does the job,</p>

```<code>sapply(mapply(seq, x, y), function(i)paste(text[i], collapse = ' '))
#[1] "cat dog"            "house mouse street"
</code>```

Body:
This is my first time posting; please let me know if I'm doing any beginner mistakes. In my specific case I have a vector of strings, and I want to collapse some adjacent rows. I have one vector indicating the starting position and one indicating the last element. How can I do this?

Here is some sample code and my approach that does not work:

text <- c("cat", "dog", "house", "mouse", "street")
x <- c(1,3)
y <- c(2,5)
result <- as.data.frame(paste(text[x:y],sep = " ",collapse = ""))

In case it's not clear, the result I want is a data frame consisting of two strings: "cat dog" and "house mouse street".

Body:
Not sure this is the best option, but it does the job,

sapply(mapply(seq, x, y), function(i)paste(text[i], collapse = ' '))
#[1] "cat dog"            "house mouse street"


问:
I am getting IMEI null in Android Q?
I am getting the IMEI ID null from the telephonymanager. What to do?

is there any workaround for that?

答:
If you needed, you can try to install a work profile in to the mobile phone and include your app in the same package or vice versa.

I tried and it works, it's simple if yo follow this repo: https://github.com/googlesamples/android-testdpc

When you install the Work Profile your app is installed in this profile and you will have acces to the IMEI.

And now there is another example fixed yesterday to Android 10:
https://github.com/android/enterprise-samples/pull/29

Title: I am getting IMEI null in Android Q?


问:
Rename files to lowercase in Powershell
I am trying to rename a bunch of files recursively using Powershell 2.0. The directory structure looks like this:

```<code>Leaflets
+ HTML
  - File1
  - File2
  ...
+ HTMLICONS
  + IMAGES
    - Image1
    - Image2
  - File1
  - File2
  ...
+ RTF
  - File1
  - File2
  ...
+ SGML
  - File1
  - File2
  ...
</code>```

I am using the following command:

```<code>get-childitem Leaflets -recurse | rename -newname { $_.name.ToLower() }
</code>```

and it seems to rename the files, but complains about the subdirectories:

```<code>Rename-Item : Source and destination path must be different.
</code>```

I reload the data monthly using robocopy, but the directories do not change, so I can rename them by hand. Is there any way to get get-children to skip the subdirectories (like find Leaflets -type f ...)?

Thanks.

UPDATE: It appears that the problem is with files that are already all lower case. I tried changing the command to:

```<code>get-childitem Leaflets -recurse | if ($_.name -ne $_name.ToLower()) rename -newname { $_.name.ToLower() }
</code>```

but now Powershell complains that if is not a cmdlet, function, etc.
Can I pipe the output of get-childitem to an if statement?

UPDATE 2: This works:

```<code>$files=get-childitem Leaflets -recurse
foreach ($file in $files)
{
    if ($file.name -ne $file.name.ToLower())
    {
        rename -newname { $_.name.ToLower() }
    }
}
</code>```

答:
A small but important correction to the answer from Jay Bazuzi. The -cne (case sensitive not equal) operator must be used if the where-part should return anything.

Additionally I found that the Path parameter needed to be present. This version worked in my setup:

```<code>gci -Recurse |
    ? { $_.Name -cne $_.Name.ToLower() } |
    % { ren $_.Name -NewName $_.Name.Tolower()  }
</code>```

ContentLicense: CC BY-SA 2.5

Title: Rename files to lowercase in Powershell

Body:
I am trying to rename a bunch of files recursively using Powershell 2.0. The directory structure looks like this:

Leaflets
+ HTML
  - File1
  - File2
  ...
+ HTMLICONS
  + IMAGES
    - Image1
    - Image2
  - File1
  - File2
  ...
+ RTF
  - File1
  - File2
  ...
+ SGML
  - File1
  - File2
  ...

I am using the following command:

get-childitem Leaflets -recurse | rename -newname { $_.name.ToLower() }

and it seems to rename the files, but complains about the subdirectories:

Rename-Item : Source and destination path must be different.

I reload the data monthly using robocopy, but the directories do not change, so I can rename them by hand. Is there any way to get get-children to skip the subdirectories (like find Leaflets -type f ...)?

Thanks.

UPDATE: It appears that the problem is with files that are already all lower case. I tried changing the command to:

get-childitem Leaflets -recurse | if ($_.name -ne $_name.ToLower()) rename -newname { $_.name.ToLower() }

but now Powershell complains that if is not a cmdlet, function, etc.
Can I pipe the output of get-childitem to an if statement?

UPDATE 2: This works:

$files=get-childitem Leaflets -recurse
foreach ($file in $files)
{
    if ($file.name -ne $file.name.ToLower())
    {
        rename -newname { $_.name.ToLower() }
    }
}

Body:
A small but important correction to the answer from Jay Bazuzi. The -cne (case sensitive not equal) operator must be used if the where-part should return anything.

Additionally I found that the Path parameter needed to be present. This version worked in my setup:

gci -Recurse |
    ? { $_.Name -cne $_.Name.ToLower() } |
    % { ren $_.Name -NewName $_.Name.Tolower()  }


问:
How to use cron with mutt to schedule a basic email?
I am new to both mutt and cron.  It seems that mutt and cron are both working but I can't get them to work together.

I have the following in my crontab however I am not receiving an email from it:

```<code>* * * * *  echo "message body" | mutt -s "Test Email" email@email.com >/dev/null 2>&1
</code>```

From the terminal I am able to use mutt to send an email using the following command:

```<code>echo "message body" | mutt -s "Test Email" email@email.com >/dev/null 2>&1
</code>```

I can get cron to append text to a file by having the following in my crontab:

```<code>* * * * * echo "some text" >> /Users/me/Desktop/stuff.txt
</code>```

EDIT:
At the top of the crontab I have put MAILTO="email@email.com"
Now each time the cron job runs I get an email from the Cron Daemon which reads:

/bin/sh: mutt: command not found

答:
The path value needed to be set in the crontab:</p>

```<code>PATH="/usr/local/bin"
</code>```

Body:
I am new to both mutt and cron.  It seems that mutt and cron are both working but I can't get them to work together.

I have the following in my crontab however I am not receiving an email from it:

* * * * *  echo "message body" | mutt -s "Test Email" email@email.com >/dev/null 2>&1

From the terminal I am able to use mutt to send an email using the following command:

echo "message body" | mutt -s "Test Email" email@email.com >/dev/null 2>&1

I can get cron to append text to a file by having the following in my crontab:

* * * * * echo "some text" >> /Users/me/Desktop/stuff.txt

EDIT:
At the top of the crontab I have put MAILTO="email@email.com"
Now each time the cron job runs I get an email from the Cron Daemon which reads:

/bin/sh: mutt: command not found

Body:
The path value needed to be set in the crontab:

PATH="/usr/local/bin"


问:
Using replace and pathArray[0], I seem to be adding rather than replacing with my JavaScript
I have made a simple browser extension and have a manifest.json file that runs through a background.js file into my JavaScript file, which has this code

var l=location;
var str2='/edit';

var pathArray = l.pathname.split('/');
var secondLevelLocation = pathArray[1];

pathArray[1] = 'node';

l.href=l.origin.replace(l.origin, pathArray[1])+l.pathname.concat(str2);```

But rather than replacing pathArray[1], it's adding to the url.

For example, the script is taking: https://mywebiste.com/items/1234;
and replacing with: https://mywebiste.com/items/node/items/1234/edit

However, the intended output is: https://mywebiste.com/node/1234/edit

Updated

Following comments on incorrect array number, I've updated my script but naturally it doesn't fix the issue.

答:
So, if you have your url like this: https://mywebiste.com/items/1234 and you split it by /, then you will have something like this: ["https:", "", "mywebiste.com", "items", "1234"]

as you see, the 3rd position is the items that you need, so you can do:

yourUrl.replace(yourUrl.split('/')[3], 'node').concat('/edit');

Feel free to use 'node' and '/edit' as variables as you did.

Hope it helps you.

EDIT:

The easiest way I can think:

let href = location.origin + location.pathname.replace('items', 'node').concat('/edit')

Body:
I have made a simple browser extension and have a manifest.json file that runs through a background.js file into my JavaScript file, which has this code

var l=location;
var str2='/edit';

var pathArray = l.pathname.split('/');
var secondLevelLocation = pathArray[1];

pathArray[1] = 'node';

l.href=l.origin.replace(l.origin, pathArray[1])+l.pathname.concat(str2);

But rather than replacing pathArray[1], it's adding to the url.

For example, the script is taking: https://mywebiste.com/items/1234;
and replacing with: https://mywebiste.com/items/node/items/1234/edit

However, the intended output is: https://mywebiste.com/node/1234/edit

Updated

Following comments on incorrect array number, I've updated my script but naturally it doesn't fix the issue.


答:
Either use base R with

```<code>mapply(function(.x,.y) paste(text[.x:.y],collapse = " "), x, y)
</code>```

or use the purrr package as

```<code>map2_chr(x,y, ~ paste(text[.x:.y],collapse = " "))
</code>```

Both yield

```<code># [1] "cat dog"            "house mouse street"
</code>```

The output as a data frame depends on the structure you want: rows or columns

Title: Collapsing rows using two vectors as indicators

Body:
Either use base R with

mapply(function(.x,.y) paste(text[.x:.y],collapse = " "), x, y)

or use the purrr package as

map2_chr(x,y, ~ paste(text[.x:.y],collapse = " "))

Both yield

# [1] "cat dog"            "house mouse street"

The output as a data frame depends on the structure you want: rows or columns


问:
Adding NSMutableArray A to NSMutableArray B, and then doing "removeAllObjects" on A, clears B too?
```<code>A = bookmarkArray
B = issueArray
[issueArray addObject:bookmarkArray];
[bookmarkArray removeAllObjects];
</code>```

Why does this leave issueArray empty, and what can I do to make sure I still have issueArray populated when bookmarkArray is cleared?

答:
Explanations from Tommy and taskinoor are right on the money. However, if your goal is for issueArray to contain the objects that are in bookmarkArray, do this:

```<code>[issueArray addObjectsFromArray:bookmarkArray];
[bookmarkArray removeAllObjects];
</code>```

Make sure you're clear on the difference. In taskinoor's code, you're adding one object to bookmarkArray, and that object is itself an array. In the lines above, you're adding [bookmarkArray count] objects to issueArray.

Body:
A = bookmarkArray
B = issueArray
[issueArray addObject:bookmarkArray];
[bookmarkArray removeAllObjects];

Why does this leave issueArray empty, and what can I do to make sure I still have issueArray populated when bookmarkArray is cleared?

Body:
Explanations from Tommy and taskinoor are right on the money. However, if your goal is for issueArray to contain the objects that are in bookmarkArray, do this:

[issueArray addObjectsFromArray:bookmarkArray];
[bookmarkArray removeAllObjects];

Make sure you're clear on the difference. In taskinoor's code, you're adding one object to bookmarkArray, and that object is itself an array. In the lines above, you're adding [bookmarkArray count] objects to issueArray.


问:
Pandas - Add columns based on grouping of other columns
I want to add three additional columns using pandas and python. I'm not sure how to add additional columns based on rows who have the same GroupID value.

min_avg: Which is the lowest avg value for rows with the same GroupID

max_avg: Which is the highest avg value for rows with the same GroupID

group_avg: Which is the avg value for each rows 'min_avg, max_avg' columns

I'm not entirely sure where to begin with this one.

I have this:

```<code>    avg     groupId
0   25.5    1016
1   26.7    1048
2   25.8    1016
3   53.5    1048
4   29.3    1064
5   27.7    1016
</code>```

and my goal is this:

```<code>    avg         groupId     min_avg     max_avg     group_average
0   25.5        1016        25.5        27.7        26.6
1   26.7        1048        26.3        53.5        39.9
2   25.8        1016        25.5        27.7        26.6
3   53.5        1048        26.3        53.5        39.9
4   29.3        1064        29.3        29.3        29.3
5   27.7        1016        25.5        27.7        26.6
</code>```

Body:
I want to add three additional columns using pandas and python. I'm not sure how to add additional columns based on rows who have the same GroupID value.

min_avg: Which is the lowest avg value for rows with the same GroupID

max_avg: Which is the highest avg value for rows with the same GroupID

group_avg: Which is the avg value for each rows 'min_avg, max_avg' columns

I'm not entirely sure where to begin with this one.

I have this:

    avg     groupId
0   25.5    1016
1   26.7    1048
2   25.8    1016
3   53.5    1048
4   29.3    1064
5   27.7    1016

and my goal is this:

    avg         groupId     min_avg     max_avg     group_average
0   25.5        1016        25.5        27.7        26.6
1   26.7        1048        26.3        53.5        39.9
2   25.8        1016        25.5        27.7        26.6
3   53.5        1048        26.3        53.5        39.9
4   29.3        1064        29.3        29.3        29.3
5   27.7        1016        25.5        27.7        26.6

Body:
We can do merge with groupby describe

df=df.merge(df.groupby('groupId').avg.describe()[['mean','min','max']].reset_index(),how='left')
Out[25]:
    avg  groupId       mean   min   max
0  25.5     1016  26.333333  25.5  27.7
1  26.7     1048  40.100000  26.7  53.5
2  25.8     1016  26.333333  25.5  27.7
3  53.5     1048  40.100000  26.7  53.5
4  29.3     1064  29.300000  29.3  29.3
5  27.7     1016  26.333333  25.5  27.7


问:
Sort list by one item and identify record that meets a condition in Netlogo
I have a list of sublists, something like the following

[[0 “coal” 500 1430] [0 “gas” 300 1300] [1 “coal” 600 1500] [1 “gas” 700 1400]]

I would like to do four things:

1. Sort the main list by item 3 of sublists

2. Cumulatively sum item 2 of sublists until a certain value is reached.

3. Identify item 3 of the last list added.

4. Then I’d like to identify items 0 and 1 of lists that were added to the loop in point 2 and ask those turtles to do something.

I've been exploring tables, lists, etc but struggling with this complex bit of code. Can people suggest how they would code this?

Thanks in advance for the help!

答:
The following seems to answer the case, I think...though there may be more elegant ways</p>

```<code>to go
  create-turtles 2
  let l [[0 "coal" 500 1430] [0 "gas" 300 1300] [1 "coal" 600 1500] [1 "gas" 700 1400]]
  ;sort the list by item 2
  let sorted sort-by bigger l
  show sorted
  ;accumulate item 3 until limit reached
  let k 0
  let n 0
  let limit 2800
  let turtleNos []
  let fuels []
  while [k < limit]
  [
    set k k + item 3 ( item n sorted )
    ;accumulate item 0 and 1
    set turtleNos lput item 0 ( item n sorted ) turtleNos
    set fuels lput item 1 ( item n sorted ) fuels
    set n n + 1
  ]
  show k
  ;show item 3 for the last item added to k
  show item 3 (item ( n - 1 ) sorted)
  ;accumulated lists - note non-unique
  show turtleNos
  show fuels
  (foreach turtleNos fuels
      [ [x y] -> ask turtle x [show y] ])

end
to-report bigger [l1 l2]
  report item 2 l1 > item 2 l2
end
</code>```

Body:
The following seems to answer the case, I think...though there may be more elegant ways

to go
  create-turtles 2
  let l [[0 "coal" 500 1430] [0 "gas" 300 1300] [1 "coal" 600 1500] [1 "gas" 700 1400]]
  ;sort the list by item 2
  let sorted sort-by bigger l
  show sorted
  ;accumulate item 3 until limit reached
  let k 0
  let n 0
  let limit 2800
  let turtleNos []
  let fuels []
  while [k < limit]
  [
    set k k + item 3 ( item n sorted )
    ;accumulate item 0 and 1
    set turtleNos lput item 0 ( item n sorted ) turtleNos
    set fuels lput item 1 ( item n sorted ) fuels
    set n n + 1
  ]
  show k
  ;show item 3 for the last item added to k
  show item 3 (item ( n - 1 ) sorted)
  ;accumulated lists - note non-unique
  show turtleNos
  show fuels
  (foreach turtleNos fuels
      [ [x y] -> ask turtle x [show y] ])

end
to-report bigger [l1 l2]
  report item 2 l1 > item 2 l2
end


问:
PHP add missing key in loop
I have the following array.

```<code>    [rows] => Array
            (
                [0] => Array
                    (
                        [id] => 2704783858001796
                        [rowNumber] => 1
                        [expanded] => 1
                        [createdAt] => 2020-02-18T18:42:54Z
                        [modifiedAt] => 2020-02-18T22:07:36Z
                        [cells] => Array
                            (
                                    [0] => Array
                                        (
                                            [columnId] => 1676391784703876
                                            [value] => Approved
                                            [displayValue] => Approved
                                        )

                                    [1] => Array
                                        (
                                            [columnId] => 1225963934640004
                                            [value] => Submitted
                                            [displayValue] => Submitted
                                        )

                                    [2] => Array
                                        (
                                            [columnId] => 4979307467564932
                                            [value] => 2020-02-18
                                        )
                                    [3] => Array
                                        (
                                            [columnId] => 3203730339325828
</code>```

Where [value] and [displayValue] are not always shown.  When I loop through the array, I need to be able to insert a [value] as blank or 0.  I cannot have the loop skip over the key.

```<code>$j = count($dataID['rows']);
for ($i = 0; $i < $j; $i++) {
    array_push($dataRows, array_column($dataID['rows'][$i]['cells'], 'value'));
}
</code>```

答:
I never recommend trying to modify a data structure while you are walking through it.  Instead, "walk through it, building some kind of list of the changes you need to make."  Then, after the walk is finished, go back and apply the changes.

Alternatively, each time you make a change, restart the walk.

Title: PHP add missing key in loop

Body:
I have the following array.

    [rows] => Array
            (
                [0] => Array
                    (
                        [id] => 2704783858001796
                        [rowNumber] => 1
                        [expanded] => 1
                        [createdAt] => 2020-02-18T18:42:54Z
                        [modifiedAt] => 2020-02-18T22:07:36Z
                        [cells] => Array
                            (
                                    [0] => Array
                                        (
                                            [columnId] => 1676391784703876
                                            [value] => Approved
                                            [displayValue] => Approved
                                        )

                                    [1] => Array
                                        (
                                            [columnId] => 1225963934640004
                                            [value] => Submitted
                                            [displayValue] => Submitted
                                        )

                                    [2] => Array
                                        (
                                            [columnId] => 4979307467564932
                                            [value] => 2020-02-18
                                        )
                                    [3] => Array
                                        (
                                            [columnId] => 3203730339325828

Where [value] and [displayValue] are not always shown.  When I loop through the array, I need to be able to insert a [value] as blank or 0.  I cannot have the loop skip over the key.

$j = count($dataID['rows']);
for ($i = 0; $i < $j; $i++) {
    array_push($dataRows, array_column($dataID['rows'][$i]['cells'], 'value'));
}


问:
iphone to ipad, iphone 4 uialertview problems
So I've upgraded the code to the ipad (i.e. converted to a universal app). However, the UIAlertview rendering seems to be off for IOS4. Instead of being positioned in the middle, it jumps up and is displayed on top, with half the box cut off. Same goes for landscape orientation.

It is my understanding that the UIalertview is always set in the middle? I looked through the code and I did not set up the frame/position anywhere in the code. This only happens for 4.0, on both the iphone 4 and the itouch running 4.0. Every other version is fine, including the ipad. Any thoughts?

Thanks.

答:
Does your alert have any Textfields added ?

Because in 4.0+ iOS scrolls the alertview to visible part if you have a textfield in the alertview.