问:
User Beanshell processor to write code so that data driven testing performed rather than using csv
I want to test a Get Request with list of values. I dont want to use CSV ,

so i started using Beanshell Preprocessor  and has those values in Array. Then used for loop to use those values and send to Get Request in HTTP Request. Every this was Successful except sending values to Get request. It is reading all values and sending the last read value to Get request.

Question : I want my request to run for each value when code reads the data one by one.

```<code>                var TtValuedetails;
                int i;
                n=22;
                String[] ttvalue = {"34324324224","fdadsfadsf","dfdsfdsfds","dafadsfa",
                "45435435","dfadsfads"
                  };
          for(int i=0;i<n;i++)
           {

            if(i==0)
            {
                TtValuedetails=ttvalue[i];

            if(ttvalue[0]=="34324324224")
                {
                    vars.put("TtValuedetails",TtValuedetails);
                    log.info(TtValuedetails);
                    log.info("first value is executed" );
                    Org.Apache.......startRequest();
                }
            }
}   ;
</code>```

答:
We cannot help you without seeing the full code and knowing what you're trying to achieve but one thing is obvious: you should not be using Beanshell, since JMeter 3.1 it's recommended to use Groovy for scripting.

Current problem with your code is:

ttvalue array contains 6 elements

n=22

the line TtValuedetails=ttvalue[i]; will cause failure on 7th iteration of the loop due to IndexOutOfBoundsException

If you want to send a request for each value of the ttvalue array the easiest is converting it into separate JMeter Variables like:

```<code>ttvalue_1=34324324224
ttvalue_2=fdadsfadsf
etc.
</code>```

and using ForEach Controller for iterating the values.

Example Groovy code for storing the values into JMeter Variables:

```<code>String[] ttvalue = ["34324324224", "fdadsfadsf", "dfdsfdsfds", "dafadsfa",
                    "45435435", "dfadsfads"];

for (int i = 1; i <= ttvalue.size(); i++) {
    vars.put("ttvalue_" + i, ttvalue[i - 1]);
}
</code>```

Body:
I want to test a Get Request with list of values. I dont want to use CSV ,

so i started using Beanshell Preprocessor  and has those values in Array. Then used for loop to use those values and send to Get Request in HTTP Request. Every this was Successful except sending values to Get request. It is reading all values and sending the last read value to Get request.

Question : I want my request to run for each value when code reads the data one by one.

                var TtValuedetails;
                int i;
                n=22;
                String[] ttvalue = {"34324324224","fdadsfadsf","dfdsfdsfds","dafadsfa",
                "45435435","dfadsfads"
                  };
          for(int i=0;i<n;i++)
           {

            if(i==0)
            {
                TtValuedetails=ttvalue[i];

            if(ttvalue[0]=="34324324224")
                {
                    vars.put("TtValuedetails",TtValuedetails);
                    log.info(TtValuedetails);
                    log.info("first value is executed" );
                    Org.Apache.......startRequest();
                }
            }
}   ;

Body:
We cannot help you without seeing the full code and knowing what you're trying to achieve but one thing is obvious: you should not be using Beanshell, since JMeter 3.1 it's recommended to use Groovy for scripting.

Current problem with your code is:

ttvalue array contains 6 elements

n=22

the line TtValuedetails=ttvalue[i]; will cause failure on 7th iteration of the loop due to IndexOutOfBoundsException

If you want to send a request for each value of the ttvalue array the easiest is converting it into separate JMeter Variables like:

ttvalue_1=34324324224
ttvalue_2=fdadsfadsf
etc.

and using ForEach Controller for iterating the values.

Example Groovy code for storing the values into JMeter Variables:

String[] ttvalue = ["34324324224", "fdadsfadsf", "dfdsfdsfds", "dafadsfa",
                    "45435435", "dfadsfads"];

for (int i = 1; i <= ttvalue.size(); i++) {
    vars.put("ttvalue_" + i, ttvalue[i - 1]);
}


来源: stackexchange

问:
Replacing numerical IDs contained as lists of strings and lists of ints in a Pandas DataFrame
In order to make data anonymous, I need to replace original IDs with a different set of new IDs, but still have identical original IDs match across all fields after being replaced. The challenge is doing so elegantly across 4 different presentations of IDs in this Pandas DataFrame.

I have real-world data where numerical IDs are found in 4 possible formats:

Within a list of strings '["38", "15", "42"]'

Within a list of numbers [14, 42, 94]

As integers 42

As floats 1.0

Here is a generalized small DataFrame with all 4 data types.

```<code>df = pd.DataFrame([['["38", "15", "42"]', [14, 42, 94], 42, 1.0],\
 ['["8", "28"]', [1, 4], 8, 94.0], ['["12"]', [12], 12, 12.0]],\
 columns = ['CommentsID','AgentID','CaseID','TicketID'])

df
| CommentsID            | AgentID         | CaseID  | TicketID |
| --------------------- | --------------- | ------- | -------- |
| ['38', '15', '42']    | [14, 42, 94]    | 42      | 1.0      |
| ['8', '28']           | [1, 4]          | 8       | 94.0     |
| ['12']                | [12]            | 12      | 12.0     |
</code>```

For ease of use in a generalized example, I'm just adding 100 to generate a list of 'new IDs'. However, in the actual problem, the list of corresponding new IDs are randomly generated, so no adding 100 throughout to solve for this one.

```<code>orig_ids = list(range(100))
new_ids = [x + 100 for x in orig_ids]
</code>```

What I would like is to find the most efficient way to replace all of the original IDs in the dataframe with the new IDs across these four data types.

Best solution I have so far is to split into three parts:

Tackle the float and int versions with a replace() function (this does not affect the lists, even with regex=True):

```<code>df = df.replace(orig_ids, new_ids)
</code>```

For the lists of integers, use a far-from-Pythonic doubled for-loop to match indices on the ID lists:

```<code>def newIDnumbers(datacol):
    newlist = []
    for i in range(len(datacol)):
        numlist = [orig_ids.index(x) for x in df.AgentID[i]]
        newlistrow = []
        for idx in range(len(numlist)):
            newlistrow.append(new_ids[numlist[idx]])
        newlist.append(newlistrow)
    return newlist

df.AgentID = newIDnumbers(df.AgentID)
df
</code>```

For the lists of strings, build string lists of original ids and new ids, then use a far-from-Pythonic doubled for-loop to match indices on the ID lists:

```<code>str_orig_ids = [str(x) for x in orig_ids]
str_new_ids = [str(x) for x in new_ids]

def newIDstrings(datacol):
    newlist = []
    for i in range(len(datacol)):
        numlist = [str_orig_ids.index(x) for x in datacol.str.findall(r'"(\d*)"')[i]]
        newlistrow = []
        for idx in range(len(numlist)):
            newlistrow.append(str_new_ids[numlist[idx]])
        newlist.append(newlistrow)
    return newlist

df.CommentsID = [str(x) for x in newIDstrings(df.CommentsID)]
df
</code>```

Does anyone have a more elegant and less computationally-heavy way to achieve this output?

```<code>df
| CommentsID            | AgentID         | CaseID  | TicketID |
| --------------------- | --------------- | ------- | -------- |
| ['138', '115', '142'] | [114, 142, 194] | 142     | 100.0    |
| ['108', '128']        | [101, 104]      | 108     | 194.0    |
| ['112']               | [112]           | 112     | 112.0    |
</code>```

答:
Here is one way using reshaping and factorize to anonymize the IDs:

```<code>from ast import literal_eval

def df_factorize(df):
    idx = df.index
    s = df.reset_index(drop=True).stack()  # stack to ensure consistent
    s[:] = s.factorize()[0]                # factors among all columns
    return s.unstack().set_index(idx)

df2 = (df
   .assign(CommentsID=df['CommentsID'].apply(literal_eval))   # extract as integers
   .explode(['CommentsID', 'AgentID'])                        # lists to rows
   .astype({'CommentsID': int}) # change str to int
   .pipe(df_factorize)                                        # anonymize
   .groupby(level=0)                                          # below to reshape
   .agg({'CommentsID': lambda s: str(list(s.astype(str))),    # to original form
         'AgentID': list,
         'CaseID': 'first',
         'TicketID': 'first',
        })
   .astype(df.dtypes)                                         # original dtypes
)
</code>```

