问:
Entity Framework creates non-existing column in query
I face the problem that EF creates a column in the query that does not exist in the Oracle database table.

The simplified model which is created by EF looks like this (I use DB first approach):

```<code>public partial class USER
{
    public int ID { get; set; }
    public string NAME { get; set; }
    public int PROCESS_ID { get; set; }

    public virtual PROCESS PROCESS { get; set; }
}

public partial class PROCESS
{
    public PROCESS()
    {
        this.USER = new HashSet<User>();
    }

    public int ID { get; set; }

    public virtual ICollection<USER> USER { get; set; }
}
</code>```

I set up the foreign key constraint in the oracle sql developer.

When I try to get the Users for a selected Process like this:

```<code>var users = context.Users.Where(u => u.PROCESS_ID == 0);
</code>```

It produces following error:

```<code>ORA-00904: "Extent1"."R1": invalid ID
</code>```

So i took a look on the produced SQL:

```<code>SELECT
"Extent1".ID,
"Extent1".NAME,
"Extent1".R1,
FROM DB.USER "Extent1"
WHERE "Extent1".R1 = :p__linq__0
</code>```

Of course this produces an error because R1 isn't a column in the table. But I can't figure out where it comes from. It seems like EF can't map the foreign key properly thats why it's also missing in the generated SQL query?

Maybe someone has a tip for me :)

答: Encountered the same error recently while working with Oracle using DevArt provider. Turned out it was caused by a column name being longer than 30 chars. OP mentioned that the model posted in his question is a simplified one so it still may be the case.</p>

Body:
I face the problem that EF creates a column in the query that does not exist in the Oracle database table.

The simplified model which is created by EF looks like this (I use DB first approach):

public partial class USER
{
    public int ID { get; set; }
    public string NAME { get; set; }
    public int PROCESS_ID { get; set; }

    public virtual PROCESS PROCESS { get; set; }
}

public partial class PROCESS
{
    public PROCESS()
    {
        this.USER = new HashSet<User>();
    }

    public int ID { get; set; }

    public virtual ICollection<USER> USER { get; set; }
}

I set up the foreign key constraint in the oracle sql developer.

When I try to get the Users for a selected Process like this:

var users = context.Users.Where(u => u.PROCESS_ID == 0);

It produces following error:

ORA-00904: "Extent1"."R1": invalid ID

So i took a look on the produced SQL:

SELECT
"Extent1".ID,
"Extent1".NAME,
"Extent1".R1,
FROM DB.USER "Extent1"
WHERE "Extent1".R1 = :p__linq__0

Of course this produces an error because R1 isn't a column in the table. But I can't figure out where it comes from. It seems like EF can't map the foreign key properly thats why it's also missing in the generated SQL query?

Maybe someone has a tip for me :)


来源: stackexchange

问:
Why do we usually use || over |? What is the difference?
I'm just wondering why we usually use logical OR || between two booleans not bitwise OR |, though they are both working well.

I mean, look at the following:

```<code>if(true  | true)  // pass
if(true  | false) // pass
if(false | true)  // pass
if(false | false) // no pass
</code>```

```<code>if(true  || true)  // pass
if(true  || false) // pass
if(false || true)  // pass
if(false || false) // no pass
</code>```

Can we use | instead of ||? Same thing with & and &&.

答:
If you use the || and && forms, rather than the | and & forms of these operators, Java will not bother to evaluate the right-hand operand alone.

It's a matter of if you want to short-circuit the evaluation or not -- most of the time you want to.

A good way to illustrate the benefits of short-circuiting would be to consider the following example.

```<code>Boolean b = true;
if(b || foo.timeConsumingCall())
{
   //we entered without calling timeConsumingCall()
}
</code>```

Another benefit, as Jeremy and Peter mentioned, for short-circuiting is the null reference check:

```<code>if(string != null && string.isEmpty())
{
    //we check for string being null before calling isEmpty()
}
</code>```

more info

ContentLicense: CC BY-SA 4.0

Body:
I'm just wondering why we usually use logical OR || between two booleans not bitwise OR |, though they are both working well.

I mean, look at the following:

if(true  | true)  // pass
if(true  | false) // pass
if(false | true)  // pass
if(false | false) // no pass

if(true  || true)  // pass
if(true  || false) // pass
if(false || true)  // pass
if(false || false) // no pass

Can we use | instead of ||? Same thing with & and &&.

Body:
If you use the || and && forms, rather than the | and & forms of these operators, Java will not bother to evaluate the right-hand operand alone.

It's a matter of if you want to short-circuit the evaluation or not -- most of the time you want to.

A good way to illustrate the benefits of short-circuiting would be to consider the following example.

Boolean b = true;
if(b || foo.timeConsumingCall())
{
   //we entered without calling timeConsumingCall()
}

Another benefit, as Jeremy and Peter mentioned, for short-circuiting is the null reference check:

if(string != null && string.isEmpty())
{
    //we check for string being null before calling isEmpty()
}

more info

ContentLicense: CC BY-SA 3.0


问:
How can I include a body while sending a POST request using HTTP AT commands with a SIM7000A module and an Arduino?
I'm crossposting this from where I posted it on the Arduino forum in hopes that maybe someone here has an answer.  I am working on a project that involves sending POST requests to a Twilio function using an Arduino Uno and a SIMCOM SIM7000A breakout board using AT commands.  So far with the Uno, I can only POST an empty request that contains headers but no body.  The following code is a test sketch where I am POSTing to a RequestBin repository.

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

unsigned char data = 0;
AltSoftSerial SIM7000;
char incomingChar;

void setup() {

  Serial.begin(9600);
  SIM7000.begin(19200);

  // put your setup code here, to run once:
  SIM7000.print("AT+CMGF=1\r");  //put in text mode
  delay(100);
  SIM7000.print("AT+CGDCONT=1\"IP\",\"super\"\r"); //create profile.  "super" is APN for twilio super sim
  delay(1000);
  SIM7000.print("AT+COPS=1,2,\"310410\"\r"); //log on to AT&T network
  delay(5000);
  SIM7000.print("AT+SAPBR=3,1,\"APN\",\"super\"\r"); //create SAPBR profile.  same APN.
  delay(300);
  SIM7000.print("AT+SAPBR=1,1\r");
  delay(2000);
  Serial.println("Setup complete.  Module should be online and fast-blinking\n from successful SAPBR profile setup.\n Entering loop.  Send \"CHECK\" to test POST");
}

void loop() {

  SIM7000.print("AT+CMGL\r");

  if (SIM7000.available() > 0) {
    incomingChar = SIM7000.read();
    if (incomingChar == 'C') {
      delay(10);
      Serial.print(incomingChar);
      incomingChar = SIM7000.read();
      if (incomingChar == 'H') {
        delay(10);
        Serial.print(incomingChar);
        incomingChar = SIM7000.read();
        if (incomingChar == 'E') {
          delay(10);
          Serial.print(incomingChar);
          incomingChar = SIM7000.read();
          if (incomingChar == 'C') {
            delay(10);
            Serial.print(incomingChar);
            incomingChar = SIM7000.read();
            if (incomingChar == 'K') {
              delay(10);
              Serial.print(incomingChar);
              incomingChar = "";
              Serial.println(F("\nGOOD CHECK"));
              Serial.println(F("SENDING POST REQUEST NOW")) ;
              sendText();
              Serial.println("POST SENT");
              return;
            }
          }
        }
      }
    }
  }
  incomingChar = "";
  return;
}

void sendText()
{

  SIM7000.print("AT+HTTPINIT\r");
  delay(1000);
  getResponse();
  SIM7000.print("AT+HTTPPARA=\"CID\",1\r");
  delay(1000);
  getResponse();
  SIM7000.print("AT+HTTPPARA=\"URL\",\"http://engt62k9mgbgo.x.pipedream.net\"\r");
  delay(1000);
  getResponse();
  SIM7000.print("AT+HTTPPARA=\"CONTENT\",\"text/plain\"\r");
  delay(1000);
  getResponse();
  SIM7000.print("AT+HTTPDATA=100,5000\r\n");
  delay(100);
  getResponse();
  SIM7000.print("\"TEST MESSAGE\"\r\n");
  SIM7000.print("\r\n");
  delay(5000);
  getResponse();
  SIM7000.print("AT+HTTPACTION=1\r");
  delay(1000);
  getResponse();
  SIM7000.print("AT+HTTPTERM\r");
  getResponse();
}

void getResponse()
{
  if (SIM7000.available())
  {
    while (SIM7000.available())
    {
      data = SIM7000.read();
      Serial.write(data);
    }
    data = 0;
  }
}
//NOV 3 2020, note: need to include AT command AT+CMGD=0,4 for routinely deleting messages
//message storage limited and not automatically overwritten
</code>```

I've included the output on the Serial monitor below.

Output on Serial Monitor

I'm thinking that the problem lies between

```<code>SIM7000.print("AT+HTTPDATA=100,5000\r\n");
</code>```

and

```<code>SIM7000.print("AT+HTTPACTION=1\r");
</code>```

You can see on the output where it prompts for DOWNLOAD, but the "TEST MESSAGE" that I try to insert here doesn't go.  I've also attached a screenshot of the RequestBin output to show that it's showing up as an empty POST with nothing but headers and a content length of 0.  Output in RequestBin

When I've done similar POST requests using the same SIM7000A module with the same AT commands on PuTTY via USB, all I have to do is enter my text during the time specified in the AT+HTTPDATA command and hit enter.  Whatever I enter during that time as it says "DOWNLOAD" shows up as the body of my POST.  But I have as of yet been unable to do the same using the Uno.
Any help you can offer is much appreciated.

答:
First of all, you must to send CR NL char after all AT commands...

SIM7000.print("AT+HTTPDATA=100,5000\r\n");

Note: \r and \n = CR and NL respectively.

Second, try the steps below:

// SEND HTTP PROCESS
  SIM7000.println("AT+HTTPINIT\r\n");
  delay(1500);
  Serial.println(SIM7000.readString());
  SIM7000.println("AT+HTTPPARA=\"CID\",1\r\n");
  delay(1500);
  Serial.println(SIM7000.readString());
  char httpSend[105] = "[URL]";
  SIM7000.println(httpSend + String("\r\n"));
  delay(1500);
  Serial.println(SIM7000.readString());
  SIM7000.println("AT+HTTPSSL=1\r\n"); // THIS LINE FOR SSL URL
  delay(1500);
  Serial.println(SIM7000.readString());
  SIM7000.println("AT+HTTPACTION=0\r\n"); //GET REQUEST = 0 | POST REQUEST = 1
  delay(7000);
  Serial.println(SIM7000.readString());
  SIM7000.println("AT+HTTPREAD\r\n");
  delay(1500);
  Serial.println(SIM7000.readString());
  SIM7000.println("AT+HTTPTERM\r\n");
  delay(1500);
  Serial.println(SIM7000.readString());
```

Body:
I'm crossposting this from where I posted it on the Arduino forum in hopes that maybe someone here has an answer.  I am working on a project that involves sending POST requests to a Twilio function using an Arduino Uno and a SIMCOM SIM7000A breakout board using AT commands.  So far with the Uno, I can only POST an empty request that contains headers but no body.  The following code is a test sketch where I am POSTing to a RequestBin repository.

#include <AltSoftSerial.h>

unsigned char data = 0;
AltSoftSerial SIM7000;
char incomingChar;

void setup() {

  Serial.begin(9600);
  SIM7000.begin(19200);

  // put your setup code here, to run once:
  SIM7000.print("AT+CMGF=1\r");  //put in text mode
  delay(100);
  SIM7000.print("AT+CGDCONT=1\"IP\",\"super\"\r"); //create profile.  "super" is APN for twilio super sim
  delay(1000);
  SIM7000.print("AT+COPS=1,2,\"310410\"\r"); //log on to AT&T network
  delay(5000);
  SIM7000.print("AT+SAPBR=3,1,\"APN\",\"super\"\r"); //create SAPBR profile.  same APN.
  delay(300);
  SIM7000.print("AT+SAPBR=1,1\r");
  delay(2000);
  Serial.println("Setup complete.  Module should be online and fast-blinking\n from successful SAPBR profile setup.\n Entering loop.  Send \"CHECK\" to test POST");
}

void loop() {

  SIM7000.print("AT+CMGL\r");

  if (SIM7000.available() > 0) {
    incomingChar = SIM7000.read();
    if (incomingChar == 'C') {
      delay(10);
      Serial.print(incomingChar);
      incomingChar = SIM7000.read();
      if (incomingChar == 'H') {
        delay(10);
        Serial.print(incomingChar);
        incomingChar = SIM7000.read();
        if (incomingChar == 'E') {
          delay(10);
          Serial.print(incomingChar);
          incomingChar = SIM7000.read();
          if (incomingChar == 'C') {
            delay(10);
            Serial.print(incomingChar);
            incomingChar = SIM7000.read();
            if (incomingChar == 'K') {
              delay(10);
              Serial.print(incomingChar);
              incomingChar = "";
              Serial.println(F("\nGOOD CHECK"));
              Serial.println(F("SENDING POST REQUEST NOW")) ;
              sendText();
              Serial.println("POST SENT");
              return;
            }
          }
        }
      }
    }
  }
  incomingChar = "";
  return;
}

void sendText()
{

  SIM7000.print("AT+HTTPINIT\r");
  delay(1000);
  getResponse();
  SIM7000.print("AT+HTTPPARA=\"CID\",1\r");
  delay(1000);
  getResponse();
  SIM7000.print("AT+HTTPPARA=\"URL\",\"http://engt62k9mgbgo.x.pipedream.net\"\r");
  delay(1000);
  getResponse();
  SIM7000.print("AT+HTTPPARA=\"CONTENT\",\"text/plain\"\r");
  delay(1000);
  getResponse();
  SIM7000.print("AT+HTTPDATA=100,5000\r\n");
  delay(100);
  getResponse();
  SIM7000.print("\"TEST MESSAGE\"\r\n");
  SIM7000.print("\r\n");
  delay(5000);
  getResponse();
  SIM7000.print("AT+HTTPACTION=1\r");
  delay(1000);
  getResponse();
  SIM7000.print("AT+HTTPTERM\r");
  getResponse();
}

void getResponse()
{
  if (SIM7000.available())
  {
    while (SIM7000.available())
    {
      data = SIM7000.read();
      Serial.write(data);
    }
    data = 0;
  }
}
//NOV 3 2020, note: need to include AT command AT+CMGD=0,4 for routinely deleting messages
//message storage limited and not automatically overwritten

I've included the output on the Serial monitor below.

Output on Serial Monitor

I'm thinking that the problem lies between

SIM7000.print("AT+HTTPDATA=100,5000\r\n");

and

SIM7000.print("AT+HTTPACTION=1\r");

You can see on the output where it prompts for DOWNLOAD, but the "TEST MESSAGE" that I try to insert here doesn't go.  I've also attached a screenshot of the RequestBin output to show that it's showing up as an empty POST with nothing but headers and a content length of 0.  Output in RequestBin

When I've done similar POST requests using the same SIM7000A module with the same AT commands on PuTTY via USB, all I have to do is enter my text during the time specified in the AT+HTTPDATA command and hit enter.  Whatever I enter during that time as it says "DOWNLOAD" shows up as the body of my POST.  But I have as of yet been unable to do the same using the Uno.
Any help you can offer is much appreciated.


问:
use nodejs var as json object statement?
how do I use a nodejs var inside a json statement, I dont realy have the required vocabulary to explain but here is my simplifyed code:

test.json:

```<code>{
"test1":["test1.1", "test1.2"],
"test2":["test2.1", "test2.2"]
}
</code>```

test.js:

```<code>const json = require("./test.json")
function myFunction(TYPE){
return(json.TYPE[0])
}
console.log(myFunction("test1"))
</code>```

as I use the "type" var it tries to uses it as an json statement or object but obviously there is no "type" there only is "test1" and "test2" but it interprets as "type" instead

答:
Brackets to access the variable key should work