output:

```<code>        CommentsID    AgentID  CaseID  TicketID
0  ['0', '4', '2']  [1, 2, 5]       2       3.0
1       ['6', '7']     [3, 8]       6       5.0
2            ['9']        [9]       9       9.0
</code>```

In case you want "real" anonymization, you could use a uuid:

```<code>from uuid import uuid4

def df_uuid(df):
    idx = df.index
    s = df.reset_index(drop=True).stack()
    f = s.unique()
    s = s.map(dict(zip(f, [str(uuid4()) for _ in range(len(f))])))
    return s.unstack().set_index(idx)
</code>```

output:

```<code>                                                                                CommentsID                                                                                AgentID                                CaseID                              TicketID
0  ['e9fa80ed-58e2-4a96-a8da-0bc0c3a87e14', 'c87ca55a-e0a4-4618-ab5a-2eaf68d5a70f', '7cba72a8-3f2a-42e7-a781-b8ed242ea2ac']  [65f95f56-877e-4a9f-be88-4302fe1f77ea, 7cba72a8-3f2a-42e7-a781-b8ed242ea2ac, 3cf48cd7-e1b0-4c7f-bbeb-41836e309511]  7cba72a8-3f2a-42e7-a781-b8ed242ea2ac  549f1768-39b5-4e74-a8dd-4edbf3bb591f
1                                          ['6e54d7d6-ae2f-4319-950e-7629128d518a', '8fef2e1c-99d1-4460-b8a4-f4dbbf213c5f']                                        [549f1768-39b5-4e74-a8dd-4edbf3bb591f, 98f82da0-fa9c-447a-943b-b11875736128]  6e54d7d6-ae2f-4319-950e-7629128d518a  3cf48cd7-e1b0-4c7f-bbeb-41836e309511
2                                                                                ['3396c9db-1244-4b2d-bb76-14bb0221778f']                                                                              [3396c9db-1244-4b2d-bb76-14bb0221778f]  3396c9db-1244-4b2d-bb76-14bb0221778f  3396c9db-1244-4b2d-bb76-14bb0221778f
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In order to make data anonymous, I need to replace original IDs with a different set of new IDs, but still have identical original IDs match across all fields after being replaced. The challenge is doing so elegantly across 4 different presentations of IDs in this Pandas DataFrame.

I have real-world data where numerical IDs are found in 4 possible formats:

Within a list of strings '["38", "15", "42"]'

Within a list of numbers [14, 42, 94]

As integers 42

As floats 1.0

Here is a generalized small DataFrame with all 4 data types.

df = pd.DataFrame([['["38", "15", "42"]', [14, 42, 94], 42, 1.0],\
 ['["8", "28"]', [1, 4], 8, 94.0], ['["12"]', [12], 12, 12.0]],\
 columns = ['CommentsID','AgentID','CaseID','TicketID'])

df
| CommentsID            | AgentID         | CaseID  | TicketID |
| --------------------- | --------------- | ------- | -------- |
| ['38', '15', '42']    | [14, 42, 94]    | 42      | 1.0      |
| ['8', '28']           | [1, 4]          | 8       | 94.0     |
| ['12']                | [12]            | 12      | 12.0     |

For ease of use in a generalized example, I'm just adding 100 to generate a list of 'new IDs'. However, in the actual problem, the list of corresponding new IDs are randomly generated, so no adding 100 throughout to solve for this one.

orig_ids = list(range(100))
new_ids = [x + 100 for x in orig_ids]

What I would like is to find the most efficient way to replace all of the original IDs in the dataframe with the new IDs across these four data types.

Best solution I have so far is to split into three parts:

Tackle the float and int versions with a replace() function (this does not affect the lists, even with regex=True):

df = df.replace(orig_ids, new_ids)

For the lists of integers, use a far-from-Pythonic doubled for-loop to match indices on the ID lists:

def newIDnumbers(datacol):
    newlist = []
    for i in range(len(datacol)):
        numlist = [orig_ids.index(x) for x in df.AgentID[i]]
        newlistrow = []
        for idx in range(len(numlist)):
            newlistrow.append(new_ids[numlist[idx]])
        newlist.append(newlistrow)
    return newlist

df.AgentID = newIDnumbers(df.AgentID)
df

For the lists of strings, build string lists of original ids and new ids, then use a far-from-Pythonic doubled for-loop to match indices on the ID lists:

str_orig_ids = [str(x) for x in orig_ids]
str_new_ids = [str(x) for x in new_ids]

def newIDstrings(datacol):
    newlist = []
    for i in range(len(datacol)):
        numlist = [str_orig_ids.index(x) for x in datacol.str.findall(r'"(\d*)"')[i]]
        newlistrow = []
        for idx in range(len(numlist)):
            newlistrow.append(str_new_ids[numlist[idx]])
        newlist.append(newlistrow)
    return newlist

df.CommentsID = [str(x) for x in newIDstrings(df.CommentsID)]
df

Does anyone have a more elegant and less computationally-heavy way to achieve this output?

df
| CommentsID            | AgentID         | CaseID  | TicketID |
| --------------------- | --------------- | ------- | -------- |
| ['138', '115', '142'] | [114, 142, 194] | 142     | 100.0    |
| ['108', '128']        | [101, 104]      | 108     | 194.0    |
| ['112']               | [112]           | 112     | 112.0    |

Body:
Here is one way using reshaping and factorize to anonymize the IDs:

from ast import literal_eval

def df_factorize(df):
    idx = df.index
    s = df.reset_index(drop=True).stack()  # stack to ensure consistent
    s[:] = s.factorize()[0]                # factors among all columns
    return s.unstack().set_index(idx)

df2 = (df
   .assign(CommentsID=df['CommentsID'].apply(literal_eval))   # extract as integers
   .explode(['CommentsID', 'AgentID'])                        # lists to rows
   .astype({'CommentsID': int}) # change str to int
   .pipe(df_factorize)                                        # anonymize
   .groupby(level=0)                                          # below to reshape
   .agg({'CommentsID': lambda s: str(list(s.astype(str))),    # to original form
         'AgentID': list,
         'CaseID': 'first',
         'TicketID': 'first',
        })
   .astype(df.dtypes)                                         # original dtypes
)

output:

        CommentsID    AgentID  CaseID  TicketID
0  ['0', '4', '2']  [1, 2, 5]       2       3.0
1       ['6', '7']     [3, 8]       6       5.0
2            ['9']        [9]       9       9.0

In case you want "real" anonymization, you could use a uuid:

from uuid import uuid4

def df_uuid(df):
    idx = df.index
    s = df.reset_index(drop=True).stack()
    f = s.unique()
    s = s.map(dict(zip(f, [str(uuid4()) for _ in range(len(f))])))
    return s.unstack().set_index(idx)

output:

                                                                                CommentsID                                                                                AgentID                                CaseID                              TicketID
0  ['e9fa80ed-58e2-4a96-a8da-0bc0c3a87e14', 'c87ca55a-e0a4-4618-ab5a-2eaf68d5a70f', '7cba72a8-3f2a-42e7-a781-b8ed242ea2ac']  [65f95f56-877e-4a9f-be88-4302fe1f77ea, 7cba72a8-3f2a-42e7-a781-b8ed242ea2ac, 3cf48cd7-e1b0-4c7f-bbeb-41836e309511]  7cba72a8-3f2a-42e7-a781-b8ed242ea2ac  549f1768-39b5-4e74-a8dd-4edbf3bb591f
1                                          ['6e54d7d6-ae2f-4319-950e-7629128d518a', '8fef2e1c-99d1-4460-b8a4-f4dbbf213c5f']                                        [549f1768-39b5-4e74-a8dd-4edbf3bb591f, 98f82da0-fa9c-447a-943b-b11875736128]  6e54d7d6-ae2f-4319-950e-7629128d518a  3cf48cd7-e1b0-4c7f-bbeb-41836e309511
2                                                                                ['3396c9db-1244-4b2d-bb76-14bb0221778f']                                                                              [3396c9db-1244-4b2d-bb76-14bb0221778f]  3396c9db-1244-4b2d-bb76-14bb0221778f  3396c9db-1244-4b2d-bb76-14bb0221778f


问:
postgres, ubuntu how to restart service on startup? get stuck on clustering after instance reboot
I have a Postgres db 9.1 running on AWS EC2, with ubuntu 12.04.

I messed a lot with the instance (i.e installed all kinds of postgres X.X before i settled on 9.1).

Now after a month working on that db, I discovered that if I restart my instance postgres doesn't load correctly, its status says "Running clusters". this will last forever until I

```<code>sudo service postgresql restart
</code>```

from terminal, and then it works again.

How do I add this line, to ubuntu startup so that each time it loads, it will restart this service, and hopefully solve my problem?

Also any other solution which might solve this.

答:
for ubuntu startup so that each time it loads, it will restart this service of Postgres on startup so that you won't have to restart it all the time</p>
```<code>sudo update-rc.d postgresql enable
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a Postgres db 9.1 running on AWS EC2, with ubuntu 12.04.

I messed a lot with the instance (i.e installed all kinds of postgres X.X before i settled on 9.1).

Now after a month working on that db, I discovered that if I restart my instance postgres doesn't load correctly, its status says "Running clusters". this will last forever until I

sudo service postgresql restart

from terminal, and then it works again.

How do I add this line, to ubuntu startup so that each time it loads, it will restart this service, and hopefully solve my problem?

Also any other solution which might solve this.

Body:
for ubuntu startup so that each time it loads, it will restart this service of Postgres on startup so that you won't have to restart it all the time

sudo update-rc.d postgresql enable


问:
TSQL, counting coherent days of holiday
I hope someone can help me on this one. :-)

I wish to count coherent periods of holiday to see if anyone had coherent holiday more than three days in a row. In other words it is not enough to count the number of days overall. The days have to be coherent. In the example of my data below I have illustrated three people with each their own days of holiday. Person 1234 has two periods of two days of holiday in a row, so this person has no periods above three days since there is a day in between two periods (the 3rd). Person 1235 and 1236 each have one period above three days. Time of day in the timestamps has no relevance, so data can be formatted as just date.

What I have:

ID
Start

1234
2022-01-01 00:00:00

1234
2022-01-02 00:00:00

1234
2022-01-04 06:50:00

1234
2022-01-05 06:50:00

1235
2022-01-04 06:50:00

1235
2022-01-05 06:50:00

1235
2022-01-06 00:00:00

1236
2022-01-01 00:00:00

1236
2022-01-02 00:00:00

1236
2022-01-03 06:50:00

1236
2022-01-04 06:50:00

1236
2022-01-05 06:50:00

1236
2022-01-08 00:00:00

What I hope to get:

ID
N holidays > 3 days

1234
0

1235
1

1236
1

Anyways, any help will be appreciated!

Kind regards,

Jacob

答:
This is a "gaps and islands" problem. You need to first group the data into "islands", which in your case is groups of consecutive holidays. Then summarize them in your final result set

Side note: your question requests greater than 3 days, but your expected output uses greater than or equal to 3 so I used that instead.

```<code>DROP TABLE IF EXISTS #Holiday;
DROP TABLE IF EXISTS #ConsecutiveHoliday
CREATE TABLE #Holiday (ID INT,StartDateTime DATETIME)
INSERT INTO #Holiday
VALUES (1234,'2022-01-01 00:00:00')
,(1234,'2022-01-02 00:00:00')
,(1234,'2022-01-04 06:50:00')
,(1234,'2022-01-05 06:50:00')
,(1235,'2022-01-04 06:50:00')
,(1235,'2022-01-05 06:50:00')
,(1235,'2022-01-06 00:00:00')
,(1236,'2022-01-01 00:00:00')
,(1236,'2022-01-02 00:00:00')
,(1236,'2022-01-03 06:50:00')
,(1236,'2022-01-04 06:50:00')
,(1236,'2022-01-05 06:50:00')
,(1236,'2022-01-08 00:00:00');

WITH cte_Previous AS (
    SELECT A.ID,B.StartDate
        ,IsHolidayConsecutive = CASE WHEN DATEADD(day,-1,StartDate) /*Current day minus 1*/ = LAG(StartDate) OVER (PARTITION BY ID ORDER BY StartDate) /*Previous holiday date*/
            THEN 0
            ELSE 1
        END
    FROM #Holiday AS A
    CROSS APPLY (SELECT StartDate = CAST(StartDateTime AS DATE)) AS B
),
cte_Groups AS (
    SELECT *,GroupID = SUM(IsHolidayConsecutive) OVER (PARTITION BY ID ORDER BY StartDate)
    FROM cte_Previous
)
/*Groups of holidays taken consecutively*/
SELECT ID
    ,StartDate = MIN(StartDate)
    ,EndDate = MAX(StartDate)
    ,NumOfDays = COUNT(*)
INTO #ConsecutiveHoliday
FROM cte_Groups
GROUP BY ID,GroupID
ORDER BY ID,StartDate

/*See list of consecutive holidays taken*/
SELECT *
FROM #ConsecutiveHoliday

/*Formatted result*/
SELECT ID
    ,[N holidays >= 3 days] = COUNT(CASE WHEN NumOfDays >= 3 THEN 1 END)
FROM #ConsecutiveHoliday
GROUP BY ID
</code>```

Title: TSQL, counting coherent days of holiday

Body:
This is a "gaps and islands" problem. You need to first group the data into "islands", which in your case is groups of consecutive holidays. Then summarize them in your final result set

Side note: your question requests greater than 3 days, but your expected output uses greater than or equal to 3 so I used that instead.

DROP TABLE IF EXISTS #Holiday;
DROP TABLE IF EXISTS #ConsecutiveHoliday
CREATE TABLE #Holiday (ID INT,StartDateTime DATETIME)
INSERT INTO #Holiday
VALUES (1234,'2022-01-01 00:00:00')
,(1234,'2022-01-02 00:00:00')
,(1234,'2022-01-04 06:50:00')
,(1234,'2022-01-05 06:50:00')
,(1235,'2022-01-04 06:50:00')
,(1235,'2022-01-05 06:50:00')
,(1235,'2022-01-06 00:00:00')
,(1236,'2022-01-01 00:00:00')
,(1236,'2022-01-02 00:00:00')
,(1236,'2022-01-03 06:50:00')
,(1236,'2022-01-04 06:50:00')
,(1236,'2022-01-05 06:50:00')
,(1236,'2022-01-08 00:00:00');

WITH cte_Previous AS (
    SELECT A.ID,B.StartDate
        ,IsHolidayConsecutive = CASE WHEN DATEADD(day,-1,StartDate) /*Current day minus 1*/ = LAG(StartDate) OVER (PARTITION BY ID ORDER BY StartDate) /*Previous holiday date*/
            THEN 0
            ELSE 1
        END
    FROM #Holiday AS A
    CROSS APPLY (SELECT StartDate = CAST(StartDateTime AS DATE)) AS B
),
cte_Groups AS (
    SELECT *,GroupID = SUM(IsHolidayConsecutive) OVER (PARTITION BY ID ORDER BY StartDate)
    FROM cte_Previous
)
/*Groups of holidays taken consecutively*/
SELECT ID
    ,StartDate = MIN(StartDate)
    ,EndDate = MAX(StartDate)
    ,NumOfDays = COUNT(*)
INTO #ConsecutiveHoliday
FROM cte_Groups
GROUP BY ID,GroupID
ORDER BY ID,StartDate

/*See list of consecutive holidays taken*/
SELECT *
FROM #ConsecutiveHoliday

/*Formatted result*/
SELECT ID
    ,[N holidays >= 3 days] = COUNT(CASE WHEN NumOfDays >= 3 THEN 1 END)
FROM #ConsecutiveHoliday
GROUP BY ID


问:
fire an event programatically every some seconds using socket.io
My server wants to say "hi" to the clients every interval of time. I have this example of code to demonstrate the event firing according to interval of time.
But sadly it is not working.

server :