function myFunction(TYPE){
return(json[TYPE][0])
}
```

Body:
how do I use a nodejs var inside a json statement, I dont realy have the required vocabulary to explain but here is my simplifyed code:

test.json:

{
"test1":["test1.1", "test1.2"],
"test2":["test2.1", "test2.2"]
}

test.js:

const json = require("./test.json")
function myFunction(TYPE){
return(json.TYPE[0])
}
console.log(myFunction("test1"))

as I use the "type" var it tries to uses it as an json statement or object but obviously there is no "type" there only is "test1" and "test2" but it interprets as "type" instead


问:
How can I fill a column with values that are computed between two dates in pandas, with a delay of one row, respecting certain conditions?
I have the following DataFrame:

Date
Distance
Position
TrainerID

2017-09-03
1000
2
6529

2017-09-03
1600
4
6529

2017-09-03
1200
3
6529

2017-09-06
1200
13
6529

2017-09-08
1000
1
6529

2017-09-10
1600
9
6529

2017-09-15
1600
2
6529

I want to compute on every row the winning percentage so far for the sprint races (distance of 1200 meters or less) in the last 1000 days, grouped by TrainerID. The result will be stored in a Win% Column. Dates need not to be unique. However, the winning % is considered to be before the race happened, so the current row is excluded. Thus, the results are delayed by one row.

The rows of the races that do not fit this category, should have the winning percentage from above.

What I am looking for is a result like this:

Date
Distance
Position
TrainerID
Win %

2017-09-03
1000
2
6529
0 (0 wins, 0 races)

2017-09-03
1600
4
6529
0 (does not fit the criteria, value copied from above)

2017-09-03
1200
3
6529
0 (0 wins, 1 race)

2017-09-06
1200
13
6529
0 (0 wins, 2 races)

2017-09-08
1000
1
6529
0 (0 wins, 3 races)

2017-09-10
1600
9
6529
25 (1 win, 4 races)

2017-09-15
1600
2
6529
25 (does not fit the criteria, value copied from above)

For this, I know I am going to need a mask to select the data that fits and, of course, the selecting code. What I have so far is this:

```<code>mask = (df.Distance == 1000) | (df.Distance == 1200)
df = (df.loc[mask].set_index('Date').groupby('TrainerID').rolling(no_days)['Position'].apply(lambda s:round(s.eq(1).sum()/len(s)*100)).groupby('TrainerID').shift().values)
</code>```

The problem is that I get a dimensional mismatch error: Length of values (12521) does not match length of index (27008)

The selection is correct, I have problems with the mask. Can you help me?

Body:
I have the following DataFrame:

Date
Distance
Position
TrainerID

2017-09-03
1000
2
6529

2017-09-03
1600
4
6529

2017-09-03
1200
3
6529

2017-09-06
1200
13
6529

2017-09-08
1000
1
6529

2017-09-10
1600
9
6529

2017-09-15
1600
2
6529

I want to compute on every row the winning percentage so far for the sprint races (distance of 1200 meters or less) in the last 1000 days, grouped by TrainerID. The result will be stored in a Win% Column. Dates need not to be unique. However, the winning % is considered to be before the race happened, so the current row is excluded. Thus, the results are delayed by one row.

The rows of the races that do not fit this category, should have the winning percentage from above.

What I am looking for is a result like this:

Date
Distance
Position
TrainerID
Win %

2017-09-03
1000
2
6529
0 (0 wins, 0 races)

2017-09-03
1600
4
6529
0 (does not fit the criteria, value copied from above)

2017-09-03
1200
3
6529
0 (0 wins, 1 race)

2017-09-06
1200
13
6529
0 (0 wins, 2 races)

2017-09-08
1000
1
6529
0 (0 wins, 3 races)

2017-09-10
1600
9
6529
25 (1 win, 4 races)

2017-09-15
1600
2
6529
25 (does not fit the criteria, value copied from above)

For this, I know I am going to need a mask to select the data that fits and, of course, the selecting code. What I have so far is this:

mask = (df.Distance == 1000) | (df.Distance == 1200)
df = (df.loc[mask].set_index('Date').groupby('TrainerID').rolling(no_days)['Position'].apply(lambda s:round(s.eq(1).sum()/len(s)*100)).groupby('TrainerID').shift().values)

The problem is that I get a dimensional mismatch error: Length of values (12521) does not match length of index (27008)

The selection is correct, I have problems with the mask. Can you help me?

Body:
I prefer to add a temporary column to calculate the winning probability.

In my environment, the following code works fine.

Code

import pandas as pd
from pandas import Timestamp

# create a sample dataframe (a markdown table is shown below as input dataframe)
df = pd.DataFrame({'Date': {0: Timestamp('2017-09-08 00:00:00'), 1: Timestamp('2017-09-05 00:00:00'), 2: Timestamp('2017-09-04 00:00:00'), 3: Timestamp('2017-09-15 00:00:00'), 4: Timestamp('2017-09-05 00:00:00'), 5: Timestamp('2017-09-11 00:00:00'), 6: Timestamp('2017-09-03 00:00:00'), 7: Timestamp('2017-09-03 00:00:00'), 8: Timestamp('2017-09-07 00:00:00'), 9: Timestamp('2017-09-07 00:00:00'), 10: Timestamp('2017-09-10 00:00:00'), 11: Timestamp('2017-09-14 00:00:00'), 12: Timestamp('2017-09-09 00:00:00'), 13: Timestamp('2017-09-11 00:00:00'), 14: Timestamp('2017-09-12 00:00:00'), 15: Timestamp('2017-09-01 00:00:00'), 16: Timestamp('2017-09-16 00:00:00'), 17: Timestamp('2017-09-15 00:00:00'), 18: Timestamp('2017-09-03 00:00:00'), 19: Timestamp('2017-09-02 00:00:00'), 20: Timestamp('2017-09-06 00:00:00')}, 'Distance': {0: 1000, 1: 1600, 2: 1000, 3: 1600, 4: 1200, 5: 1600, 6: 1600, 7: 1000, 8: 1200, 9: 1000, 10: 1600, 11: 1600, 12: 1000, 13: 1000, 14: 1600, 15: 1200, 16: 1000, 17: 1200, 18: 1200, 19: 1600, 20: 1200}, 'Position': {0: 1, 1: 1, 2: 1, 3: 2, 4: 3, 5: 1, 6: 4, 7: 2, 8: 1, 9: 2, 10: 9, 11: 9, 12: 1, 13: 1, 14: 9, 15: 10, 16: 2, 17: 2, 18: 3, 19: 9, 20: 13}, 'TrainerID': {0: 6529, 1: 1234, 2: 1234, 3: 6529, 4: 1234, 5: 1234, 6: 6529, 7: 6529, 8: 1234, 9: 9999, 10: 6529, 11: 9999, 12: 9999, 13: 9999, 14: 1234, 15: 9999, 16: 1234, 17: 9999, 18: 6529, 19: 9999, 20: 6529}})

# ensure that rows of the same Trainer ID stack in a single block, not seperately.
df = df.sort_values(['TrainerID', 'Date'], kind='stable')

# determine a window size for time series
no_days = '1000D'

# create a mask
mask = (df.Distance == 1000) | (df.Distance == 1200)

# add a temporary column for calculation
df = df.assign(Position_for_calc=df.loc[mask, 'Position'])

# use Date as index
df = df.set_index('Date')

# define calculation of win
calc = lambda s: round(100*s.eq(1).sum()/s.notnull().sum())

# obtain pd.series of calculated winning probability
ser_win = df.groupby('TrainerID').rolling(no_days)['Position_for_calc'].apply(calc).groupby('TrainerID').shift().fillna(0).values

# add Win column and drop the temporary column (a markdown table is shown below as output dataframe)
df = df.assign(Win=ser_win).drop('Position_for_calc', axis=1)

If you want to squeeze everything into a few lines,

df = df.sort_values(['TrainerID', 'Date'], kind='stable')
df = df.assign(Win=df.assign(Position_for_calc=df.loc[(df.Distance == 1000) | (df.Distance == 1200), 'Position']).set_index('Date').groupby('TrainerID').rolling('1000D')['Position_for_calc'].apply(lambda s: round(100*s.eq(1).sum()/s.notnull().sum())).groupby('TrainerID').shift().fillna(0).values)

Python Version

3.9.10

Pandas Version

1.3.5

Input Dataframe

Date
Distance
Position
TrainerID

0
2017-09-08 00:00:00
1000
1
6529

1
2017-09-05 00:00:00
1600
1
1234

2
2017-09-04 00:00:00
1000
1
1234

3
2017-09-15 00:00:00
1600
2
6529

4
2017-09-05 00:00:00
1200
3
1234

5
2017-09-11 00:00:00
1600
1
1234

6
2017-09-03 00:00:00
1600
4
6529

7
2017-09-03 00:00:00
1000
2
6529

8
2017-09-07 00:00:00
1200
1
1234

9
2017-09-07 00:00:00
1000
2
9999

10
2017-09-10 00:00:00
1600
9
6529

11
2017-09-14 00:00:00
1600
9
9999

12
2017-09-09 00:00:00
1000
1
9999

13
2017-09-11 00:00:00
1000
1
9999

14
2017-09-12 00:00:00
1600
9
1234

15
2017-09-01 00:00:00
1200
10
9999

16
2017-09-16 00:00:00
1000
2
1234

17
2017-09-15 00:00:00
1200
2
9999

18
2017-09-03 00:00:00
1200
3
6529

19
2017-09-02 00:00:00
1600
9
9999

20
2017-09-06 00:00:00
1200
13
6529

Output Dataframe

Date
Distance
Position
TrainerID
Win

2017-09-04 00:00:00
1000
1
1234
0

2017-09-05 00:00:00
1600
1
1234
100

2017-09-05 00:00:00
1200
3
1234
100

2017-09-07 00:00:00
1200
1
1234
50

2017-09-11 00:00:00
1600
1
1234
67

2017-09-12 00:00:00
1600
9
1234
67

2017-09-16 00:00:00
1000
2
1234
67

2017-09-03 00:00:00
1600
4
6529
0

2017-09-03 00:00:00
1000
2
6529
0

2017-09-03 00:00:00
1200
3
6529
0

2017-09-06 00:00:00
1200
13
6529
0

2017-09-08 00:00:00
1000
1
6529
0

2017-09-10 00:00:00
1600
9
6529
25

2017-09-15 00:00:00
1600
2
6529
25

2017-09-01 00:00:00
1200
10
9999
0

2017-09-02 00:00:00
1600
9
9999
0

2017-09-07 00:00:00
1000
2
9999
0

2017-09-09 00:00:00
1000
1
9999
0

2017-09-11 00:00:00
1000
1
9999
33

2017-09-14 00:00:00
1600
9
9999
50

2017-09-15 00:00:00
1200
2
9999
50


问:
tksheet and postgresql database (how to update database from tksheet )
I am working with tksheet table which pulls data from postgresql database. The operation I want to perform is to edit the cells from tksheet and get those changes reflected in the database. The treeview update option works but I need to do the same with tksheet to perform update operation from tksheet directly to the database. Thanks</p>
```<code>import tkinter as tk

def update_records():
my_conn= psycopg2.connect(
host="localhost",
user="postgres",
password="********",
database="TEST4"
)
cursor= my_conn.cursor()
self.sheet.set_sheet_data(data = [[]],
           reset_col_positions = True,
           reset_row_positions = True,
           redraw = True,
           verify = False,
           reset_highlights = False)
cursor.execute('''UPDATE std SET snum, venum, tl, des, stat, ps, lfp, fap, fv, fa fp, pd, ps, uss, ul awg, as, not''')
</code>```

答:
Facing same question 6 month later, thought this could help someone in the future:

Use the extra_binding function to bind the table functionality to your own function which is to update your database. Check the documentation at https://github.com/ragardner/tksheet/blob/master/DOCUMENTATION.md#6-Getting-Table-Data for details (chapter 7).

Body:
I am working with tksheet table which pulls data from postgresql database. The operation I want to perform is to edit the cells from tksheet and get those changes reflected in the database. The treeview update option works but I need to do the same with tksheet to perform update operation from tksheet directly to the database. Thanks

import tkinter as tk

def update_records():
my_conn= psycopg2.connect(
host="localhost",
user="postgres",
password="********",
database="TEST4"
)
cursor= my_conn.cursor()
self.sheet.set_sheet_data(data = [[]],
           reset_col_positions = True,
           reset_row_positions = True,
           redraw = True,
           verify = False,
           reset_highlights = False)
cursor.execute('''UPDATE std SET snum, venum, tl, des, stat, ps, lfp, fap, fv, fa fp, pd, ps, uss, ul awg, as, not''')


问:
find pairs of numbers where cube is equal to square
We are given a number N and we have to find pairs i and j where i^3=j^2

For example, let N=50 so for this we will have 3 pairs (1,1),(4,8),(9,27)
basically, we have to find pairs where the cube of one number is the same as the square of the other number in a given pair

the constraint is

1<=N<10^6

1<=i,j<N

Naive approach use 2 for loops iterate through each element and get those pairs where cube is equal to sum time complexity is O(n*2)

```<code>def get_pair(N):
    for i in range(1,N):
        for j in range(1,N):
            if i*i*i==j*j:
                print(i,j)
N=50
get_pair(N)
</code>```

what will be an optimal way to solve this problem with a better time complexity?

答:
Since you're working with integers, if there exists some number M = i^3 = j^2 for i and j between 1 and N, then that means there exists a k such that M = k^6. To find i and j, simply compare the representations of M:

(1) M = k^6 = i^3 = (k^2)^3 therefore i = k^2

(2) M = k^6 = j^2 = (k^3)^2 therefore j = k^3

Since j is always greater than or equal to i, you only need to check if 1 < k^3 < N. In other words, k should be less than the cube root of N.

k
M = k^6
i = k^2
j = k^3

2
64
4
8

3
729
9
27

4
4,096
16
64

5
15,625
25
125

6
46,656
36
216

...
...
...
...

97
8.329x10^11
9409
912,673

98
8.858x10^11
9604
941,192

99
9.415x10^11
9801
970,299

Note that 100 isn't a valid candidate for k because that would make j less than or equal to N instead of strictly less than N (if we're going with N = 10^6).

So to get the list of tuples that satisfy your problem, find the values of k such that 1 < k^3 < N and return its square and cube in a tuple.

import math
from typing import List, Tuple

N: int = 10**6
pairs: List[Tuple[int, int]] = [(k * k, k * k * k) for k in range(2, math.ceil(N**(1 / 3)))]
print(pairs)
```

This is a list comprehension, a shorthand for a for-loop.

I'm basically asking Python to generate a list of tuples over an index k that falls in the range defined as range(2, math.ceil(N**(1 / 3)). That range is exactly the first column of the table above.

Then, for every k in that range I make a tuple of which the first item is k^2 and the second item is k^3, just like the last two columns of the table.

Also threw in the typing library in there for good measure. Clear code is good code, even for something as small as this. Python can figure out that pairs is a list of tuples without anyone telling it, but this way I've explicitly enforced that variable to be a list of tuples to avoid any confusion when someone tries to give it a different value or isn't sure what the variable contains.

Body:
We are given a number N and we have to find pairs i and j where i^3=j^2

For example, let N=50 so for this we will have 3 pairs (1,1),(4,8),(9,27)
basically, we have to find pairs where the cube of one number is the same as the square of the other number in a given pair

the constraint is

1<=N<10^6

1<=i,j<N

Naive approach use 2 for loops iterate through each element and get those pairs where cube is equal to sum time complexity is O(n*2)

def get_pair(N):
    for i in range(1,N):
        for j in range(1,N):
            if i*i*i==j*j:
                print(i,j)
N=50
get_pair(N)

what will be an optimal way to solve this problem with a better time complexity?

Body:
Since you're working with integers, if there exists some number M = i^3 = j^2 for i and j between 1 and N, then that means there exists a k such that M = k^6. To find i and j, simply compare the representations of M:

(1) M = k^6 = i^3 = (k^2)^3 therefore i = k^2

(2) M = k^6 = j^2 = (k^3)^2 therefore j = k^3

Since j is always greater than or equal to i, you only need to check if 1 < k^3 < N. In other words, k should be less than the cube root of N.

k
M = k^6
i = k^2
j = k^3

2
64
4
8

3
729
9
27

4
4,096
16
64

5
15,625
25
125

6
46,656
36
216

...
...
...
...

97
8.329x10^11
9409
912,673

98
8.858x10^11
9604
941,192

99
9.415x10^11
9801
970,299

Note that 100 isn't a valid candidate for k because that would make j less than or equal to N instead of strictly less than N (if we're going with N = 10^6).

So to get the list of tuples that satisfy your problem, find the values of k such that 1 < k^3 < N and return its square and cube in a tuple.

import math
from typing import List, Tuple

N: int = 10**6
pairs: List[Tuple[int, int]] = [(k * k, k * k * k) for k in range(2, math.ceil(N**(1 / 3)))]
print(pairs)

This is a list comprehension, a shorthand for a for-loop.

I'm basically asking Python to generate a list of tuples over an index k that falls in the range defined as range(2, math.ceil(N**(1 / 3)). That range is exactly the first column of the table above.

Then, for every k in that range I make a tuple of which the first item is k^2 and the second item is k^3, just like the last two columns of the table.

Also threw in the typing library in there for good measure. Clear code is good code, even for something as small as this. Python can figure out that pairs is a list of tuples without anyone telling it, but this way I've explicitly enforced that variable to be a list of tuples to avoid any confusion when someone tries to give it a different value or isn't sure what the variable contains.


问:
Reversing a hash, getting its keys, and sorting
I'm still learning Perl, so there's probably a more efficient way of doing this. I'm trying to take a hash, reverse it so $values => $keys, grab the new key (the old value) and then sort those keys.

Here's the code in question:

```<code>foreach my $key (sort keys reverse %hash){

...}
</code>```

What I'm expecting to happen is that reverse %hash will return a hash type, which is what keys is looking for. However, I get the following error:

Type of arg 1 to keys must be hash (not reverse)

I've tried putting parentheses around reverse %hash, but still get the same thing.

Any ideas why this wouldn't work?

答:
Perl functions can either return scalar values or lists; there is no explicit hash return type
(You can call return %hash from a subroutine, but Perl implicitly unrolls the key-value pairs from the hash and returns them as a list).

Therefore, the return value of reverse %hash is a list, not a hash, and not suitable for use as an argument to keys. You can force Perl to interpret this list as a hash with the %{{}} cast:

```<code>foreach my $key (sort keys %{{reverse %hash}}) { ...
</code>```

You could also sort on the values of the hash by saying

```<code>foreach my $key (sort values %hash) { ...
</code>```

Using values %hash is subtly different from using keys %{{reverse %hash}} in that keys %{{reverse %hash}} will not return any duplicate values.

Body:
I'm still learning Perl, so there's probably a more efficient way of doing this. I'm trying to take a hash, reverse it so $values => $keys, grab the new key (the old value) and then sort those keys.

Here's the code in question:

foreach my $key (sort keys reverse %hash){

...}

What I'm expecting to happen is that reverse %hash will return a hash type, which is what keys is looking for. However, I get the following error:

Type of arg 1 to keys must be hash (not reverse)

I've tried putting parentheses around reverse %hash, but still get the same thing.

Any ideas why this wouldn't work?

Body:
Perl functions can either return scalar values or lists; there is no explicit hash return type
(You can call return %hash from a subroutine, but Perl implicitly unrolls the key-value pairs from the hash and returns them as a list).

Therefore, the return value of reverse %hash is a list, not a hash, and not suitable for use as an argument to keys. You can force Perl to interpret this list as a hash with the %{{}} cast:

foreach my $key (sort keys %{{reverse %hash}}) { ...

You could also sort on the values of the hash by saying

foreach my $key (sort values %hash) { ...

Using values %hash is subtly different from using keys %{{reverse %hash}} in that keys %{{reverse %hash}} will not return any duplicate values.


问:
Hazelcast - distributed data structure state of other members / monitoring consistency corruption
I have a distributed IMap (exposed through a JCache implementation). When I access it, I get the data of the requesting member. I wish to see the state of this dataset in other members in order to debug consistency corruption scenarios such as stale data in one of the nodes, and so on.

I would also like to explore other recommended practices to monitor the data consistency across the cluster.

Thanks.

答:
A runnable/callable that is HazelcastInstanceAware can invoke localKeySet(). This would give it access to the subset of keys stored on each node.

If read-from-backup is enabled, when that same runnable retrieves the value, it gets the value stored on that node.

This might also be a useful read.


问:
How to not change the length of preexisting character variables when creating a new dataset in proc-iml?
I have a dataset which I manipulate in proc-iml and then create a new dataset reading some of the manipulated values in. When I read character values in, their length is changed from 7 to 9.

This doesn't really create a problem, except for the minor annoyance that when I later merge this new dataset, I receive the warning that the variables' length is different in two datasets.

Is there a way to keep the length of the original variable?

Sample code

```<code>data data1;
infile datalines delimiter=',';

input classif :$9. time :$7.;
datalines;
05, 2021_11
051, 2021_11
;
run;

proc iml;
    use work.data1;
    read all var {classif time } into _temp_1;
    classif = _temp_1[,1];
    time   = _temp_1[,2];
close;
create work.data2 var{classif time};
append;
quit;

</code>```

Observe how the length of time is 7 in data1, but 9 in data2.

答:
If you want the variables from DATA1 to be defined the same in DATA2 you could just add a data step after your PROC IML code.

```<code>data data2;
  set data1(obs=0) data2;
run;
</code>```

It works because SAS defines the variables the first time they are seen. In this case the variables are defined by how the are defined in DATA1 even though the OBS=0 dataset option will prevent any observations actually being read from DATA1.

Body:
I have a dataset which I manipulate in proc-iml and then create a new dataset reading some of the manipulated values in. When I read character values in, their length is changed from 7 to 9.

This doesn't really create a problem, except for the minor annoyance that when I later merge this new dataset, I receive the warning that the variables' length is different in two datasets.

Is there a way to keep the length of the original variable?

Sample code

data data1;
infile datalines delimiter=',';

input classif :$9. time :$7.;
datalines;
05, 2021_11
051, 2021_11
;
run;

proc iml;
    use work.data1;
    read all var {classif time } into _temp_1;
    classif = _temp_1[,1];
    time   = _temp_1[,2];
close;
create work.data2 var{classif time};
append;
quit;

Observe how the length of time is 7 in data1, but 9 in data2.

Body:
If you want the variables from DATA1 to be defined the same in DATA2 you could just add a data step after your PROC IML code.

data data2;
  set data1(obs=0) data2;
run;

It works because SAS defines the variables the first time they are seen. In this case the variables are defined by how the are defined in DATA1 even though the OBS=0 dataset option will prevent any observations actually being read from DATA1.


问:
My android project is not reacting to any changes in the code of .java files
My android project had so far been working perfectly fine, just as expected. Now, however, my app does not react to major changes in code at all. I have no idea how, why or when exactly it happened, but one of my .java activity files was basically reverted to a default state and all of the code I had written was removed, only the boiler plate code is there now, with the minimum includes and the onCreate().

```<code>package com.example.treasurehunt;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.Toast;

public class FindGame extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Toast.makeText(this, "FindGame was changed!", Toast.LENGTH_SHORT).show();
    }
}
</code>```

That activity works with Firebase to populate a listView with entries from the database. Without the code in it, that listView should be completely empty, but even when I build the app again (which should give an error but it doesn't) and run it, the activity works as normal. I changed the code in the onCreate() to include a Log.i message, and it doesn't show up in the Logcat. I then made it so it shows a Toast in the onCreate(), and that doesn't show up either, so it just doesn't change as the code does, which is super weird.

I went into the project directory and opened the FindGame.CLASS file in Notepad++ to see if it maybe had the old, complete version of the code and it didn't. I also checked the local history and the old, correct version isn't there. I'm baffled and don't understand how the android app can kind of ignore the contents of a .java file, or even why it would just change on it's own in the first place.

I didn't have Version Control, I know that's kind of a cardinal sin, I got arrogant and assumed something like this could never happen and that I wouldn't make other kinds of mistakes but now I'm paying for it. I have no code to show for my FindGame activity and no way to change my app, even though it works. I would greatly appreciate any help. Thank you!

答:
Build -> Clean Project

Build -> Rebuild Project

Run the app again.

Body:
My android project had so far been working perfectly fine, just as expected. Now, however, my app does not react to major changes in code at all. I have no idea how, why or when exactly it happened, but one of my .java activity files was basically reverted to a default state and all of the code I had written was removed, only the boiler plate code is there now, with the minimum includes and the onCreate().

package com.example.treasurehunt;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.Toast;

public class FindGame extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Toast.makeText(this, "FindGame was changed!", Toast.LENGTH_SHORT).show();
    }
}

That activity works with Firebase to populate a listView with entries from the database. Without the code in it, that listView should be completely empty, but even when I build the app again (which should give an error but it doesn't) and run it, the activity works as normal. I changed the code in the onCreate() to include a Log.i message, and it doesn't show up in the Logcat. I then made it so it shows a Toast in the onCreate(), and that doesn't show up either, so it just doesn't change as the code does, which is super weird.

I went into the project directory and opened the FindGame.CLASS file in Notepad++ to see if it maybe had the old, complete version of the code and it didn't. I also checked the local history and the old, correct version isn't there. I'm baffled and don't understand how the android app can kind of ignore the contents of a .java file, or even why it would just change on it's own in the first place.

I didn't have Version Control, I know that's kind of a cardinal sin, I got arrogant and assumed something like this could never happen and that I wouldn't make other kinds of mistakes but now I'm paying for it. I have no code to show for my FindGame activity and no way to change my app, even though it works. I would greatly appreciate any help. Thank you!


问:
Why does my ajax call not returning my data from controller?
I'm having a hard time getting the data from client but my code on visual studio when I'm on a breakpoint it gets the data but I cant receive it on my browser.

Here's my AJAX call

```<code>function GetRecord() {
    var elemEmployee = 55;
    var startDT = $('#searchFilterStartDate').val();
    var endDT = $('#searchFilterEndDate').val();

    $.ajax({
        url: "/Modules/GetDTRRecord",
        type: "GET",
        data: {
            EmployeeID: elemEmployee,
            DateFrom: endDT,
            DateTo: startDT,
        },
        dataType: "json",
        success: function(data) {

            console.log('Data Success ');

             console.log(data);

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

here's my controller:

```<code>
        [HttpGet]
        public List<DTRRecordList.Entity> GetDTRRecord(DTRRecordList.Entity data)
        {
            var entity = new DTRRecordList();

            return entity.GetDTR(data);
        }
</code>```

As you can see below I got 38 records but I can't receive it on my js even that console.log('Data Success') is not shown on my console.

答:
You need to return JSON from your Controller method. You can change your method to:

```<code>    [HttpGet]
    public JsonResult GetDTRRecord(DTRRecordList.Entity data)
    {
        var entity = new DTRRecordList();
        var getDTR= entity.GetDTR(data);
        return Json(new {dtrData= getDTR});
    }
</code>```

And in your Ajax call:

```<code>$.ajax({
    url: "/Modules/GetDTRRecord",
    type: "GET",
    data: {
        EmployeeID: elemEmployee,
        DateFrom: endDT,
        DateTo: startDT,
    },
    dataType: "json",
    success: function(data) {
         console.log('Data Success ');
         console.log(data.dtrData);
    },
    error: function(error) {
        console.log(error)
    }
});
</code>```

After a discussion with O.P and seeing the code, it was found that the issue was happening because the form submit was happening which was causing the page to reload twice. After removing the form event and adding the click event in:

```<code>$(document).ready(function () {
    //On Clink "Search Button"
    $("#searchbtn").click(
    function () { GetRecord(); });
});
</code>```

The data seems to be coming as expected.

Body:
I'm having a hard time getting the data from client but my code on visual studio when I'm on a breakpoint it gets the data but I cant receive it on my browser.

Here's my AJAX call

function GetRecord() {
    var elemEmployee = 55;
    var startDT = $('#searchFilterStartDate').val();
    var endDT = $('#searchFilterEndDate').val();

    $.ajax({
        url: "/Modules/GetDTRRecord",
        type: "GET",
        data: {
            EmployeeID: elemEmployee,
            DateFrom: endDT,
            DateTo: startDT,
        },
        dataType: "json",
        success: function(data) {

            console.log('Data Success ');

             console.log(data);

        }
    });
}

here's my controller:

        [HttpGet]
        public List<DTRRecordList.Entity> GetDTRRecord(DTRRecordList.Entity data)
        {
            var entity = new DTRRecordList();

            return entity.GetDTR(data);
        }

As you can see below I got 38 records but I can't receive it on my js even that console.log('Data Success') is not shown on my console.

Body:
You need to return JSON from your Controller method. You can change your method to:

    [HttpGet]
    public JsonResult GetDTRRecord(DTRRecordList.Entity data)
    {
        var entity = new DTRRecordList();
        var getDTR= entity.GetDTR(data);
        return Json(new {dtrData= getDTR});
    }

And in your Ajax call:

$.ajax({
    url: "/Modules/GetDTRRecord",
    type: "GET",
    data: {
        EmployeeID: elemEmployee,
        DateFrom: endDT,
        DateTo: startDT,
    },
    dataType: "json",
    success: function(data) {
         console.log('Data Success ');
         console.log(data.dtrData);
    },
    error: function(error) {
        console.log(error)
    }
});

After a discussion with O.P and seeing the code, it was found that the issue was happening because the form submit was happening which was causing the page to reload twice. After removing the form event and adding the click event in:

$(document).ready(function () {
    //On Clink "Search Button"
    $("#searchbtn").click(
    function () { GetRecord(); });
});

The data seems to be coming as expected.


问:
Enabling blocked text selection using JavaScript
I recently came across a website that disabled text selection, preventing anyone from easily copying and pasting text. I have a bookmarklet that disables similar attempts to block context menus using JavaScript, and I'm wondering if it would be possible to do something similar for text selection.

```<code>function disableSelection(target){
if (typeof target.onselectstart!="undefined") //For IE
    target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //For Firefox
    target.style.MozUserSelect="none"
else //All other route (For Opera)
    target.onmousedown=function(){return false}
target.style.cursor = "default"
}
</code>```

Elsewhere the function is called with disableSelection(document.body).

The solution from my context menu bookmarklet is also probably necessary:

```<code>javascript:void(document.onmousedown=null);
void(document.onclick=null);
void(document.oncontextmenu=null)
</code>```

Finally, I had seen elsewhere on StackOverflow that CSS could also be used:

```<code>-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;
</code>```

Is there a method to fight all of these at once and end this tyranny over my browser? How would I both enable MozUserSelect/SelectStart for all elements and set the CSS properties?

答:
Web sites can always find ways to be obnoxious.  All they have to do is put transparent images over things or put text in images and you'll be slowed down a bit.

Give up worrying about it.  Firefox 4+ gives you control over right-click again so apps can't wrest it away from you.  If you think a site is being that obnoxious, then stop using it and support some other site that isn't being that obnoxious or stop trying to take things they don't want you to take.  Unless the page is all dynamically built from JS, you can always get text from the source of the page.  I say you should stop using sites that annoy you.  If everyone did that, they'd have to change their ways.

Body:
I recently came across a website that disabled text selection, preventing anyone from easily copying and pasting text. I have a bookmarklet that disables similar attempts to block context menus using JavaScript, and I'm wondering if it would be possible to do something similar for text selection.

function disableSelection(target){
if (typeof target.onselectstart!="undefined") //For IE
    target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //For Firefox
    target.style.MozUserSelect="none"
else //All other route (For Opera)
    target.onmousedown=function(){return false}
target.style.cursor = "default"
}

Elsewhere the function is called with disableSelection(document.body).

The solution from my context menu bookmarklet is also probably necessary:

javascript:void(document.onmousedown=null);
void(document.onclick=null);
void(document.oncontextmenu=null)

Finally, I had seen elsewhere on StackOverflow that CSS could also be used:

-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;

Is there a method to fight all of these at once and end this tyranny over my browser? How would I both enable MozUserSelect/SelectStart for all elements and set the CSS properties?


问:
How to fix "TypeError: Cannot read properties of undefined (reading 'useSystemColorMode')"
So I am using ChakraUI and React JS to make a project. Whenever I start the project it gives me the error, "TypeError: Cannot read properties of undefined (reading 'useSystemColorMode')".

I didn't edit any global theme or anything in chakra. I just started making the navbar, designed with CSS. And when I try to run it, it shows me the error.
here is my navbar component

```<code>import React from "react";
import { MenuItems } from "./MenuItems";
import "./navbar.css";

function Navbar() {
  return (
    <>
      <nav className='NavbarItems'>
        <h1 className='navbar-logo'></h1>
        <div className='menu-icon'></div>
        <ul>
          {MenuItems.map((item, index) => {
            return (
              <li key={index}>
                <a className={item.cname} href={item.url}>
                  {item.title}
                </a>
              </li>
            );
          })}
        </ul>
      </nav>
    </>
  );
}

export default Navbar;
</code>```

Navbar CSS file

```<code>.NavbarItems {
  height: 80px;
  display: flex;
  justify-content: center;
}
</code>```

App.js file

```<code>import { ChakraProvider } from "@chakra-ui/provider";
import Navbar from "./components/navbar";
function App() {
  return (
    <ChakraProvider>
      <Navbar />
    </ChakraProvider>
  );
}

export default App;
</code>```

答: Once I used extendTheme instead of an object for theme the error was gone. https://chakra-ui.com/docs/theming/customize-theme</p>

Body:
So I am using ChakraUI and React JS to make a project. Whenever I start the project it gives me the error, "TypeError: Cannot read properties of undefined (reading 'useSystemColorMode')".

I didn't edit any global theme or anything in chakra. I just started making the navbar, designed with CSS. And when I try to run it, it shows me the error.
here is my navbar component

import React from "react";
import { MenuItems } from "./MenuItems";
import "./navbar.css";

function Navbar() {
  return (
    <>

          {MenuItems.map((item, index) => {
            return (

                  {item.title}

            );
          })}

    </>
  );
}

export default Navbar;

Navbar CSS file

.NavbarItems {
  height: 80px;
  display: flex;
  justify-content: center;
}

App.js file

import { ChakraProvider } from "@chakra-ui/provider";
import Navbar from "./components/navbar";
function App() {
  return (
    <ChakraProvider>
      <Navbar />
    </ChakraProvider>
  );
}

export default App;


答:
In JavaScript, json objects are pretty much same as plain JS objects. You need to use string as an index to access properties:

// This could be your json file, its almost the same
// Just require it like you did instead of using const JSON like i am
const json = {
"test1":["test1.1", "test1.2"],
"test2":["test2.1", "test2.2"]
}

function myFunction(TYPE){
// Access the json by using keyword directly as index string
  return(json[TYPE])
  // because TYPE is a string, TYPE[0] would mean first letter of TYPE string
}

function myFunctionDeeper(TYPE){
  // To access a field and array in that field
  return(json[TYPE][0])
}

console.log(myFunction("test1"))
console.log(myFunctionDeeper("test1"))

// example for what happens when accessing string by index
console.log("test1"[0])```

Read more about objects here

Title: use nodejs var as json object statement?

Body:
In JavaScript, json objects are pretty much same as plain JS objects. You need to use string as an index to access properties:

// This could be your json file, its almost the same
// Just require it like you did instead of using const JSON like i am
const json = {
"test1":["test1.1", "test1.2"],
"test2":["test2.1", "test2.2"]
}

function myFunction(TYPE){
// Access the json by using keyword directly as index string
  return(json[TYPE])
  // because TYPE is a string, TYPE[0] would mean first letter of TYPE string
}

function myFunctionDeeper(TYPE){
  // To access a field and array in that field
  return(json[TYPE][0])
}

console.log(myFunction("test1"))
console.log(myFunctionDeeper("test1"))

// example for what happens when accessing string by index
console.log("test1"[0])

Read more about objects here


问:
Can you check if validation rules exist / are valid? [Laravel]
My app has a custom fields functionality: the user can create additional fields for its products.

Ex: the user sells food and wants to add a date field for the product's expiration date.

The expiration date must be greater than today's date. To achieve this, the user has a set of validation rules he can select from the frontend. The rules are sent through the request and stored in the database. When the user creates a new product, the validation rules are retrieved from the database and applied to that field (ex: expiration_date).

How can I make sure that the user cannot tamper with the request to try and add invalid validation rules?

Is there a way to check that the validation rules are valid/exist so that the app doesn't try to apply invalid rules and throws an error?

答:
I ended up using regex to validate all validation rules.

Available validation rules:
accepted,
active_url,
alpha,
alpha_dash,
array,
boolean,
date,
declined,
distinct,
email:,
integer,
ip,
ipv4
ipv6,
mac_address,
json,
required,
nullable,
string,
url,
after:,
before:,
after_or_equal:,
before_or_equal:,
between:,
digits:,
digits_between:,
ends_with:,
starts_with:,
min:,
max:,
multiple_of:,
size:

This is the regex:

/accepted|nullable|active_url|alpha(_dash)?|array|size:[0-9]{1,9}
|(max|min|multiple_of):(-?[0-9]{1,9})|(ends|starts)_with:([A-z]+,)*([A-z]+)
|digits_between:([0-9]{1,2}),([0-9]{1,2})|digits:(-?[0-9]{1,2})
|between:(-?[0-9]{1,9}),(-?[0-9]{1,9})|boolean|date
|(after|before)(_or_equal)?:(today|[0-9]{4}-((1[0-2])|(0?[1-9]))-((3[01])|([0-2]?[0-9])))
|declined|distinct(:(strict|ignore_case))?
|email(:(((rfc|dns|strict|spoof|filter),){1,4})?(rfc|dns|strict|spoof|filter))?
|integer|ip(v[46])?|mac_address|json|required|string|url/
```


问:
How can I test the request object using a specific URL in application_helper_spec.rb?
I have a method defined in application_helper.rb that returns a canonical URL based on the current request. How can I mock or otherwise specify a complete URL for the controller?

```<code># spec/helpers/application_helper_spec.rb
describe "#canonical_url" do
  it "should return a path to an asset that includes the asset_host" do
    # Given: "http://www.foo.com:80/asdf.asdf?asdf=asdf"
    helper.canonical_url().should eq("http://www.foo.com/asdf.asdf")
  end
end

# app/helpers/application_helper.rb
def canonical_url
  "#{request.protocol}#{request.host}#{(request.port == 80) ? "" : request.port_string}#{request.path}"
end
</code>```

EDIT:

Ultimately I want to test that canonical_url() returns the proper string for a bunch of different URLs, some with ports, some w/o, some with querystrings, some with paths, etc. Maybe that's overkill, but that is the end goal. I would like to both explicitly stub/mock/whatever the initial URL and then explicitly set the expectation in the matcher. I would love to be able to do this in one call, i.e. controller.request.url = 'http://www.foo.com:80/asdf.asdf?asdf=asdf' or request = ActionController::TestRequest.new :url => 'http://www.foo.com:80/asdf.asdf?asdf=asdf' but so far I have not found a single "hook" that allows me to do so. So that is the solution I'm looking for. How do I explicitly define the request URL for a given test.

答:
The ultimate cause of this confusion lies in ActionPack:

ActionDispatch::TestRequest

ActionDispatch::Http::URL

e.g. if you set a port (ActionDispatch::TestRequest)

```<code>def port=(number)
  @env['SERVER_PORT'] = number.to_i
end
</code>```

e.g. then you read it (ActionDispatch::Http::URL)

```<code>def raw_host_with_port
  if forwarded = env["HTTP_X_FORWARDED_HOST"]
    forwarded.split(/,\s?/).last
  else
    env['HTTP_HOST'] || "#{env['SERVER_NAME'] || env['SERVER_ADDR']}:#{env['SERVER_PORT']}"
  end
end
</code>```

Setting SERVER_PORT will only take effect if you have no SERVER_NAME, HTTP_X_FORWARDED_HOST or HTTP_HOST already set.

My basic workaround for port settings was to add the port to the host - because request.port doesn't do what you want typically.

e.g. to set the port

```<code>request.host = 'example.com:1234'
</code>```

The real answer is to read the code in ActionPack; it's fairly straightforward.

Body:
I have a method defined in application_helper.rb that returns a canonical URL based on the current request. How can I mock or otherwise specify a complete URL for the controller?

# spec/helpers/application_helper_spec.rb
describe "#canonical_url" do
  it "should return a path to an asset that includes the asset_host" do
    # Given: "http://www.foo.com:80/asdf.asdf?asdf=asdf"
    helper.canonical_url().should eq("http://www.foo.com/asdf.asdf")
  end
end

# app/helpers/application_helper.rb
def canonical_url
  "#{request.protocol}#{request.host}#{(request.port == 80) ? "" : request.port_string}#{request.path}"
end

EDIT:

Ultimately I want to test that canonical_url() returns the proper string for a bunch of different URLs, some with ports, some w/o, some with querystrings, some with paths, etc. Maybe that's overkill, but that is the end goal. I would like to both explicitly stub/mock/whatever the initial URL and then explicitly set the expectation in the matcher. I would love to be able to do this in one call, i.e. controller.request.url = 'http://www.foo.com:80/asdf.asdf?asdf=asdf' or request = ActionController::TestRequest.new :url => 'http://www.foo.com:80/asdf.asdf?asdf=asdf' but so far I have not found a single "hook" that allows me to do so. So that is the solution I'm looking for. How do I explicitly define the request URL for a given test.

Body:
The ultimate cause of this confusion lies in ActionPack:

ActionDispatch::TestRequest

ActionDispatch::Http::URL

e.g. if you set a port (ActionDispatch::TestRequest)

def port=(number)
  @env['SERVER_PORT'] = number.to_i
end

e.g. then you read it (ActionDispatch::Http::URL)

def raw_host_with_port
  if forwarded = env["HTTP_X_FORWARDED_HOST"]
    forwarded.split(/,\s?/).last
  else
    env['HTTP_HOST'] || "#{env['SERVER_NAME'] || env['SERVER_ADDR']}:#{env['SERVER_PORT']}"
  end
end

Setting SERVER_PORT will only take effect if you have no SERVER_NAME, HTTP_X_FORWARDED_HOST or HTTP_HOST already set.

My basic workaround for port settings was to add the port to the host - because request.port doesn't do what you want typically.

e.g. to set the port

request.host = 'example.com:1234'

The real answer is to read the code in ActionPack; it's fairly straightforward.


问:
Remove unwanted elements from subarrays in multidimensional array
I have a multidimensional array like this:

```<code>[
    [
        'id' => 1,
        'name' => 'John',
        'address' => 'Some address 1'
        'city' => 'NY'
    ],
    [
        'id' => 2,
        'name' => 'Jack',
        'address' => 'Some address 2'
        'city' => 'NY'
    ]
    ...

    [ ... ]
]
</code>```

How can I remove elements in all subarrays and only retain the id and name keys with their values?

答:
You want to retain the first two associative elements, so you can make array_slice() calls within array_map(). (Demo)

```<code>var_export(
    array_map(fn($row) => array_slice($row, 0, 2), $array)
);
</code>```

Or mapped called of array_intersect_key() against an establish whitelist array. (Demo)

```<code>$keep = ['id' => '', 'name' => ''];
var_export(
    array_map(
        fn($row) => array_intersect_key($row, $keep),
        $array
    )
)
</code>```

Or, you could use array destructuring inside of a classic foreach() and make iterated compact() calls. (Demo)

```<code>$result = [];
foreach ($array as ['id' => $id, 'name' => $name]) {
    $result[] = compact(['id', 'name']);
}
var_export($result);
</code>```

Body:
I have a multidimensional array like this:

[
    [
        'id' => 1,
        'name' => 'John',
        'address' => 'Some address 1'
        'city' => 'NY'
    ],
    [
        'id' => 2,
        'name' => 'Jack',
        'address' => 'Some address 2'
        'city' => 'NY'
    ]
    ...

    [ ... ]
]

How can I remove elements in all subarrays and only retain the id and name keys with their values?

Body:
You want to retain the first two associative elements, so you can make array_slice() calls within array_map(). (Demo)

var_export(
    array_map(fn($row) => array_slice($row, 0, 2), $array)
);

Or mapped called of array_intersect_key() against an establish whitelist array. (Demo)

$keep = ['id' => '', 'name' => ''];
var_export(
    array_map(
        fn($row) => array_intersect_key($row, $keep),
        $array
    )
)

Or, you could use array destructuring inside of a classic foreach() and make iterated compact() calls. (Demo)

$result = [];
foreach ($array as ['id' => $id, 'name' => $name]) {
    $result[] = compact(['id', 'name']);
}
var_export($result);


问:
Firestore authentication for multiple devices
I'm developing linux c++ desktop application that connects to Firebase. The app will be deployed on multiple devices. Is it possible to perform REST authentication (Sign in with email / password) for all of these devices using one common e-mail address or will it trigger a security alert when more than one sign in operations are performed at the same time? Is there any better solution to solve this problem?</p>

答: A user can sign in to Firebase Authentication from multiple devices. There is no inherent limit to the number of devices a single user can sign in from.</p>


问:
Efficient overflow-immune arithmetic mean in C/C++
The arithmetic mean of two unsigned integers is defined as:

```<code>mean = (a+b)/2
</code>```

Directly implementing this in C/C++ may overflow and produce a wrong result. A correct implementation would avoid this. One way of coding it could be:

```<code>mean = a/2 + b/2 + (a%2 + b%2)/2
</code>```

But this produces rather a lot of code with typical compilers. In assembler, this usually can be done much more efficiently. For example, the x86 can do this in the following way (assembler pseudo code, I hope you get the point):

```<code>ADD a,b   ; addition, leaving the overflow condition in the carry bit
RCR a,1   ; rotate right through carry, effectively a division by 2
</code>```

After those two instructions, the result is in a, and the remainder of the division is in the carry bit. If correct rounding is desired, a third ADC instruction would have to add the carry into the result.

Note that the RCR instruction is used, which rotates a register through the carry. In our case, it is a rotate by one position, so that the previous carry becomes the most significant bit in the register, and the new carry holds the previous LSB from the register. It seems that MSVC doesn't even offer an intrinsic for this instruction.

Is there a known C/C++ pattern that can be expected to be recognized by an optimizing compiler so that it produces such efficient code? Or, more generally, is there a rational way how to program in C/C++ source level so that the carry bit is being used by the compiler to optimize the generated code?

EDIT:

A 1-hour lecture about std::midpoint: https://www.youtube.com/watch?v=sBtAGxBh-XI

Wow!

EDIT2: Great discussion on Microsoft blog

答:
There are three typical methods to compute average without overflow, one of which is limited to uint32_t (on 64-bit architectures).

```<code>// average "SWAR" / Montgomery
uint32_t avg(uint32_t a, uint32_t b) {
   return (a & b) + ((a ^ b) >> 1);
}

// in case the relative magnitudes are known
uint32_t avg2(uint32_t min, uint32_t max) {
  return min + (max - min) / 2;
}
// in case the relative magnitudes are not known
uint32_t avg2_constrained(uint32_t a, uint32_t b) {
  return a + (int32_t)(b - a) / 2;
}

// average increase width (not applicable to uint64_t)
uint32_t avg3(uint32_t a, uint32_t b) {
   return ((uint64_t)a + b) >> 1;
}
</code>```

The corresponding assembler sequences from clang in two architectures are

```<code>avg(unsigned int, unsigned int)
    mov     eax, esi
    and     eax, edi
    xor     esi, edi
    shr     esi
    add     eax, esi

avg2(unsigned int, unsigned int)
    sub     esi, edi
    shr     esi
    lea     eax, [rsi + rdi]

avg3(unsigned int, unsigned int)
    mov     ecx, edi
    mov     eax, esi
    add     rax, rcx
    shr     rax
</code>```

vs.

```<code>avg(unsigned int, unsigned int)
    and     w8, w1, w0
    eor     w9, w1, w0
    add     w0, w8, w9, lsr #1
    ret
avg2(unsigned int, unsigned int)
    sub     w8, w1, w0
    add     w0, w0, w8, lsr #1
    ret
avg3(unsigned int, unsigned int):
    mov     w8, w1
    add     x8, x8, w0, uxtw
    lsr     x0, x8, #1
    ret
</code>```

Out of these three versions, avg2 would perform in ARM64 as well, as the optimal sequence using carry flag -- and also it's likely that avg3 would perform as well, noticing that the mov w8,w1 is used to clear the top 32-bits, which may be unnecessary given that the compiler knows they are cleared by any previous instruction that is used to produce the value.

Similar statement can be made of the Intel version for avg3, which would in optimal case compiled to just the two meaningful instructions:

```<code>add     rax, rcx
shr     rax
</code>```

See https://godbolt.org/z/5TMd3zr81 for online comparison.

The "SWAR"/Montgomery version is typically only justified, when trying to compute multiple averages packed to a single (large) integer in which case the full formula contains masking with the bit positions of the highest bits: return (a & b) + (((a ^ b) >> 1) & ~kH;.

Body:
The arithmetic mean of two unsigned integers is defined as:

mean = (a+b)/2

Directly implementing this in C/C++ may overflow and produce a wrong result. A correct implementation would avoid this. One way of coding it could be:

mean = a/2 + b/2 + (a%2 + b%2)/2

But this produces rather a lot of code with typical compilers. In assembler, this usually can be done much more efficiently. For example, the x86 can do this in the following way (assembler pseudo code, I hope you get the point):

ADD a,b   ; addition, leaving the overflow condition in the carry bit
RCR a,1   ; rotate right through carry, effectively a division by 2

After those two instructions, the result is in a, and the remainder of the division is in the carry bit. If correct rounding is desired, a third ADC instruction would have to add the carry into the result.

Note that the RCR instruction is used, which rotates a register through the carry. In our case, it is a rotate by one position, so that the previous carry becomes the most significant bit in the register, and the new carry holds the previous LSB from the register. It seems that MSVC doesn't even offer an intrinsic for this instruction.

Is there a known C/C++ pattern that can be expected to be recognized by an optimizing compiler so that it produces such efficient code? Or, more generally, is there a rational way how to program in C/C++ source level so that the carry bit is being used by the compiler to optimize the generated code?

EDIT:

A 1-hour lecture about std::midpoint: https://www.youtube.com/watch?v=sBtAGxBh-XI

Wow!

EDIT2: Great discussion on Microsoft blog

Body:
There are three typical methods to compute average without overflow, one of which is limited to uint32_t (on 64-bit architectures).

// average "SWAR" / Montgomery
uint32_t avg(uint32_t a, uint32_t b) {
   return (a & b) + ((a ^ b) >> 1);
}

// in case the relative magnitudes are known
uint32_t avg2(uint32_t min, uint32_t max) {
  return min + (max - min) / 2;
}
// in case the relative magnitudes are not known
uint32_t avg2_constrained(uint32_t a, uint32_t b) {
  return a + (int32_t)(b - a) / 2;
}

// average increase width (not applicable to uint64_t)
uint32_t avg3(uint32_t a, uint32_t b) {
   return ((uint64_t)a + b) >> 1;
}

The corresponding assembler sequences from clang in two architectures are

avg(unsigned int, unsigned int)
    mov     eax, esi
    and     eax, edi
    xor     esi, edi
    shr     esi
    add     eax, esi

avg2(unsigned int, unsigned int)
    sub     esi, edi
    shr     esi
    lea     eax, [rsi + rdi]

avg3(unsigned int, unsigned int)
    mov     ecx, edi
    mov     eax, esi
    add     rax, rcx
    shr     rax

vs.

avg(unsigned int, unsigned int)
    and     w8, w1, w0
    eor     w9, w1, w0
    add     w0, w8, w9, lsr #1
    ret
avg2(unsigned int, unsigned int)
    sub     w8, w1, w0
    add     w0, w0, w8, lsr #1
    ret
avg3(unsigned int, unsigned int):
    mov     w8, w1
    add     x8, x8, w0, uxtw
    lsr     x0, x8, #1
    ret

Out of these three versions, avg2 would perform in ARM64 as well, as the optimal sequence using carry flag -- and also it's likely that avg3 would perform as well, noticing that the mov w8,w1 is used to clear the top 32-bits, which may be unnecessary given that the compiler knows they are cleared by any previous instruction that is used to produce the value.

Similar statement can be made of the Intel version for avg3, which would in optimal case compiled to just the two meaningful instructions:

add     rax, rcx
shr     rax

See https://godbolt.org/z/5TMd3zr81 for online comparison.

The "SWAR"/Montgomery version is typically only justified, when trying to compute multiple averages packed to a single (large) integer in which case the full formula contains masking with the bit positions of the highest bits: return (a & b) + (((a ^ b) >> 1) & ~kH;.


问:
I want to run Power Shell script with admin privileges
I want to run this powershell script with admin privileges so it won't give me the error:

Script Output with error

Here is the script:

```<code>$processes = "PDStyleAgent", "AdobeIPCBroker", "CCXProcess", "RichVideo64", "CCLibrary", "AdobeNotificationClient", "AdobeUpdateService", "PDHanumanSvr", "PDR"

Foreach ($process in $processes){
    try {
    $f = Get-Process $process -ErrorAction Stop
    $f | kill
    Write-Output "$process killed."
        }
    catch [Microsoft.PowerShell.Commands.ProcessCommandException]{
    Write-Output "No instances of $process running."
        }
}

Start-Sleep -Seconds 3
</code>```

I want to run this script so it kill the processes that are giving errors

答:
1.Create a shortcut to your Powershell script on your desktop

2.Right-click the shortcut and click Properties

3.Click the Shortcut tab

4.Click Advanced

5.Select Run as Administrator

NOTE: add powershell -f  in front of the script path

Body:
I want to run this powershell script with admin privileges so it won't give me the error:

Script Output with error

Here is the script:

$processes = "PDStyleAgent", "AdobeIPCBroker", "CCXProcess", "RichVideo64", "CCLibrary", "AdobeNotificationClient", "AdobeUpdateService", "PDHanumanSvr", "PDR"

Foreach ($process in $processes){
    try {
    $f = Get-Process $process -ErrorAction Stop
    $f | kill
    Write-Output "$process killed."
        }
    catch [Microsoft.PowerShell.Commands.ProcessCommandException]{
    Write-Output "No instances of $process running."
        }
}

Start-Sleep -Seconds 3

I want to run this script so it kill the processes that are giving errors


问:
Is it possible to retrieve logs from kubernetes pods through API endpoint from AWS EKS?
I have a kubernetes running on EKS AWS. I want to know it if its possible to access the pods logs through the API endpoint AWS offers for the cluster.

I want to send the logs to a serverless loki running in a different service. I'm not allowed to install nor loki neither promtail inside the kubernetes for company reasons, that's why I want to access the logs through the API endpoint.

答:
Here's a complete guide how to do that using a service account token. To follow the log append ?follow=true like:

```<code>curl -s $APISERVER/api/v1/namespaces/<namespace>/pods/<pod name>/log?follow=true --header "Authorization: Bearer $TOKEN"
--cacert ca.crt
</code>```

Body:
Here's a complete guide how to do that using a service account token. To follow the log append ?follow=true like:

curl -s $APISERVER/api/v1/namespaces/<namespace>/pods/<pod name>/log?follow=true --header "Authorization: Bearer $TOKEN"
--cacert ca.crt


问:
jQuery Find and List all LI elements within a UL within a specific DIV
I have 3 Columns of ULs each a Dynamic UL container that can have anywhere from 0-9 LI containers (eventually more). All my LI elements have an attribute "rel" which I am trying to ultimately find that attribute and use it for something else on all LI elements within that parent DIV. I do eventually want to find more based on each but for not the very least the rel.. Any Ideas how I can achieve that with jQuery? Example:

```<code><ul id="column1">
   <li rel="1">Info</li>
   <li rel="2">Info</li>
   <li rel="3">Info</li>
</ul>
<ul id="column2">
   <li rel="4">Info</li>
   <li rel="5">Info</li>
   <li rel="6">Info</li>
</ul>
<ul id="column3">
   <li rel="7">Info</li>
   <li rel="8">Info</li>
   <li rel="9">Info</li>
</ul>
</code>```

these elements are all sortable as well. So when I get a list of them I want to also keep them in the order they were found from top to bottom of each column.

I have tried find(), parent(), and similar, maybe I am approaching it wrong. But its still worth mentioning to help come up with an idea

答:
```<code>var column1RelArray = [];
$('#column1 li').each(function(){
    column1RelArray.push($(this).attr('rel'));
});
</code>```

or fp style

```<code>var column1RelArray = $('#column1 li').map(function(){
    return $(this).attr('rel');
});
</code>```

Body:
I have 3 Columns of ULs each a Dynamic UL container that can have anywhere from 0-9 LI containers (eventually more). All my LI elements have an attribute "rel" which I am trying to ultimately find that attribute and use it for something else on all LI elements within that parent DIV. I do eventually want to find more based on each but for not the very least the rel.. Any Ideas how I can achieve that with jQuery? Example:

Info

Info

Info

Info

Info

Info

Info

Info

Info

these elements are all sortable as well. So when I get a list of them I want to also keep them in the order they were found from top to bottom of each column.

I have tried find(), parent(), and similar, maybe I am approaching it wrong. But its still worth mentioning to help come up with an idea

Body:
var column1RelArray = [];
$('#column1 li').each(function(){
    column1RelArray.push($(this).attr('rel'));
});

or fp style

var column1RelArray = $('#column1 li').map(function(){
    return $(this).attr('rel');
});


问:
Tabulator AJAX-like Loader for JSON object data source
I'm currently utilising Tabulator 4.8 inside a custom NetSuite (suitelet) form, and it's working really well.

The reactive data feature is quite effective for what I'm doing which is a full replacement for NetSuite's Order Items page and subsequent purchase order creation.

However, when the user selects a large number of items to order, there is a delay while the data is processed inside the client script.

Purely for the user experience I would be able to grey out the screen with an "Ajax" like loader, but as the data source is a preloaded Javascript object, I don't believe the Tabulator Ajax Loader is an object.

From a suitescript point of view, the Suitelet loads all the required data as the page is loaded (server-side) then stores this as a JSON object in an inline html field.

Then the PageInit client script grabs the data and stores it in a client side variable for use in the table and subsequent actions performed.

Functionally it's great, no problems. I'd just love to be able to grey out the tabulator  element with an animated gif loader while all the client side calculations are happening.

答:
"However, when the user selects a large number of items to order,"

This sounds to me like an ongoing concern and the same suitelet might be running for a while with many modifications ... are there any events in the Tabulator that you already hook into?

If not i would look at that. The api shows many callbacks options for different events and context that are based on data events, dom events and ajax events.  http://tabulator.info/docs/3.5#callbacks-cell

For example (and note i'm using their jQuery versions here) you could hook into a render start to display and animation.

$("#example-table").tabulator({
    renderStarted:function(){
          toggleWaitScreen();
    },{
    renderStarted:function(){
          toggleWaitScreen();
    }
});
```


问:
How can I extract the user and type of the repository_dispatch trigger?
I am triggering a repository_dispatch event from C# bot on a github workflow. How can I extract the user and the event type (which is 'run_ba' in my case, I need the info beneath "Triggered via repository dispatch 6 days ago" label in the run example picture) that triggered the run using octokit.net?

run example

I tried using GET on https://api.github.com/repos/{repoOwner}/{repoName}/actions/runs ,but did not find what I was looking for.

答:
I am posting my solution here, maybe it will help someone or someone will provide a better way to do this.

-Create another job in the workflow that creates annotations for the info that I need (check_run_id …)

e.g. echo “::notice title=RunId::${{ github.run_id }}”

-Using octokit to filter workflow runs based on status
-Using octokit retrieve the list of annotations based on the check_run_id from the list of workflow runs and the checksuite that is attached to annotations job.


问:
Two fonts in row of cell using VBA
I want two fonts in the same cell. The second row, is price and the unit of measure (for example ea, dz, cs, pk).

When I work on one cell, the activeCell.character is looking for a start for the first font and a start for the second font.

Due to the price changing is size from 3 numbers including those after the decimal place to 4, 5 and 6 this method won't work.

I need something that will have the cell as one font and then 3 places to the right of the decimal place "." change the font.

Sub TwoFonts2()

    Dim MyPos, SearchChar
    SearchChar = "."

    Rows("2:2").Select
    With ActiveCell.Characters(Start:=1, Length:=8).Font
        .Name = "ITC Avant Garde Std Bk"
        .FontStyle = "Bold"
        .Size = 26
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .ThemeColor = xlThemeColorLight1
        .TintAndShade = 0
        .ThemeFont = xlThemeFontNone
    End With

    With MyPos = (InStr(SearchChar, x, " ") + 3)
        .Name = "ITC Avant Garde Std Bk"
        .FontStyle = "Bold"
        .Size = 14
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .ThemeColor = xlThemeColorLight1
        .TintAndShade = 0
        .ThemeFont = xlThemeFontNone
    End With

End Sub
```

答:
Please, try the next way. It accepts spaces before the number, which is mandatory to have a dot as decimal separator. The string after the last space (for the second font) may have any number of characters. If only one space, before the last small font characters, the code can be simplified, directly returning the space position:</p>
```<code>Sub SplitCharactersFonts()
   Dim x As String, secF As Long
   x = ActiveCell.Value

   secF = InStr(InStr(x, "."), x, " ") + 1 'find space starting from dot position
   With ActiveCell.Characters(1, secF - 1).Font
        .size = 26
        'do watever you need with the first part
   End With
   With ActiveCell.Characters(secF, Len(x)).Font
        .size = 14
         'do whatever you need with the second part
   End With
End Sub
</code>```

Title: Two fonts in row of cell using VBA

Body:
Please, try the next way. It accepts spaces before the number, which is mandatory to have a dot as decimal separator. The string after the last space (for the second font) may have any number of characters. If only one space, before the last small font characters, the code can be simplified, directly returning the space position:

Sub SplitCharactersFonts()
   Dim x As String, secF As Long
   x = ActiveCell.Value

   secF = InStr(InStr(x, "."), x, " ") + 1 'find space starting from dot position
   With ActiveCell.Characters(1, secF - 1).Font
        .size = 26
        'do watever you need with the first part
   End With
   With ActiveCell.Characters(secF, Len(x)).Font
        .size = 14
         'do whatever you need with the second part
   End With
End Sub


问:
Display an image as a splash screen when running Windows batch file, vbscript/wscript or Python console script
Any ideas how I can display an image file (bmp or png) centered on the screen as an application splash screen when running a Windows console script based on a batch file, vbscript/wscript or Python console script?

I'm not interested in a wxPython solution - that's too much overhead just to implement a cosmetic feature like a splash screen.

Thank you,
Malcolm

答:
I'll add a late reply to the mix. I think this is an interesting option worth looking at:

http://www.quicksplash.net

ContentLicense: CC BY-SA 2.5