```<code>    var app = require('http').createServer(handler),
     io = require('socket.io').listen(app),
     fs = require('fs');

    app.listen(8001);

     function handler(req, res) {
     fs.readFile(__dirname + '/client1.html', function(err, data) {
      if (err) {
      console.log(err);
      res.writeHead(500);
      return res.end('Error loading client1.html');
    }
    res.writeHead(200);
      res.end(data);
    });
  }

  io.sockets.on('connection', function (socket) {
    console.log("runing time");

    socket.emit( "clientMessage","hi from server");
    socket.on('clientMessage', function () {
        socket.emit( "serverMessage","hi from server");
    });
    socket.on('disconnect', function () {
        console.log("disconnecting");
    });
  });
</code>```

Client :

```<code>   <script src="/socket.io/socket.io.js"></script>

   <script>
   var socket = io.connect("http://localhost:8001");
   socket.on('connection', function(socket) {

       // *this line is not reached*
        alert("connected")

      sendTestMessage()

    socket.on("serverMessage", function(d) {
        alert("server Message : " + d)
    })
    socket.on('disconnect', function() {
        alert("disconnected")
    });

   });

   function sendTestMessage() {
    alert("test")
    socket.emit('clientMessage', "Test Message From Client");
    setTimeout(sendTestMessage(), 5000)
   }

  </script>
</code>```

Please any help why ?

答:
events on server side and client side should be same.
you should try this
server.js:

```<code>io.on('connection', function (socket) {
console.log("runing time");

setInterval(()=>{
socket.emit("clientMessage","hi from server")
}, 1000)

socket.on('disconnect', function () {
    console.log("disconnecting");
});
</code>```

client.js:

```<code>socket.on('connect',()=>{console.log('socket connected')});

socket.on('disconnect',()=>{console.log('socket disconnected')});

socket.on('clientMessage', (msg)=>{
   console.log('Message From Server: ', msg)
});
</code>```

this will emit message from server after every second to client.

Body:
My server wants to say "hi" to the clients every interval of time. I have this example of code to demonstrate the event firing according to interval of time.
But sadly it is not working.

server :

    var app = require('http').createServer(handler),
     io = require('socket.io').listen(app),
     fs = require('fs');

    app.listen(8001);

     function handler(req, res) {
     fs.readFile(__dirname + '/client1.html', function(err, data) {
      if (err) {
      console.log(err);
      res.writeHead(500);
      return res.end('Error loading client1.html');
    }
    res.writeHead(200);
      res.end(data);
    });
  }

  io.sockets.on('connection', function (socket) {
    console.log("runing time");

    socket.emit( "clientMessage","hi from server");
    socket.on('clientMessage', function () {
        socket.emit( "serverMessage","hi from server");
    });
    socket.on('disconnect', function () {
        console.log("disconnecting");
    });
  });

Client :

Please any help why ?

Body:
events on server side and client side should be same.
you should try this
server.js:

io.on('connection', function (socket) {
console.log("runing time");

setInterval(()=>{
socket.emit("clientMessage","hi from server")
}, 1000)

socket.on('disconnect', function () {
    console.log("disconnecting");
});

client.js:

socket.on('connect',()=>{console.log('socket connected')});

socket.on('disconnect',()=>{console.log('socket disconnected')});

socket.on('clientMessage', (msg)=>{
   console.log('Message From Server: ', msg)
});

this will emit message from server after every second to client.


问:
Failed to construct Notification: Illegal constructor
My site uses desktop notifications which have never worked on mobile devices but I've recently started to receive the following exception in Chrome Version 42.0.2311.108 on Android 4.4:

```<code>Failed to construct 'Notification': Illegal constructor. Use ServiceWorkerRegistration.showNotification() instead. TypeError: Failed to construct 'Notification': Illegal constructor. Use ServiceWorkerRegistration.showNotification() instead.
</code>```

My notification code is simple, after checking if the user has granted permissions I initialize a new Notification object as follows:

```<code>var notification = new Notification(messageOptions.title, { icon: messageOptions.icon });
</code>```

How do I change this code to use the ServiceWorkerRegistration.showNotification, which comes up as undefined, to support notifications in the mobile version of Chrome or if that isn't possible do a feature detection and prevent the exceptions from happening if this really isn't supported [yet].

答:
According to this:

Note: Trying to create a notification inside the ServiceWorkerGlobalScope using the Notification() constructor will throw an error.

If you want to send notification in a Service Worker, use self.registration.showNotification(). See https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/showNotification

Body:
My site uses desktop notifications which have never worked on mobile devices but I've recently started to receive the following exception in Chrome Version 42.0.2311.108 on Android 4.4:

Failed to construct 'Notification': Illegal constructor. Use ServiceWorkerRegistration.showNotification() instead. TypeError: Failed to construct 'Notification': Illegal constructor. Use ServiceWorkerRegistration.showNotification() instead.

My notification code is simple, after checking if the user has granted permissions I initialize a new Notification object as follows:

var notification = new Notification(messageOptions.title, { icon: messageOptions.icon });

How do I change this code to use the ServiceWorkerRegistration.showNotification, which comes up as undefined, to support notifications in the mobile version of Chrome or if that isn't possible do a feature detection and prevent the exceptions from happening if this really isn't supported [yet].


问:
How to use \COPY command inside a function in PostgreSQL
I want to export the table into a .CSV file using \COPY command. I can able to do that as a stand-alone command. I can't embed the same line inside a function in PostgreSQL. Actually that call should come from a ECPG. I chose \COPY over COPY command as I don't have super-user account! Please guide me on this.

Thanks and Regards,
Siva.

答:
If you are talking about using copy with plpgsql, I think this might help:

Dynamically-generated table-name in PostgreSQL COPY command


问:
can not have consistent point size in geom_size (in ggplot)
I have two dataset and produce bubble chart with ggplot. when I want to scale the point size, they do not stay consistent. for example circle with count of 3 is bigger thant ciricle with count size of 3 in df_table1.

```<code>df_table1:

         Raw.data temporal.technique Counts
         LMSdata         clustering      3
         LMSdata                 PM      3
         LMSdata      visualization      3
     custLogData               stat      2
    learningProd               stat      2
    perfMeasures      visualization      2
      contextual         clustering      1
      contextual            network      1
      contextual         TextMining      1
     custLogData          otherPred      1

df_table2:

         Raw.data temporal.technique Counts
         LMSdata         clustering      15
         LMSdata      visualization      8
     custLogData               stat      7
    learningProd               stat      4
    perfMeasures      visualization      3
     contextual         clustering      1
     contextual            network      1

</code>```

I tried this code but did not make point sizes consistent. using fix number like scale_size(range = c(1, 10) did not work either.

```<code>ggplot(df_table, aes(x=df_table[,1], y=df_table[,2], size = Counts)) +
    geom_text(data=df_table,aes(x=df_table[,1], y=df_table[,2],label= Counts,size=1.5))+
    scale_size(range = c(1, max(df_table$Counts)))
</code>```

答:
Does this approach solve your problem?

library(tidyverse)

df_table1 <- read.table(text = "         Raw.data temporal.technique Counts
         LMSdata         clustering      3
         LMSdata                 PM      3
         LMSdata      visualization      3
     custLogData               stat      2
    learningProd               stat      2
    perfMeasures      visualization      2
      contextual         clustering      1
      contextual            network      1
      contextual         TextMining      1
     custLogData          otherPred      1", header = TRUE)

df_table2 <- read.table(text = "         Raw.data temporal.technique Counts
         LMSdata         clustering      15
         LMSdata      visualization      8
     custLogData               stat      7
    learningProd               stat      4
    perfMeasures      visualization      3
     contextual         clustering      1
     contextual            network      1", header = TRUE)

# Combine df_table1 and df_table2 to a single df
df_table <- map_df(.x = list("df_table1" = df_table1,
                             "df_table2" = df_table2),
                   .f = bind_rows,
                   .id = "src")

# Plot them side-by-side using `facet_wrap()`
ggplot(df_table, aes(x=Raw.data, y=temporal.technique, size = Counts)) +
  geom_text(aes(label = Counts)) +
  scale_size(range = c(1, 10)) +
  facet_wrap(~src)
```

Created on 2022-02-08 by the reprex package (v2.0.1)

Body:
I have two dataset and produce bubble chart with ggplot. when I want to scale the point size, they do not stay consistent. for example circle with count of 3 is bigger thant ciricle with count size of 3 in df_table1.

df_table1:

         Raw.data temporal.technique Counts
         LMSdata         clustering      3
         LMSdata                 PM      3
         LMSdata      visualization      3
     custLogData               stat      2
    learningProd               stat      2
    perfMeasures      visualization      2
      contextual         clustering      1
      contextual            network      1
      contextual         TextMining      1
     custLogData          otherPred      1

df_table2:

         Raw.data temporal.technique Counts
         LMSdata         clustering      15
         LMSdata      visualization      8
     custLogData               stat      7
    learningProd               stat      4
    perfMeasures      visualization      3
     contextual         clustering      1
     contextual            network      1

I tried this code but did not make point sizes consistent. using fix number like scale_size(range = c(1, 10) did not work either.

ggplot(df_table, aes(x=df_table[,1], y=df_table[,2], size = Counts)) +
    geom_text(data=df_table,aes(x=df_table[,1], y=df_table[,2],label= Counts,size=1.5))+
    scale_size(range = c(1, max(df_table$Counts)))

Body:
Does this approach solve your problem?

library(tidyverse)

df_table1 <- read.table(text = "         Raw.data temporal.technique Counts
         LMSdata         clustering      3
         LMSdata                 PM      3
         LMSdata      visualization      3
     custLogData               stat      2
    learningProd               stat      2
    perfMeasures      visualization      2
      contextual         clustering      1
      contextual            network      1
      contextual         TextMining      1
     custLogData          otherPred      1", header = TRUE)

df_table2 <- read.table(text = "         Raw.data temporal.technique Counts
         LMSdata         clustering      15
         LMSdata      visualization      8
     custLogData               stat      7
    learningProd               stat      4
    perfMeasures      visualization      3
     contextual         clustering      1
     contextual            network      1", header = TRUE)

# Combine df_table1 and df_table2 to a single df
df_table <- map_df(.x = list("df_table1" = df_table1,
                             "df_table2" = df_table2),
                   .f = bind_rows,
                   .id = "src")

# Plot them side-by-side using `facet_wrap()`
ggplot(df_table, aes(x=Raw.data, y=temporal.technique, size = Counts)) +
  geom_text(aes(label = Counts)) +
  scale_size(range = c(1, 10)) +
  facet_wrap(~src)

Created on 2022-02-08 by the reprex package (v2.0.1)


问:
How to create a widget for window 10 and 11 using dotnet 6
I want to create a widget to show some information to users to businesses regarding information and the widget should look like as attached screenshot. It should behave like start on startup and like widget is running but there is not any property in the taskbar for it

I want to use dotnet6 for that

答:
If you are looking for a personal widget to display system info, like seen in the screenshot. Try using this program called Rainmeter. There are lots of documentation to help create your own Rainmeter widget too.

If you are looking to create your own widget using dotnet6 you can create a windows form application normally but add something like this this.ShowInTaskbar = false; in your form_Load event function as seen here.

Here is some more information on that code I gave.

Here is some more information on how to create a windows form application.

To get your program to startup on computer start, place a shortcut to your program here C:\Users\[User Name]\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
More information on this startup location here.


问:
What is the logic behind this fstring in python?
From this question: Converting an integer to signed 2's complement binary string

we have this code:

```<code>def f(n):
    nbits = n.bit_length() + 1
    return f"{n & ((1 << nbits) - 1):0{nbits}b}"
</code>```

I'm looking for some explanation/reference reading on the f string. In particular, what is the purpose of the :, the 0{...} syntax and the b?

答:
: separates the value to be printed from the format specification.

In a format specification, the last character specifies the type of formatting; in this case, b means binary. A number before that specifies the field with; in this case it's the value of the nbits variable (nested {expression} are expanded and used as part of the format specification). And a leading zero before the field width means to padd with zeroes.

So this prints (1 << nbits) - 1 in binary in a field that's nbits wide with leading zeroes.

The leading zeroes in the specification don't seem relevant, because the value being printed will be nbits 1's -- there won't be any need for padding.

Body:
From this question: Converting an integer to signed 2's complement binary string

we have this code:

def f(n):
    nbits = n.bit_length() + 1
    return f"{n & ((1 << nbits) - 1):0{nbits}b}"

I'm looking for some explanation/reference reading on the f string. In particular, what is the purpose of the :, the 0{...} syntax and the b?


问:
Animation.save does not save all frames in matplotlib
I have the following code to animate plot:

```<code># Creating the Animation object
line_ani = animation.FuncAnimation(fig, update, frames=generate(), fargs=(lines,),
                                   interval=5, blit=False)

#plt.show()
line_ani.save("animation.mp4")
</code>```

generate function yields data and update function set this data onto the plot.

When I run this script with plt.show() I see very slow and long animation.

When I run this script with line_ani.save("animation.mp4") it ends very soon and produces very short animation inside mp4 file.

Why and how to fix?

UPDATE

Although script runs without any errors, PyCharms is reporting a warning:

Expected type 'Optional[int]', got 'Generator[...

答: I had the same issue - you can fix it by supplying the 'FuncAnimation' function with a 'save_count' argument, which tells the function the number of frames it should save (i.e., the number of frames you want to animate). I don't know why this argument is in the 'FuncAnimation' and not in the .save() method...</p>

Body:
I have the following code to animate plot:

# Creating the Animation object
line_ani = animation.FuncAnimation(fig, update, frames=generate(), fargs=(lines,),
                                   interval=5, blit=False)

#plt.show()
line_ani.save("animation.mp4")

generate function yields data and update function set this data onto the plot.

When I run this script with plt.show() I see very slow and long animation.

When I run this script with line_ani.save("animation.mp4") it ends very soon and produces very short animation inside mp4 file.

Why and how to fix?

UPDATE

Although script runs without any errors, PyCharms is reporting a warning:

Expected type 'Optional[int]', got 'Generator[...


问:
django : __str__ returned non-string (type NoneType), only when __str__ defined
I knew there is tons of post regarding this error.
I think what I got is pretty strange.

Ok here it is.

models.py

```<code>class Axie(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=30, blank=True, null=True)
    sire = models.ForeignKey("Axie", related_name= "mysire", blank=True, null=True, on_delete=models.SET_NULL)
    matron = models.ForeignKey("Axie", related_name= "mymatron", blank=True, null=True, on_delete=models.SET_NULL)
    scholar= models.ForeignKey(Scholar,null=True, blank=True, on_delete=models.SET_NULL)

    def __str__(self):
        return self.name

</code>```

With that code, I got a normal basic list as usual

But I got error on every 'change view'

This is the traceback from debug page

```<code>Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/admin/university/axie/10277276/change/

Django Version: 4.0.2
Python Version: 3.8.10
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'university.apps.UniversityConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Template error:
In template /home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/contrib/admin/templates/admin/includes/fieldset.html, error at line 19
   __str__ returned non-string (type NoneType)
   9 :             {% for field in line %}
   10 :                 <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}>
   11 :                     {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %}
   12 :                     {% if field.is_checkbox %}
   13 :                         {{ field.field }}{{ field.label_tag }}
   14 :                     {% else %}
   15 :                         {{ field.label_tag }}
   16 :                         {% if field.is_readonly %}
   17 :                             <div class="readonly">{{ field.contents }}</div>
   18 :                         {% else %}
   19 :                              {{ field.field }}
   20 :                         {% endif %}
   21 :                     {% endif %}
   22 :                     {% if field.field.help_text %}
   23 :                         <div class="help">{{ field.field.help_text|safe }}</div>
   24 :                     {% endif %}
   25 :                 </div>
   26 :             {% endfor %}
   27 :         </div>
   28 :     {% endfor %}
   29 : </fieldset>

Traceback (most recent call last):
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/core/handlers/base.py", line 204, in _get_response
    response = response.render()
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/response.py", line 105, in render
    self.content = self.rendered_content
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/response.py", line 83, in rendered_content
    return template.render(context, self._request)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 176, in render
    return self._render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 168, in _render
    return self.nodelist.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 977, in render
    return SafeString(''.join([
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 978, in <listcomp>
    node.render_annotated(context) for node in self
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 938, in render_annotated
    return self.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/loader_tags.py", line 153, in render
    return compiled_parent._render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 168, in _render
    return self.nodelist.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 977, in render
    return SafeString(''.join([
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 978, in <listcomp>
    node.render_annotated(context) for node in self
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 938, in render_annotated
    return self.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/loader_tags.py", line 153, in render
    return compiled_parent._render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 168, in _render
    return self.nodelist.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 977, in render
    return SafeString(''.join([
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 978, in <listcomp>
    node.render_annotated(context) for node in self
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 938, in render_annotated
    return self.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/loader_tags.py", line 65, in render
    result = block.nodelist.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 977, in render
    return SafeString(''.join([
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 978, in <listcomp>
    node.render_annotated(context) for node in self
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 938, in render_annotated
    return self.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/loader_tags.py", line 65, in render
    result = block.nodelist.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 977, in render
    return SafeString(''.join([
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 978, in <listcomp>
    node.render_annotated(context) for node in self
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 938, in render_annotated
    return self.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/defaulttags.py", line 217, in render
    nodelist.append(node.render_annotated(context))
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 938, in render_annotated
    return self.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/loader_tags.py", line 201, in render
    return template.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 178, in render
    return self._render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 168, in _render
    return self.nodelist.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 977, in render
    return SafeString(''.join([
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 978, in <listcomp>
    node.render_annotated(context) for node in self
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 938, in render_annotated
    return self.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/defaulttags.py", line 217, in render
    nodelist.append(node.render_annotated(context))
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 938, in render_annotated
    return self.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/defaulttags.py", line 217, in render
    nodelist.append(node.render_annotated(context))
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 938, in render_annotated
    return self.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/defaulttags.py", line 298, in render
    return nodelist.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 977, in render
    return SafeString(''.join([
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 978, in <listcomp>
    node.render_annotated(context) for node in self
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 938, in render_annotated
    return self.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/defaulttags.py", line 298, in render
    return nodelist.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 977, in render
    return SafeString(''.join([
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 978, in <listcomp>
    node.render_annotated(context) for node in self
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 938, in render_annotated
    return self.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 1044, in render
    return render_value_in_context(output, context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 1021, in render_value_in_context
    value = str(value)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/utils/html.py", line 377, in <lambda>
    klass.__str__ = lambda self: mark_safe(klass_str(self))
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/forms/boundfield.py", line 33, in __str__
    return self.as_widget()
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/forms/boundfield.py", line 92, in as_widget
    return widget.render(
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/forms/widgets.py", line 246, in render
    context = self.get_context(name, value, attrs)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/contrib/admin/widgets.py", line 283, in get_context
    'rendered_widget': self.widget.render(name, value, attrs),
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/forms/widgets.py", line 246, in render
    context = self.get_context(name, value, attrs)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/forms/widgets.py", line 681, in get_context
    context = super().get_context(name, value, attrs)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/forms/widgets.py", line 642, in get_context
    context['widget']['optgroups'] = self.optgroups(name, context['widget']['value'], attrs)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/forms/widgets.py", line 592, in optgroups
    for index, (option_value, option_label) in enumerate(self.choices):
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/forms/models.py", line 1191, in __iter__
    yield self.choice(obj)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/forms/models.py", line 1205, in choice
    self.field.label_from_instance(obj),
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/forms/models.py", line 1274, in label_from_instance
    return str(obj)

Exception Type: TypeError at /admin/university/axie/10277276/change/
Exception Value: __str__ returned non-string (type NoneType)
</code>```

Next, I remove the 'def str(self)' part,

```<code>class Axie(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=30, blank=True, null=True)
    sire = models.ForeignKey("Axie", related_name= "mysire", blank=True, null=True, on_delete=models.SET_NULL)
    matron = models.ForeignKey("Axie", related_name= "mymatron", blank=True, null=True, on_delete=models.SET_NULL)
    scholar= models.ForeignKey(Scholar,null=True, blank=True, on_delete=models.SET_NULL)

</code>```

As expected, the list view do not show the name,

But Got 'nice' change view

Kindly please give me any clue to fix this problem.

Sincerely

-bino-

答:
Use this</p>
```<code>def __str__(self):
    return "%s"%self.name
</code>```

Body:
I knew there is tons of post regarding this error.
I think what I got is pretty strange.

Ok here it is.

models.py

class Axie(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=30, blank=True, null=True)
    sire = models.ForeignKey("Axie", related_name= "mysire", blank=True, null=True, on_delete=models.SET_NULL)
    matron = models.ForeignKey("Axie", related_name= "mymatron", blank=True, null=True, on_delete=models.SET_NULL)
    scholar= models.ForeignKey(Scholar,null=True, blank=True, on_delete=models.SET_NULL)

    def __str__(self):
        return self.name

With that code, I got a normal basic list as usual

But I got error on every 'change view'

This is the traceback from debug page

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/admin/university/axie/10277276/change/

Django Version: 4.0.2
Python Version: 3.8.10
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'university.apps.UniversityConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Template error:
In template /home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/contrib/admin/templates/admin/includes/fieldset.html, error at line 19
   __str__ returned non-string (type NoneType)
   9 :             {% for field in line %}
   10 :

   11 :                     {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %}
   12 :                     {% if field.is_checkbox %}
   13 :                         {{ field.field }}{{ field.label_tag }}
   14 :                     {% else %}
   15 :                         {{ field.label_tag }}
   16 :                         {% if field.is_readonly %}
   17 :
{{ field.contents }}

   18 :                         {% else %}
   19 :                              {{ field.field }}
   20 :                         {% endif %}
   21 :                     {% endif %}
   22 :                     {% if field.field.help_text %}
   23 :
{{ field.field.help_text|safe }}

   24 :                     {% endif %}
   25 :

   26 :             {% endfor %}
   27 :

   28 :     {% endfor %}
   29 : </fieldset>

Traceback (most recent call last):
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/core/handlers/base.py", line 204, in _get_response
    response = response.render()
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/response.py", line 105, in render
    self.content = self.rendered_content
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/response.py", line 83, in rendered_content
    return template.render(context, self._request)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 176, in render
    return self._render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 168, in _render
    return self.nodelist.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 977, in render
    return SafeString(''.join([
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 978, in <listcomp>
    node.render_annotated(context) for node in self
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 938, in render_annotated
    return self.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/loader_tags.py", line 153, in render
    return compiled_parent._render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 168, in _render
    return self.nodelist.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 977, in render
    return SafeString(''.join([
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 978, in <listcomp>
    node.render_annotated(context) for node in self
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 938, in render_annotated
    return self.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/loader_tags.py", line 153, in render
    return compiled_parent._render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 168, in _render
    return self.nodelist.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 977, in render
    return SafeString(''.join([
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 978, in <listcomp>
    node.render_annotated(context) for node in self
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 938, in render_annotated
    return self.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/loader_tags.py", line 65, in render
    result = block.nodelist.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 977, in render
    return SafeString(''.join([
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 978, in <listcomp>
    node.render_annotated(context) for node in self
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 938, in render_annotated
    return self.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/loader_tags.py", line 65, in render
    result = block.nodelist.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 977, in render
    return SafeString(''.join([
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 978, in <listcomp>
    node.render_annotated(context) for node in self
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 938, in render_annotated
    return self.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/defaulttags.py", line 217, in render
    nodelist.append(node.render_annotated(context))
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 938, in render_annotated
    return self.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/loader_tags.py", line 201, in render
    return template.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 178, in render
    return self._render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 168, in _render
    return self.nodelist.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 977, in render
    return SafeString(''.join([
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 978, in <listcomp>
    node.render_annotated(context) for node in self
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 938, in render_annotated
    return self.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/defaulttags.py", line 217, in render
    nodelist.append(node.render_annotated(context))
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 938, in render_annotated
    return self.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/defaulttags.py", line 217, in render
    nodelist.append(node.render_annotated(context))
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 938, in render_annotated
    return self.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/defaulttags.py", line 298, in render
    return nodelist.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 977, in render
    return SafeString(''.join([
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 978, in <listcomp>
    node.render_annotated(context) for node in self
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 938, in render_annotated
    return self.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/defaulttags.py", line 298, in render
    return nodelist.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 977, in render
    return SafeString(''.join([
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 978, in <listcomp>
    node.render_annotated(context) for node in self
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 938, in render_annotated
    return self.render(context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 1044, in render
    return render_value_in_context(output, context)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/template/base.py", line 1021, in render_value_in_context
    value = str(value)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/utils/html.py", line 377, in <lambda>
    klass.__str__ = lambda self: mark_safe(klass_str(self))
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/forms/boundfield.py", line 33, in __str__
    return self.as_widget()
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/forms/boundfield.py", line 92, in as_widget
    return widget.render(
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/forms/widgets.py", line 246, in render
    context = self.get_context(name, value, attrs)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/contrib/admin/widgets.py", line 283, in get_context
    'rendered_widget': self.widget.render(name, value, attrs),
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/forms/widgets.py", line 246, in render
    context = self.get_context(name, value, attrs)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/forms/widgets.py", line 681, in get_context
    context = super().get_context(name, value, attrs)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/forms/widgets.py", line 642, in get_context
    context['widget']['optgroups'] = self.optgroups(name, context['widget']['value'], attrs)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/forms/widgets.py", line 592, in optgroups
    for index, (option_value, option_label) in enumerate(self.choices):
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/forms/models.py", line 1191, in __iter__
    yield self.choice(obj)
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/forms/models.py", line 1205, in choice
    self.field.label_from_instance(obj),
  File "/home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/forms/models.py", line 1274, in label_from_instance
    return str(obj)

Exception Type: TypeError at /admin/university/axie/10277276/change/
Exception Value: __str__ returned non-string (type NoneType)

Next, I remove the 'def str(self)' part,

class Axie(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=30, blank=True, null=True)
    sire = models.ForeignKey("Axie", related_name= "mysire", blank=True, null=True, on_delete=models.SET_NULL)
    matron = models.ForeignKey("Axie", related_name= "mymatron", blank=True, null=True, on_delete=models.SET_NULL)
    scholar= models.ForeignKey(Scholar,null=True, blank=True, on_delete=models.SET_NULL)

As expected, the list view do not show the name,

But Got 'nice' change view

Kindly please give me any clue to fix this problem.

Sincerely

-bino-

Body:
Use this

def __str__(self):
    return "%s"%self.name


问:
android dynamic TableRow with doInBackground not working?
```<code>//////  SeatLayout.java ///////////

public class SeatLayoutActivity  extends Activity
{
    private TableLayout mineField; // table layout to add mines to

    private Block blocks[][]; // blocks for mine field
    private int blockDimension = 24; // width of each block
    private int blockPadding = 2; // padding between blocks

    private int numberOfRowsInMineField = 9;
    private int numberOfColumnsInMineField = 9;

    public ProgressDialog progressDialog;

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

         progressDialog = ProgressDialog.show(SeatLayoutActivity.this, "Getting data", "Loading...");
         new GetDataTask(SeatLayoutActivity.this).execute();

          setContentView(R.layout.seatlayout);
    }

     private Boolean isOnline() {
            ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo ni = cm.getActiveNetworkInfo();
            if(ni != null && ni.isConnected())
                return true;

            return false;
        }

     private class GetDataTask extends AsyncTask<Void, Void, Integer> {
         private Context ctx;
         public GetDataTask(Context context) {
             ctx = context;
         }

      @Override
      protected Integer doInBackground(Void... params) {

            if(isOnline()){

                mineField = (TableLayout)findViewById(R.id.MineField);
                blocks = new Block[numberOfRowsInMineField + 2][numberOfColumnsInMineField + 2];

                //in feature below table(number of rows and columns) will based on RESET service response

                for (int row = 0; row < numberOfRowsInMineField + 2; row++)
                {
                    for (int column = 0; column < numberOfColumnsInMineField + 2; column++)
                    {
                        blocks[row][column] = new Block(ctx);
                        blocks[row][column].setDefaults();

                    }
                }

                for (int row = 1; row < numberOfRowsInMineField + 1; row++)
                {
                    TableRow tableRow = new TableRow(ctx);
                    tableRow.setLayoutParams(new LayoutParams((blockDimension + 2 * blockPadding) * numberOfColumnsInMineField, blockDimension + 2 * blockPadding));

                    for (int column = 1; column < numberOfColumnsInMineField + 1; column++)
                    {
                        blocks[row][column].setLayoutParams(new LayoutParams(
                                blockDimension + 2 * blockPadding,
                                blockDimension + 2 * blockPadding));
                        blocks[row][column].setPadding(blockPadding, blockPadding, blockPadding, blockPadding);
                        tableRow.addView(blocks[row][column]);
                    }
                    mineField.addView(tableRow,new TableLayout.LayoutParams(
                            (blockDimension + 2 * blockPadding) * numberOfColumnsInMineField, blockDimension + 2 * blockPadding));
                }

            }else{
                Toast.makeText(SeatLayoutActivity.this, "No connection..", Toast.LENGTH_LONG).show();
            }

          return 1;
      }

      @Override
      protected void onPostExecute(Integer result) {

        progressDialog.dismiss();
          super.onPostExecute(result);
      }
  }
}

///Block.java

package com.pxr.tutorial.xmltest;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.Button;

public class Block extends Button
{
    private boolean isCovered; // is block covered yet
    private boolean isMined; // does the block has a mine underneath
    private boolean isFlagged; // is block flagged as a potential mine
    private boolean isQuestionMarked; // is block question marked
    private boolean isClickable; // can block accept click events
    private int numberOfMinesInSurrounding; // number of mines in nearby blocks

    public Block(Context context)
    {
        super(context);
    }

    public Block(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public Block(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }

    // set default properties for the block
    public void setDefaults()
    {
        isCovered = true;
        isMined = false;
        isFlagged = false;
        isQuestionMarked = false;
        isClickable = true;
        numberOfMinesInSurrounding = 0;

        this.setBackgroundResource(R.drawable.square_blue);
        setBoldFont();
    }

    // mark the block as disabled/opened
    // update the number of nearby mines
    public void setNumberOfSurroundingMines(int number)
    {
        this.setBackgroundResource(R.drawable.square_grey);

        updateNumber(number);
    }

    // set mine icon for block
    // set block as disabled/opened if false is passed
    public void setMineIcon(boolean enabled)
    {
        this.setText("M");

        if (!enabled)
        {
            this.setBackgroundResource(R.drawable.square_grey);
            this.setTextColor(Color.RED);
        }
        else
        {
            this.setTextColor(Color.BLACK);
        }
    }

    // set mine as flagged
    // set block as disabled/opened if false is passed
    public void setFlagIcon(boolean enabled)
    {
        this.setText("F");

        if (!enabled)
        {
            this.setBackgroundResource(R.drawable.square_grey);
            this.setTextColor(Color.RED);
        }
        else
        {
            this.setTextColor(Color.BLACK);
        }
    }

    // set mine as question mark
    // set block as disabled/opened if false is passed
    public void setQuestionMarkIcon(boolean enabled)
    {
        this.setText("?");

        if (!enabled)
        {
            this.setBackgroundResource(R.drawable.square_grey);
            this.setTextColor(Color.RED);
        }
        else
        {
            this.setTextColor(Color.BLACK);
        }
    }

    // set block as disabled/opened if false is passed
    // else enable/close it
    public void setBlockAsDisabled(boolean enabled)
    {
        if (!enabled)
        {
            this.setBackgroundResource(R.drawable.square_grey);
        }
        else
        {
            this.setBackgroundResource(R.drawable.square_blue);
        }
    }

    // clear all icons/text
    public void clearAllIcons()
    {
        this.setText("");
    }

    // set font as bold
    private void setBoldFont()
    {
        this.setTypeface(null, Typeface.BOLD);
    }

    // uncover this block
    public void OpenBlock()
    {
        // cannot uncover a mine which is not covered
        if (!isCovered)
            return;

        setBlockAsDisabled(false);
        isCovered = false;

        // check if it has mine
        if (hasMine())
        {
            setMineIcon(false);
        }
        // update with the nearby mine count
        else
        {
            setNumberOfSurroundingMines(numberOfMinesInSurrounding);
        }
    }

    // set text as nearby mine count
    public void updateNumber(int text)
    {
        if (text != 0)
        {
            this.setText(Integer.toString(text));

            // select different color for each number
            // we have already skipped 0 mine count
            switch (text)
            {
                case 1:
                    this.setTextColor(Color.BLUE);
                    break;
                case 2:
                    this.setTextColor(Color.rgb(0, 100, 0));
                    break;
                case 3:
                    this.setTextColor(Color.RED);
                    break;
                case 4:
                    this.setTextColor(Color.rgb(85, 26, 139));
                    break;
                case 5:
                    this.setTextColor(Color.rgb(139, 28, 98));
                    break;
                case 6:
                    this.setTextColor(Color.rgb(238, 173, 14));
                    break;
                case 7:
                    this.setTextColor(Color.rgb(47, 79, 79));
                    break;
                case 8:
                    this.setTextColor(Color.rgb(71, 71, 71));
                    break;
                case 9:
                    this.setTextColor(Color.rgb(205, 205, 0));
                    break;
            }
        }
    }

    // set block as a mine underneath
    public void plantMine()
    {
        isMined = true;
    }

    // mine was opened
    // change the block icon and color
    public void triggerMine()
    {
        setMineIcon(true);
        this.setTextColor(Color.RED);
    }

    // is block still covered
    public boolean isCovered()
    {
        return isCovered;
    }

    // does the block have any mine underneath
    public boolean hasMine()
    {
        return isMined;
    }

    // set number of nearby mines
    public void setNumberOfMinesInSurrounding(int number)
    {
        numberOfMinesInSurrounding = number;
    }

    // get number of nearby mines
    public int getNumberOfMinesInSorrounding()
    {
        return numberOfMinesInSurrounding;
    }

    // is block marked as flagged
    public boolean isFlagged()
    {
        return isFlagged;
    }

    // mark block as flagged
    public void setFlagged(boolean flagged)
    {
        isFlagged = flagged;
    }

    // is block marked as a question mark
    public boolean isQuestionMarked()
    {
        return isQuestionMarked;
    }

    // set question mark for the block
    public void setQuestionMarked(boolean questionMarked)
    {
        isQuestionMarked = questionMarked;
    }

    // can block receive click event
    public boolean isClickable()
    {
        return isClickable;
    }

    // disable block for receive click events
    public void setClickable(boolean clickable)
    {
        isClickable = clickable;
    }
}
</code>```

答: You mustn't modify and even access UI from non-UI thread. If you want to modify UI from AsyncTask.doInBackground() you should use Activity.runOnUiThread() or call AsyncTask.publishProgress() periodically and override AsyncTask.onProgressUpdate() method because it's executed on the main thread.


问:
How to i chain two parts of an animation together in jetpack compose so the the offset increases then decreases?
Ive recently got into doing animations using jet pack compose and am wondering how you can make it so that when you increase a value in an offset, once the animation reaches that value it then changes the value to another value. So like update transition but instead of at the same time, one after the other.</p>

答:
Actually @RaBaKa's answer is partially correct, but it's missing information about how the animation should be run.

It should be done as a side effect. For example, you can use LaunchedEffect: it is already running in a coroutine scope. It is perfectly normal to run one animation after another - as soon as the first suspend function finishes, the second will be started:

```<code>val value = remember { Animatable(0f) }
LaunchedEffect(Unit) {
    value.animateTo(
        20f,
        animationSpec = tween(2000),
    )
    value.animateTo(
        10f,
        animationSpec = tween(2000),
    )
}
Text(value.value.toString())
</code>```

If you want to do this in response to some action, such as pressing a button, you need to run the coroutine yourself. The main thing is to run the animations in the same coroutine so that they are chained.

```<code>val value = remember { Animatable(0f) }
val scope = rememberCoroutineScope()
Button(onClick = {
    scope.launch {
        value.animateTo(
            20f,
            animationSpec = tween(2000),
        )
        value.animateTo(
            10f,
            animationSpec = tween(2000),
        )
    }
}) {

}
Text(value.value.toString())
</code>```

Body:
Actually @RaBaKa's answer is partially correct, but it's missing information about how the animation should be run.

It should be done as a side effect. For example, you can use LaunchedEffect: it is already running in a coroutine scope. It is perfectly normal to run one animation after another - as soon as the first suspend function finishes, the second will be started:

val value = remember { Animatable(0f) }
LaunchedEffect(Unit) {
    value.animateTo(
        20f,
        animationSpec = tween(2000),
    )
    value.animateTo(
        10f,
        animationSpec = tween(2000),
    )
}
Text(value.value.toString())

If you want to do this in response to some action, such as pressing a button, you need to run the coroutine yourself. The main thing is to run the animations in the same coroutine so that they are chained.

val value = remember { Animatable(0f) }
val scope = rememberCoroutineScope()
Button(onClick = {
    scope.launch {
        value.animateTo(
            20f,
            animationSpec = tween(2000),
        )
        value.animateTo(
            10f,
            animationSpec = tween(2000),
        )
    }
}) {

}
Text(value.value.toString())


问:
Disable redirects in OkHttp3 for ONE request only
I have a singleton (object in Kotlin) that holds an instance of OkHttpClient which as per the search on stack is the way to go.

Now I come to the scenario where for just ONE request in my app I need to skip the redirect to get the Location header.

It seems that the way to do it is via

```<code>val client = OkHttpClient.Builder()
            .followRedirects(false)
            .followSslRedirects(false)
            .build()
</code>```

This is fine and dandy, but now I need to store two instances of OkHttpClient and the non-redirecting one is not even to be always used coz it pertains to a login flow for my app only.

Is it possible (e.g. via writing a network interceptor maybe?) to disable redirect for just ONE request?

答:
Per the docs, you should use one main instance, and then build customizations off of that base instance.

```<code>// renamed solely to make it clear what's going on below
val commonClient = OkHttpClient.Builder()
                   .followRedirects(true) // you can skip these calls, they are true by default
                   .followSslRedirects(true)
                   .build()
</code>```

Then later on, in your "do login" function, you'd create a fork of the base client. Under the hood, everything will still use commonClient but any requests made using this "new" client will use the settings you overrode. It's just a bit of an odd, roundabout syntax.

```<code>// fork the base instance
val noRedirectClient = commonClient.newBuilder()
                       .followRedirects(false) // override the previous/default settings used by commonClient
                       .followSslRedirects(false)
                       .build()

// make your request(s)

// don't shutdown noRedirectClient, because it would also shutdown the
// underlying commonClient instance because they share resources
</code>```

Body:
I have a singleton (object in Kotlin) that holds an instance of OkHttpClient which as per the search on stack is the way to go.

Now I come to the scenario where for just ONE request in my app I need to skip the redirect to get the Location header.

It seems that the way to do it is via

val client = OkHttpClient.Builder()
            .followRedirects(false)
            .followSslRedirects(false)
            .build()

This is fine and dandy, but now I need to store two instances of OkHttpClient and the non-redirecting one is not even to be always used coz it pertains to a login flow for my app only.

Is it possible (e.g. via writing a network interceptor maybe?) to disable redirect for just ONE request?

Body:
Per the docs, you should use one main instance, and then build customizations off of that base instance.

// renamed solely to make it clear what's going on below
val commonClient = OkHttpClient.Builder()
                   .followRedirects(true) // you can skip these calls, they are true by default
                   .followSslRedirects(true)
                   .build()

Then later on, in your "do login" function, you'd create a fork of the base client. Under the hood, everything will still use commonClient but any requests made using this "new" client will use the settings you overrode. It's just a bit of an odd, roundabout syntax.

// fork the base instance
val noRedirectClient = commonClient.newBuilder()
                       .followRedirects(false) // override the previous/default settings used by commonClient
                       .followSslRedirects(false)
                       .build()

// make your request(s)

// don't shutdown noRedirectClient, because it would also shutdown the
// underlying commonClient instance because they share resources