问:
How to solve Error when checking input: with incorrect size
This is my first attempt to solve task on the kaggle. This is page of the task - https://www.kaggle.com/c/bike-sharing-demand.
I wrote this code (I have some excess code lines, because I am not really sure what I need now):

```<code>import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import keras

import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
import matplotlib.pyplot as plt

import os
for dirname, _, filenames in os.walk('/kaggle/input'):
    for filename in filenames:
        print(os.path.join(dirname, filename))

train_data = pd.read_csv('/kaggle/input/bike-sharing-demand/train.csv')
train_targets = train_data[['casual', 'registered', 'count']]

train_datetime_helper = train_data[['datetime']]

dt = pd.DatetimeIndex(train_data['datetime'])
train_data['day'] = dt.day
train_data['month'] = dt.month
train_data['year'] = dt.year
train_data['hour'] = dt.hour
train_data['dow'] = dt.dayofweek
train_data['woy'] = dt.weekofyear

train_data = train_data.drop(['casual', 'registered', 'count', 'datetime'], axis=1)

test_data = pd.read_csv('/kaggle/input/bike-sharing-demand/test.csv')

test_datetime_helper = test_data[['datetime']]

dt = pd.DatetimeIndex(test_data['datetime'])

test_data['day'] = dt.day
test_data['month'] = dt.month
test_data['year'] = dt.year
test_data['hour'] = dt.hour
test_data['dow'] = dt.dayofweek
test_data['woy'] = dt.weekofyear

test_data = test_data.drop(['datetime'], axis=1)

mean = train_data.mean(axis=0)
train_data -= mean
std = train_data.std(axis=0)
train_data /= std

test_data -= mean
test_data /= std

from keras import models
from keras import layers
from keras.layers import Dense, Conv2D, Flatten

def build_model():
    model = models.Sequential()
    model.add(layers.Dense(64, activation='relu', input_shape=(train_data.shape[1], train_targets.shape[1])))
    model.add(layers.Dense(64, activation='relu'))
    model.add(layers.Dense(1))
    model.compile(optimizer='rmsprop', loss='mse', metrics=['mae'])
    return model

k = 4

num_val_samples = len(train_data) // k
num_epochs = 100
all_scores = []
for i in range(k):
    print('Processing fold #', i)
    val_data = train_data[i * num_val_samples: (i + 1) * num_val_samples]
    val_targets = train_targets[i * num_val_samples: (i + 1) * num_val_samples]

    partial_train_data = np.concatenate(
        [train_data[:i * num_val_samples],
        train_data[(i + 1) * num_val_samples:]], axis=0)
    partial_train_targets = np.concatenate(
        [train_targets[:i * num_val_samples],
        train_targets[(i + 1) * num_val_samples:]], axis=0)

    model = build_model()

    model.fit(partial_train_data, partial_train_targets,
             epochs=num_epochs, batch_size=1, verbose=0)

    val_mse, val_mae = model.evaluate(val_data, val_targets, verbose=0)

    all_scores.append(val_mae)
</code>```

I have got this error. Can you explain how can I solve it enter image description here

答:
you specified wrong the input dimension of your model. try to define your first layer in this way</p>

```<code>model.add(layers.Dense(64, activation='relu', input_shape=(train_data.shape[1],)))
</code>```

Body:
This is my first attempt to solve task on the kaggle. This is page of the task - https://www.kaggle.com/c/bike-sharing-demand.
I wrote this code (I have some excess code lines, because I am not really sure what I need now):

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import keras

import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
import matplotlib.pyplot as plt

import os
for dirname, _, filenames in os.walk('/kaggle/input'):
    for filename in filenames:
        print(os.path.join(dirname, filename))

train_data = pd.read_csv('/kaggle/input/bike-sharing-demand/train.csv')
train_targets = train_data[['casual', 'registered', 'count']]

train_datetime_helper = train_data[['datetime']]

dt = pd.DatetimeIndex(train_data['datetime'])
train_data['day'] = dt.day
train_data['month'] = dt.month
train_data['year'] = dt.year
train_data['hour'] = dt.hour
train_data['dow'] = dt.dayofweek
train_data['woy'] = dt.weekofyear

train_data = train_data.drop(['casual', 'registered', 'count', 'datetime'], axis=1)

test_data = pd.read_csv('/kaggle/input/bike-sharing-demand/test.csv')

test_datetime_helper = test_data[['datetime']]

dt = pd.DatetimeIndex(test_data['datetime'])

test_data['day'] = dt.day
test_data['month'] = dt.month
test_data['year'] = dt.year
test_data['hour'] = dt.hour
test_data['dow'] = dt.dayofweek
test_data['woy'] = dt.weekofyear

test_data = test_data.drop(['datetime'], axis=1)

mean = train_data.mean(axis=0)
train_data -= mean
std = train_data.std(axis=0)
train_data /= std

test_data -= mean
test_data /= std

from keras import models
from keras import layers
from keras.layers import Dense, Conv2D, Flatten

def build_model():
    model = models.Sequential()
    model.add(layers.Dense(64, activation='relu', input_shape=(train_data.shape[1], train_targets.shape[1])))
    model.add(layers.Dense(64, activation='relu'))
    model.add(layers.Dense(1))
    model.compile(optimizer='rmsprop', loss='mse', metrics=['mae'])
    return model

k = 4

num_val_samples = len(train_data) // k
num_epochs = 100
all_scores = []
for i in range(k):
    print('Processing fold #', i)
    val_data = train_data[i * num_val_samples: (i + 1) * num_val_samples]
    val_targets = train_targets[i * num_val_samples: (i + 1) * num_val_samples]

    partial_train_data = np.concatenate(
        [train_data[:i * num_val_samples],
        train_data[(i + 1) * num_val_samples:]], axis=0)
    partial_train_targets = np.concatenate(
        [train_targets[:i * num_val_samples],
        train_targets[(i + 1) * num_val_samples:]], axis=0)

    model = build_model()

    model.fit(partial_train_data, partial_train_targets,
             epochs=num_epochs, batch_size=1, verbose=0)

    val_mse, val_mae = model.evaluate(val_data, val_targets, verbose=0)

    all_scores.append(val_mae)

I have got this error. Can you explain how can I solve it enter image description here

Body:
you specified wrong the input dimension of your model. try to define your first layer in this way

model.add(layers.Dense(64, activation='relu', input_shape=(train_data.shape[1],)))


来源: stackexchange

问:
How to find the minimal element of each column in a two-dimensional array in Python
```<code>import random
x =[[random.randint(1,10) for j in range(5)] for i in range(4)]
for i in range(4):
    for j in range(5):
        print("%4d" % (x[i][j]), end="")
    print(end='\n')
</code>```

I need to find minimal element of each column in a  two-dimensional array and add them in a new array(one-dimensional array)

答:
Just use min on each column and list comprehension.</p>

```<code>x_new = [min(x_i) for x_i in x]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
import random
x =[[random.randint(1,10) for j in range(5)] for i in range(4)]
for i in range(4):
    for j in range(5):
        print("%4d" % (x[i][j]), end="")
    print(end='\n')

I need to find minimal element of each column in a  two-dimensional array and add them in a new array(one-dimensional array)

Body:
Just use min on each column and list comprehension.

x_new = [min(x_i) for x_i in x]


答:
You can use a list comprehension to apply min to each column of data:

```<code>import random
x =[[random.randint(1,10) for j in range(5)] for i in range(4)]
for i in range(4):
    for j in range(5):
        print("%4d" % (x[i][j]), end="")
    print(end='\n')

print([min(x[i][j] for i in range(4)) for j in range(5)])
</code>```

Sample output:

```<code>   8   1   7   6   9
   9   2   8   6   8
  10   5   3   3   5
   1   9   7  10   9

[1, 1, 3, 3, 5]
</code>```

Title: How to find the minimal element of each column in a two-dimensional array in Python

Body:
You can use a list comprehension to apply min to each column of data:

import random
x =[[random.randint(1,10) for j in range(5)] for i in range(4)]
for i in range(4):
    for j in range(5):
        print("%4d" % (x[i][j]), end="")
    print(end='\n')

print([min(x[i][j] for i in range(4)) for j in range(5)])

Sample output:

   8   1   7   6   9
   9   2   8   6   8
  10   5   3   3   5
   1   9   7  10   9

[1, 1, 3, 3, 5]


问:
Web Bluetooth API Connecting multiple devices in a single web page with same events priority
I would connect multiple hardware devices with BLE to a single HTML/javascript web page.
I have used Web Bluetooth API. Everything is working fine. I'm able to connect all devices and read out single characteristics from each one of those.
My problem is that I would have the same priority for each device.
It seems that last connected device got higher priorities than previous ones in terms of events polling out.
Is there a way for attributing the same priority to all the devices?

Here is my code for one device. All devices offer the same service and same characteristic.

```<code> //for device 1
    function connect_device_1(){
       navigator.bluetooth.requestDevice({
       filters: [
       {services: myService},
       {name: myDeviceName},
       ]
    })
    .then(function(device) {
       return device.gatt.connect();
    })
    .then(function(server) {
       return server.getPrimaryService(myService);
    })
    .then(function(service) {
       return service.getCharacteristics();
    })
    .then(function(characteristics) {
       sNots(characteristics);
    })
    .catch(function(error) {
    console.error('Connection failed!', error);
    });
    }

    async function sNots(characteristics) {
        try {
          characteristics[0].addEventListener('characteristicvaluechanged', handleData1);
          await  characteristics[0].startNotifications();
        } catch (e) {
          console.log("Characteristic error!");
        }
     }

     function handleData1(event) {
             //only one read out for cycle
     }

     //same as above for device 2
     //....
     function handleData2(event) {

     }
     //same as above for device 3
     //....
     function handleData3(event) {

     }
     //same as above for device 4
     //....
     function handleData4(event) {
          //For instance, if the device 4 is connected as the last one, this event is called more
          //than all the others, while I would like to have same priority with all the others.
     }
</code>```

答:
If your devices stream a lot of notifications, then this is the expected behaviour how BLE connection scheduling is usually implemented inside the Bluetooth controller, when you have the same connection interval among all connections.

See Bluetooth 5 & BLE throughput over multiple connections and https://infocenter.nordicsemi.com/topic/sds_s132/SDS/s1xx/multilink_scheduling/central_connection_timing.html.

There is not much you can do about this. You could try, from the peripheral side to select different connection parameters to avoid this situation. Normally, you can hint the controller how long connection events you want when you initiate a connection over HCI. But neither Web Bluetooth nor the underlying Bluetooth stacks Web Bluetooth uses expose this setting, leaving it to 0 (unspecified).

Body:
I would connect multiple hardware devices with BLE to a single HTML/javascript web page.
I have used Web Bluetooth API. Everything is working fine. I'm able to connect all devices and read out single characteristics from each one of those.
My problem is that I would have the same priority for each device.
It seems that last connected device got higher priorities than previous ones in terms of events polling out.
Is there a way for attributing the same priority to all the devices?

Here is my code for one device. All devices offer the same service and same characteristic.

 //for device 1
    function connect_device_1(){
       navigator.bluetooth.requestDevice({
       filters: [
       {services: myService},
       {name: myDeviceName},
       ]
    })
    .then(function(device) {
       return device.gatt.connect();
    })
    .then(function(server) {
       return server.getPrimaryService(myService);
    })
    .then(function(service) {
       return service.getCharacteristics();
    })
    .then(function(characteristics) {
       sNots(characteristics);
    })
    .catch(function(error) {
    console.error('Connection failed!', error);
    });
    }

    async function sNots(characteristics) {
        try {
          characteristics[0].addEventListener('characteristicvaluechanged', handleData1);
          await  characteristics[0].startNotifications();
        } catch (e) {
          console.log("Characteristic error!");
        }
     }

     function handleData1(event) {
             //only one read out for cycle
     }

     //same as above for device 2
     //....
     function handleData2(event) {

     }
     //same as above for device 3
     //....
     function handleData3(event) {

     }
     //same as above for device 4
     //....
     function handleData4(event) {
          //For instance, if the device 4 is connected as the last one, this event is called more
          //than all the others, while I would like to have same priority with all the others.
     }


问:
Sepia filter CS50 week 4
I need to create a filter that converts an colour image into sepia filter with the formulas below on my code. This is a CS50 week 4 problem set.

I am having trouble understanding the errors on I get when I run check50. Please see below my code and the errors that I got. The code makes sense and returns the expected rgb values but I still get two errors on check50.
```
:) sepia correctly filters single pixel

:) sepia correctly filters simple 3x3 image

:( sepia correctly filters more complex 3x3 image
    expected "25 22 17\n66 5...", not "25 22 17\n66 5..." - ERROR HERE

:( sepia correctly filters 4x4 image
    expected "25 22 17\n66 5...", not "25 22 17\n66 5..." - ERROR HERE
</p>

<code>// Convert image to sepia
void sepia(int height, int width, RGBTRIPLE image[height][width])
{
    float sr = 0;
    float sg = 0;
    float sb = 0;

    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            sr = (0.393 * image[i][j].rgbtRed + 0.769 * image[i][j].rgbtGreen + 0.189 * image[i][j].rgbtBlue);
            sg = (0.349 * image[i][j].rgbtRed + 0.686 * image[i][j].rgbtGreen + 0.168 * image[i][j].rgbtBlue);
            sb = (0.272 * image[i][j].rgbtRed + 0.534 * image[i][j].rgbtGreen + 0.131 * image[i][j].rgbtBlue);

           image[i][j].rgbtRed = round(sr);
           image[i][j].rgbtGreen = round(sg);
           image[i][j].rgbtBlue = round(sb);
        }
    }

    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
           if (image[i][j].rgbtRed > 255)
           {
               image[i][j].rgbtRed = 255;

           }

            if (image[i][j].rgbtGreen > 255)
           {
               image[i][j].rgbtGreen = 255;

           }

            if (image[i][j].rgbtBlue > 255)
           {
               image[i][j].rgbtBlue = 255;

           }

        }

    }

    return;

}
</code>```

答:
```<code>sr = (0.393 * image[i][j].rgbtRed + 0.769 * image[i][j].rgbtGreen + 0.189 * image[i][j].rgbtBlue);
sg = (0.349 * image[i][j].rgbtRed + 0.686 * image[i][j].rgbtGreen + 0.168 * image[i][j].rgbtBlue);
sb = (0.272 * image[i][j].rgbtRed + 0.534 * image[i][j].rgbtGreen + 0.131 * image[i][j].rgbtBlue);
</code>```

For this part you need to limit the pixel color to go past 255. You can make a function like this

```<code>int limit(int RGB)
{
    if (RGB > 255)
    {
        RGB = 255;
    }
    return RGB;
}
</code>```

to limit it. You would also have to round the sepia colors using the round function

Title: Sepia filter CS50 week 4

Body:
I need to create a filter that converts an colour image into sepia filter with the formulas below on my code. This is a CS50 week 4 problem set.

I am having trouble understanding the errors on I get when I run check50. Please see below my code and the errors that I got. The code makes sense and returns the expected rgb values but I still get two errors on check50.

:) sepia correctly filters single pixel

:) sepia correctly filters simple 3x3 image

:( sepia correctly filters more complex 3x3 image
    expected "25 22 17\n66 5...", not "25 22 17\n66 5..." - ERROR HERE

:( sepia correctly filters 4x4 image
    expected "25 22 17\n66 5...", not "25 22 17\n66 5..." - ERROR HERE

// Convert image to sepia
void sepia(int height, int width, RGBTRIPLE image[height][width])
{
    float sr = 0;
    float sg = 0;
    float sb = 0;

    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            sr = (0.393 * image[i][j].rgbtRed + 0.769 * image[i][j].rgbtGreen + 0.189 * image[i][j].rgbtBlue);
            sg = (0.349 * image[i][j].rgbtRed + 0.686 * image[i][j].rgbtGreen + 0.168 * image[i][j].rgbtBlue);
            sb = (0.272 * image[i][j].rgbtRed + 0.534 * image[i][j].rgbtGreen + 0.131 * image[i][j].rgbtBlue);

           image[i][j].rgbtRed = round(sr);
           image[i][j].rgbtGreen = round(sg);
           image[i][j].rgbtBlue = round(sb);
        }
    }

    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
           if (image[i][j].rgbtRed > 255)
           {
               image[i][j].rgbtRed = 255;

           }

            if (image[i][j].rgbtGreen > 255)
           {
               image[i][j].rgbtGreen = 255;

           }

            if (image[i][j].rgbtBlue > 255)
           {
               image[i][j].rgbtBlue = 255;

           }

        }

    }

    return;

}

Body:
sr = (0.393 * image[i][j].rgbtRed + 0.769 * image[i][j].rgbtGreen + 0.189 * image[i][j].rgbtBlue);
sg = (0.349 * image[i][j].rgbtRed + 0.686 * image[i][j].rgbtGreen + 0.168 * image[i][j].rgbtBlue);
sb = (0.272 * image[i][j].rgbtRed + 0.534 * image[i][j].rgbtGreen + 0.131 * image[i][j].rgbtBlue);

For this part you need to limit the pixel color to go past 255. You can make a function like this

int limit(int RGB)
{
    if (RGB > 255)
    {
        RGB = 255;
    }
    return RGB;
}

to limit it. You would also have to round the sepia colors using the round function


问:
Faster way to update an empty dataframe using the information from two dataframes
I  have two dataframes: df_a and df_b (each having a total of 1,000,000 rows).

df_a has two columns: uniqueID, start_time

df_b has two columns: uniqueID, end_time

My objective is to generate a dataframe (df_final) with following columns:

uniqueID, start_time, end_time

df_final must contains all the data from df_a (i.e. uniqueID, start_time). For each (uniqueID, start_time) in df_final, end_time must be taken from df_b corresponding to same uniqueID. df_b have multiple end_time for each uniqueID. For each uniqueID, end_time closest to start_time must be considered for df_final["end_time"]. In case, no such closest end_time is available in df_b, then df_final["end_time"] must be NULL.

My approaches:
Approach 1:

```<code>#define a function
def get_end_date(uniqueID, start_time):
    sub_sectiondata = df_b[(df_b['uniqueID']==uniqueID) & (df_b["end_time"]>start_time)]
    if len(sub_sectiondata) == 0:
        return None
    else:
        return min(sub_sectiondata["end_time"])
</code>```

Then apply the above function on df_a.

```<code>df_a['end_time'] = df_a.apply(lambda x: get_end_date(x['uniqueID'], x['start_time']), axis=1)
</code>```

Approach 2:

```<code>df = df_a.copy()

for row in df.itertuples():
    sub_sectiondata = df_b[(df_b['uniqueID']==row.uniqueID) & (df_b["end_time"]>row.start_time)]
    if len(sub_sectiondata)>0:
        df_final = df_final .append({'uniqueID':row.uniqueID, 'start_time':row.start_time, 'end_time': min(sub_sectiondata["end_time"])}, ignore_index = True)

    else:
        df_final = df_final .append({'uniqueID':row.uniqueID, 'start_time':row.start_time, 'end_time': None}, ignore_index = True)
</code>```

In both the approaches, I am getting the desired result, but the time taken to execute this is very high. It increases linearly (for every 10000 records, it takes approx 20 minutes). So for 1000000, it will be around 33 hours to complete which is huge. So is there any other method in python to handle this? Any help in this regard from the community?

答:
Iterating by rows over dataframes is known to be a slow operation. Here the magic word is merge_asof: it allows to select a row from a second dataframe immediately after a row in a first one, or having a numeric or date value nearest to the first one.

So if you want the end_time closest to start_time, you can do:

```<code>df_final = pd.merge_asof(df_a.sort_values('start_time'), df_b.sort_values('end_time')
    , left_on='start_time', right_on='end_time',
    by='unique_id', direction='nearest')
</code>```

But this would allow an end_time before the start_time. If you want to ensure end_time >= start_time you should use direction='forward':

```<code>df_final = pd.merge_asof(df_a.sort_values('start_time'), df_b.sort_values('end_time')
    , left_on='start_time', right_on='end_time',
    by='unique_id', direction='forward')
</code>```

Body:
I  have two dataframes: df_a and df_b (each having a total of 1,000,000 rows).

df_a has two columns: uniqueID, start_time

df_b has two columns: uniqueID, end_time

My objective is to generate a dataframe (df_final) with following columns:

uniqueID, start_time, end_time

df_final must contains all the data from df_a (i.e. uniqueID, start_time). For each (uniqueID, start_time) in df_final, end_time must be taken from df_b corresponding to same uniqueID. df_b have multiple end_time for each uniqueID. For each uniqueID, end_time closest to start_time must be considered for df_final["end_time"]. In case, no such closest end_time is available in df_b, then df_final["end_time"] must be NULL.

My approaches:
Approach 1:

#define a function
def get_end_date(uniqueID, start_time):
    sub_sectiondata = df_b[(df_b['uniqueID']==uniqueID) & (df_b["end_time"]>start_time)]
    if len(sub_sectiondata) == 0:
        return None
    else:
        return min(sub_sectiondata["end_time"])

Then apply the above function on df_a.

df_a['end_time'] = df_a.apply(lambda x: get_end_date(x['uniqueID'], x['start_time']), axis=1)

Approach 2:

df = df_a.copy()

for row in df.itertuples():
    sub_sectiondata = df_b[(df_b['uniqueID']==row.uniqueID) & (df_b["end_time"]>row.start_time)]
    if len(sub_sectiondata)>0:
        df_final = df_final .append({'uniqueID':row.uniqueID, 'start_time':row.start_time, 'end_time': min(sub_sectiondata["end_time"])}, ignore_index = True)

    else:
        df_final = df_final .append({'uniqueID':row.uniqueID, 'start_time':row.start_time, 'end_time': None}, ignore_index = True)

In both the approaches, I am getting the desired result, but the time taken to execute this is very high. It increases linearly (for every 10000 records, it takes approx 20 minutes). So for 1000000, it will be around 33 hours to complete which is huge. So is there any other method in python to handle this? Any help in this regard from the community?

Body:
Iterating by rows over dataframes is known to be a slow operation. Here the magic word is merge_asof: it allows to select a row from a second dataframe immediately after a row in a first one, or having a numeric or date value nearest to the first one.

So if you want the end_time closest to start_time, you can do:

df_final = pd.merge_asof(df_a.sort_values('start_time'), df_b.sort_values('end_time')
    , left_on='start_time', right_on='end_time',
    by='unique_id', direction='nearest')

But this would allow an end_time before the start_time. If you want to ensure end_time >= start_time you should use direction='forward':

df_final = pd.merge_asof(df_a.sort_values('start_time'), df_b.sort_values('end_time')
    , left_on='start_time', right_on='end_time',
    by='unique_id', direction='forward')


问:
OpenJDK 1.8.0 in Docker container has different timezone than /etc/timezone and from the host
I have a Linux box running a Docker container, which is running TomEE, and running a WAR I built.

On the base Linux box, I get a "date" value of "Fri Jan 20 10:37:27 PST 2017".  The TZ environment variable is not set.

When I run the following class:

```<code>import java.util.Date;
import java.util.TimeZone;

public class DatePrint {
        public static void main(String[] args) {
                System.out.println("date[" + new Date() + "] tzoffset[" + TimeZone.getDefault().getOffset(new java.util.Date().getTime()) + "]");
        }
}
</code>```

I get this:

```<code>date[Fri Jan 20 10:39:02 PST 2017] tzoffset[-28800000]
</code>```

This is all fine.

In my Docker container running on the box, where I have "-v /etc/localtime:/etc/localtime" as one of the volume mappings, I obviously have the same /etc/localtime file.  The TZ environment variable is not set.  When I run "date" inside the container, I get a time value in the same timezone (PST) as in the base host.

I then compile and run the same Java class as above, and I get the following:

```<code>date[Fri Jan 20 18:30:38 UTC 2017] tzoffset[0]
</code>```

I then manually set the TZ environment variable in the container (remember that it's not set in the base host) to "America/Los_Angeles" (I verified this value by looking at the file that "/etc/localtime" symlinks to on the base host).

I then reran the class on the container and got this:

```<code>date[Fri Jan 20 10:35:08 PST 2017] tzoffset[-28800000]
</code>```

Note that the two versions of Java on the base host and the container are almost identical.  They are both OpenJDK 1.8.0_111 (b15 on the host, b14 on the container).

So, can someone explain what's going on here?  On the base host, I had "etc/localtime" pointing to the proper file, but I did not have TZ set.  It reports the correct timezone with "date" and in the Java class.  On the container, "/etc/localtime" is pointing to the proper file, and I didn't originally have TZ set.  The "date" command returns the correct value, but Java did not.

I had to manually set TZ on the container to the TZ value from the host, and that made it work.  I'd really rather not do this.  That seems like a hack to me.

Update:

I noticed the following in the "localtime(5)" man page:

Because the timezone identifier is extracted from the symlink target
         name of /etc/localtime, this file may not be a normal file or hardlink.

So, that may be part of my problem.  It's still curious that "date" from the shell works fine, but Java (without the TZ setting) gets confused.

答: Follow Gilles's answer in https://unix.stackexchange.com/questions/452559/what-is-etc-timezone-used-for, Java reads /etc/timezone instead of /etc/localtime because of historical reasons. Further explanations can be found in that post.

ContentLicense: CC BY-SA 3.0

Body:
I have a Linux box running a Docker container, which is running TomEE, and running a WAR I built.

On the base Linux box, I get a "date" value of "Fri Jan 20 10:37:27 PST 2017".  The TZ environment variable is not set.

When I run the following class:

import java.util.Date;
import java.util.TimeZone;

public class DatePrint {
        public static void main(String[] args) {
                System.out.println("date[" + new Date() + "] tzoffset[" + TimeZone.getDefault().getOffset(new java.util.Date().getTime()) + "]");
        }
}

I get this:

date[Fri Jan 20 10:39:02 PST 2017] tzoffset[-28800000]

This is all fine.

In my Docker container running on the box, where I have "-v /etc/localtime:/etc/localtime" as one of the volume mappings, I obviously have the same /etc/localtime file.  The TZ environment variable is not set.  When I run "date" inside the container, I get a time value in the same timezone (PST) as in the base host.

I then compile and run the same Java class as above, and I get the following:

date[Fri Jan 20 18:30:38 UTC 2017] tzoffset[0]

I then manually set the TZ environment variable in the container (remember that it's not set in the base host) to "America/Los_Angeles" (I verified this value by looking at the file that "/etc/localtime" symlinks to on the base host).

I then reran the class on the container and got this:

date[Fri Jan 20 10:35:08 PST 2017] tzoffset[-28800000]

Note that the two versions of Java on the base host and the container are almost identical.  They are both OpenJDK 1.8.0_111 (b15 on the host, b14 on the container).

So, can someone explain what's going on here?  On the base host, I had "etc/localtime" pointing to the proper file, but I did not have TZ set.  It reports the correct timezone with "date" and in the Java class.  On the container, "/etc/localtime" is pointing to the proper file, and I didn't originally have TZ set.  The "date" command returns the correct value, but Java did not.

I had to manually set TZ on the container to the TZ value from the host, and that made it work.  I'd really rather not do this.  That seems like a hack to me.

Update:

I noticed the following in the "localtime(5)" man page:

Because the timezone identifier is extracted from the symlink target
         name of /etc/localtime, this file may not be a normal file or hardlink.

So, that may be part of my problem.  It's still curious that "date" from the shell works fine, but Java (without the TZ setting) gets confused.


问:
read only particular json files from s3 buckets from multiple folders
am trying to scroll over all buckets in s3 and see if there is a prefix that matches and get into those folders and read the json files.

I have tried to get the folders that contain a prefix, but failing to enter them.

Code:

```<code>import boto3
bucket = ['test-eob', 'test-eob-images']
client = boto3.client('s3')
for i in bucket:
    result = client.list_objects(Bucket=i,Prefix = 'PROCESSED_BY/FILE_JSON', Delimiter='/')
    print(result)
</code>```

Using this am getting the ones with prefix and fails when bucket doesnt have that prefix.

structure of test-eob , test-eob/PROCESSED_BY/FILE_JSON/*.json
I have to read the json if only my prefix matches, else come out of the bucket.

Can anyone help me out here.

答:
Try to catch the error(is it a KeyError?) when the bucket does not contain the prefix.

For example:

```<code>for i in bucket:
    try:
          result = client.list_objects(Bucket=i,Prefix = 'PROCESSED_BY/FILE_JSON', Delimiter='/')
          print(result)
    except KeyError:
          pass
</code>```

To read the json, there are several ways. For example with json.loads() from the json module.

So for each object in the bucket:

```<code>content_object = s3.Object(bucket_name, file_name)
file_content = content_object.get()['Body'].read().decode('utf-8')
json_content = json.loads(file_content)
</code>```

Body:
am trying to scroll over all buckets in s3 and see if there is a prefix that matches and get into those folders and read the json files.

I have tried to get the folders that contain a prefix, but failing to enter them.

Code:

import boto3
bucket = ['test-eob', 'test-eob-images']
client = boto3.client('s3')
for i in bucket:
    result = client.list_objects(Bucket=i,Prefix = 'PROCESSED_BY/FILE_JSON', Delimiter='/')
    print(result)

Using this am getting the ones with prefix and fails when bucket doesnt have that prefix.

structure of test-eob , test-eob/PROCESSED_BY/FILE_JSON/*.json
I have to read the json if only my prefix matches, else come out of the bucket.

Can anyone help me out here.

Body:
Try to catch the error(is it a KeyError?) when the bucket does not contain the prefix.

For example:

for i in bucket:
    try:
          result = client.list_objects(Bucket=i,Prefix = 'PROCESSED_BY/FILE_JSON', Delimiter='/')
          print(result)
    except KeyError:
          pass

To read the json, there are several ways. For example with json.loads() from the json module.

So for each object in the bucket:

content_object = s3.Object(bucket_name, file_name)
file_content = content_object.get()['Body'].read().decode('utf-8')
json_content = json.loads(file_content)


问:
"PT" Formatted time string in python
I'm receiving a string which is formatted in the following way: "PTXMYS" Where X is the amount of minutes and Y is the amount of seconds.

I'd like to turn that string into an int which presents the amount of seconds in total.
I tried using datetime and other stuff and it just won't work for me, I read online that this formatting is standard for iso8601 so it's weird for me that it doesn't really work.

String example:

```<code>x="PT4M13S"
</code>```

答:
What you are trying to do can easily be solved using regex. Try this out:

import re
m, s = re.findall('PT(\d+)M(\d+)S',x)[0]
total_secs = 60*int(m) + int(s)
print(total_secs)
```

<p>Output:</p>

```253
```

Title: "PT" Formatted time string in python

Body:
I'm receiving a string which is formatted in the following way: "PTXMYS" Where X is the amount of minutes and Y is the amount of seconds.

I'd like to turn that string into an int which presents the amount of seconds in total.
I tried using datetime and other stuff and it just won't work for me, I read online that this formatting is standard for iso8601 so it's weird for me that it doesn't really work.

String example:

x="PT4M13S"

Body:
What you are trying to do can easily be solved using regex. Try this out:

import re
m, s = re.findall('PT(\d+)M(\d+)S',x)[0]
total_secs = 60*int(m) + int(s)
print(total_secs)

Output:

253


问:
How to recognize that a parent page is left from within an iframe?
I would like to execute a function from within an iframe before page is unloaded to send data to my Analytics tool. But I am in an iframe.

I do only know:

window.onbeforeunload = function(){ ... }

But it seems like that doesn't work from the iframe, my function is not executed.

I also found this:

```<code>var iframe = document.getElementById('iframe');
iframe.load(
    function(){
        iframe.contentWindow.onbeforeunload = function(){
            myFunction();
        }
    }
)
</code>```

but it didn't work either.

Is there any other way to do this?

答:
Try this:

```<code>var iframe = document.getElementById('iframe');

iframe.addEventListener( "load", function(e) {
    alert('content loaded');
});
iframe.addEventListener( "beforeunload", function(e) {
    alert('content reloaded');
    myFunction();
});
</code>```

Body:
I would like to execute a function from within an iframe before page is unloaded to send data to my Analytics tool. But I am in an iframe.

I do only know:

window.onbeforeunload = function(){ ... }

But it seems like that doesn't work from the iframe, my function is not executed.

I also found this:

var iframe = document.getElementById('iframe');
iframe.load(
    function(){
        iframe.contentWindow.onbeforeunload = function(){
            myFunction();
        }
    }
)

but it didn't work either.

Is there any other way to do this?

Body:
Try this:

var iframe = document.getElementById('iframe');

iframe.addEventListener( "load", function(e) {
    alert('content loaded');
});
iframe.addEventListener( "beforeunload", function(e) {
    alert('content reloaded');
    myFunction();
});


问:
Can’t serialize access for this transaction with isolation to ISOLATION_READ_UNCOMMITTED
Using spring-batch, I have 2 datasources : one for the spring batch called centralDataSource and one for the business called localDataSource.

I've set the isolation level to ISOLATION_READ_UNCOMMITTED to avoid problems with concurrent transactions as below.

@Bean
public Job myJob(Step firstStep,
                     Step secondStep,
                     JobCompletionNotificationListener listener,
                     JobRepository customJobRepository) {
    return jobBuilderFactory.get("my-job")
                           .repository(customJobRepository)
                           .listener(listener)
                           .incrementer(new RunIdIncrementer())
                           .start(firstStep)
                           .next(secondStep)
                           .build();
}

@Bean
public JobRepository customJobRepository(
        @Qualifier("centralDataSource") DataSource centralDataSource,
        @Qualifier("centralTransactionManager") PlatformTransactionManager centralTransactionManager)
            throws Exception {
    JobRepositoryFactoryBean factoryBean = new JobRepositoryFactoryBean();
    factoryBean.setDatabaseType("ORACLE");
    factoryBean.setDataSource(centralDataSource);
    factoryBean.setTransactionManager(centralTransactionManager);
    factoryBean.setIsolationLevelForCreate("ISOLATION_READ_UNCOMMITTED");
    return factoryBean.getObject();
}
```

I still have Application run failed with SQLException: ORA-08177: can’t serialize access for this transaction.

I don't understand why. There are not even 2 concurrent spring batch jobs running at the same time. Jobs are run sequentially so why does this happen and how can I solve it ?

Can anyone help me ?

答:
I don't know Spring and how it can change transaction isolation level but:

First, Oracle database does not support READ_UNCOMMITTED isolation level:

```<code>alter session set isolation_level=read_uncommitted
                                  *
ERROR at line 1:
ORA-02183: valid options: ISOLATION_LEVEL { SERIALIZABLE | READ COMMITTED }
</code>```

Second if you have ORA-8177 it means you are using SERIALIZABLE isolation level.

```<code>$ oerr ora 8177
08177, 00000, "can't serialize access for this transaction"
// *Cause:   Encountered data changed by an operation that occurred after
//           the start of this serializable transaction.
// *Action:  In read/write transactions, retry the intended operation or
//           transaction.
</code>```

You need to check what ALTER SESSION statements to change isolation level are run by Spring.

Body:
Using spring-batch, I have 2 datasources : one for the spring batch called centralDataSource and one for the business called localDataSource.

I've set the isolation level to ISOLATION_READ_UNCOMMITTED to avoid problems with concurrent transactions as below.

@Bean
public Job myJob(Step firstStep,
                     Step secondStep,
                     JobCompletionNotificationListener listener,
                     JobRepository customJobRepository) {
    return jobBuilderFactory.get("my-job")
                           .repository(customJobRepository)
                           .listener(listener)
                           .incrementer(new RunIdIncrementer())
                           .start(firstStep)
                           .next(secondStep)
                           .build();
}

@Bean
public JobRepository customJobRepository(
        @Qualifier("centralDataSource") DataSource centralDataSource,
        @Qualifier("centralTransactionManager") PlatformTransactionManager centralTransactionManager)
            throws Exception {
    JobRepositoryFactoryBean factoryBean = new JobRepositoryFactoryBean();
    factoryBean.setDatabaseType("ORACLE");
    factoryBean.setDataSource(centralDataSource);
    factoryBean.setTransactionManager(centralTransactionManager);
    factoryBean.setIsolationLevelForCreate("ISOLATION_READ_UNCOMMITTED");
    return factoryBean.getObject();
}

I still have Application run failed with SQLException: ORA-08177: can’t serialize access for this transaction.

I don't understand why. There are not even 2 concurrent spring batch jobs running at the same time. Jobs are run sequentially so why does this happen and how can I solve it ?

Can anyone help me ?

Body:
I don't know Spring and how it can change transaction isolation level but:

First, Oracle database does not support READ_UNCOMMITTED isolation level:

alter session set isolation_level=read_uncommitted
                                  *
ERROR at line 1:
ORA-02183: valid options: ISOLATION_LEVEL { SERIALIZABLE | READ COMMITTED }

Second if you have ORA-8177 it means you are using SERIALIZABLE isolation level.

$ oerr ora 8177
08177, 00000, "can't serialize access for this transaction"
// *Cause:   Encountered data changed by an operation that occurred after
//           the start of this serializable transaction.
// *Action:  In read/write transactions, retry the intended operation or
//           transaction.

You need to check what ALTER SESSION statements to change isolation level are run by Spring.


问:
UISearchBar with a white background is impossible?
I really thought it would be easy to set the background color of my UISearchBar's text field to white. But no matter what I try, it always stays offwhite / light gray (#efeff0).

import UIKit

class ViewController: UIViewController {
  private let searchController = UISearchController()

  override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.title = "Hello World"
    view.backgroundColor = #colorLiteral(red: 0.9588784575, green: 0.9528519511, blue: 0.9350754619, alpha: 1)
    searchController.searchBar.searchTextField.backgroundColor = .white
    navigationItem.searchController = searchController
  }
}
```

How can I make the search bar have a pure white background color? App is iOS 13+, if that helps.

Tiny test project: https://github.com/kevinrenskers/WhiteSearch.

答:
```<code>Try this ... Change colors and images according to your preference

 DispatchQueue.main.async {
            searchBar.backgroundImage = UIImage()

            for s in searchBar.subviews[0].subviews {
                if s is UITextField {
                    s.layer.borderWidth = 1.0
                    s.layer.borderColor = UIColor.lightGray.cgColor

                }
            }

            let searchTextField:UITextField = searchBar.subviews[0].subviews.last as? UITextField ?? UITextField()
            searchTextField.layer.cornerRadius = 10
            searchTextField.textAlignment = NSTextAlignment.left
            let image:UIImage = UIImage(named: "search")!
            let imageView:UIImageView = UIImageView.init(image: image)
            searchTextField.leftView = nil
            searchTextField.placeholder = "Search..."
            searchTextField.font = UIFont.textFieldText
            searchTextField.rightView = imageView
            searchTextField.rightViewMode = UITextField.ViewMode.always

        }
</code>```

Body:
I really thought it would be easy to set the background color of my UISearchBar's text field to white. But no matter what I try, it always stays offwhite / light gray (#efeff0).

import UIKit

class ViewController: UIViewController {
  private let searchController = UISearchController()

  override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.title = "Hello World"
    view.backgroundColor = #colorLiteral(red: 0.9588784575, green: 0.9528519511, blue: 0.9350754619, alpha: 1)
    searchController.searchBar.searchTextField.backgroundColor = .white
    navigationItem.searchController = searchController
  }
}

How can I make the search bar have a pure white background color? App is iOS 13+, if that helps.

Tiny test project: https://github.com/kevinrenskers/WhiteSearch.


问:
How to create a directory in Laravel
I'm trying to create a folder in the storage folder in Laravel, but I keep getting this error:

```<code>mkdir(): No such file or directory
</code>```

I get what that means, but I thought it would be possible to create one with either:

```<code>File::makeDirectory(storage_path("story/$story->id"));
</code>```

or

```<code>mkdir(storage_path("story/$story->id"));
</code>```

but both of them are giving me the error above.

答:
This is from an existing project:

```<code>if($request->hasFile('cover_image'))
    {
        // Get the file with extension
        $filenameWithExt = $request->file('cover_image')->getClientOriginalName();
        //Get the file name
        $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
        //Get the ext
        $extension = $request->file('cover_image')->getClientOriginalExtension();
        //File name to store
        $fileNameToStore = $filename.'_'.time().'.'.$extension;
        //Upload Image
        $path = $request->file('cover_image')->storeAS('public/cover_images', $fileNameToStore);
    }
</code>```

This creates a folder in public folder and save the file. Rest you can use it anywhere with variable $fileNameToStore

Title: How to create a directory in Laravel

Body:
I'm trying to create a folder in the storage folder in Laravel, but I keep getting this error:

mkdir(): No such file or directory

I get what that means, but I thought it would be possible to create one with either:

File::makeDirectory(storage_path("story/$story->id"));

or

mkdir(storage_path("story/$story->id"));

but both of them are giving me the error above.

Body:
This is from an existing project:

if($request->hasFile('cover_image'))
    {
        // Get the file with extension
        $filenameWithExt = $request->file('cover_image')->getClientOriginalName();
        //Get the file name
        $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
        //Get the ext
        $extension = $request->file('cover_image')->getClientOriginalExtension();
        //File name to store
        $fileNameToStore = $filename.'_'.time().'.'.$extension;
        //Upload Image
        $path = $request->file('cover_image')->storeAS('public/cover_images', $fileNameToStore);
    }

This creates a folder in public folder and save the file. Rest you can use it anywhere with variable $fileNameToStore


问:
Initialize window handle for form and child controls without displaying
Is there a way to programmatically force a form and all of its child controls to have window handles without it being visible?  It looked like CreateControl would do it, but that only seems to work if the control is visible.  Requesting the handle of the form gives the form a handle, but doesn't give handles to all child controls, and I don't really want to iterate through all child controls manually forcing them to have handles.

Currently, I'm resorting to making the form visible for a split second and then hiding it, which seems to be a pretty hacky solution to me.  Is there a better way?

答:
If you want create the window handles without actually seeing the form, you can do this:</p>

```<code>  public Form1()
  {
     InitializeComponent();
     this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
     this.ShowInTaskbar = false;
     this.Load += new EventHandler(Form1_Load);
  }

  void Form1_Load(object sender, EventArgs e)
  {
     this.Size = new Size(0, 0);
  }
</code>```

Body:
If you want create the window handles without actually seeing the form, you can do this:

  public Form1()
  {
     InitializeComponent();
     this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
     this.ShowInTaskbar = false;
     this.Load += new EventHandler(Form1_Load);
  }

  void Form1_Load(object sender, EventArgs e)
  {
     this.Size = new Size(0, 0);
  }


问:
Django : no such table
I am using a ManyToMany relationship using an intermediate table (keyword through) in django and I get a OperationalError at /admin/workoutJournal/workout/add/ no such table: workoutJournal_workoutexercise

My code is the following :

```<code>class Exercise(models.Model):

    name = models.CharField(max_length=120, default='')

    def __repr__ (self):
        return 'self.name'

    def __str__ (self):
        return self.name

    class planesOfMovement(models.TextChoices):
        SAGITTAL = 'SA', _('Sagittal')
        FRONTAL = 'FR', _('Frontal')
        TRANSVERSAL = 'TR', _('Transversal')

    planesOfMovement = models.CharField(
        max_length=2,
        choices=planesOfMovement.choices,
        default=planesOfMovement.FRONTAL,
    )

    class typeOfMovement(models.TextChoices):
        PUSH = 'PS', _('Push')
        PULL = 'PL', _('Pull')
        CARRY = 'CA', _('Carry')
        LOAD = 'LO', _('Load')

    typeOfMovement = models.CharField(
        max_length=2,
        choices=typeOfMovement.choices,
        default=typeOfMovement.LOAD,
    )

class Workout(models.Model):
    date = models.DateField(default=datetime.date.today)
    exercises = models.ManyToManyField(Exercise, through='WorkoutExercise')

    def __str__(self):              # __unicode__ on Python 2
        return self.name

    # class Meta:
    #     db_table = "workoutJournal_Workout_exercises" # necessary to update migrations when modifying the through
    #                                                 # argument of an existing relation

class WorkoutExercise(models.Model):
    exercise = models.ForeignKey(Exercise, on_delete=models.DO_NOTHING)
    workout =  models.ForeignKey(Workout, on_delete = models.PROTECT)
    sets = models.PositiveIntegerField()
    reps = models.PositiveIntegerField()
    tempo = models.CharField(max_length = 11, validators=[
                                      RegexValidator(r'[0-9]{1,3}-[0-9]{1,3}-[0-9]{1,3}',
                                      message='Please format your tempo as [0-9]{1,3}-[0-9]{1,3}-[0-9]{1,3}')
                                  ])
</code>```

Any idea what I am doing wrong ?

答:
Step 1: Delete all files in the migrations folder except __init__.py.

Step 2: Comment out all the fields in models.py, and add some random field, like:

```<code>class Exercise(models.Model):
    randomfield = models.CharField(max_length=10)
    #name = models.CharField(max_length=120, default='')

    #def __repr__ (self):
     #   return 'self.name'

    #def __str__ (self):
     #   return self.name

</code>```

Step 3:  Run python manage.py makemigrations and python manage.py migrate in your terminal or CMD.

Step 4: Now remove the random field and uncomment the fields, like:

```<code>class Exercise(models.Model):
    name = models.CharField(max_length=120, default='')

    def __repr__ (self):
        return 'self.name'

    def __str__ (self):
        return self.name

</code>```

Step 5: Run python manage.py makemigrations and python manage.py migrate again.

I hope that this should work for you.

Note: Be sure to do this with all models!

Title: Django : no such table

Body:
I am using a ManyToMany relationship using an intermediate table (keyword through) in django and I get a OperationalError at /admin/workoutJournal/workout/add/ no such table: workoutJournal_workoutexercise

My code is the following :

class Exercise(models.Model):

    name = models.CharField(max_length=120, default='')

    def __repr__ (self):
        return 'self.name'

    def __str__ (self):
        return self.name

    class planesOfMovement(models.TextChoices):
        SAGITTAL = 'SA', _('Sagittal')
        FRONTAL = 'FR', _('Frontal')
        TRANSVERSAL = 'TR', _('Transversal')

    planesOfMovement = models.CharField(
        max_length=2,
        choices=planesOfMovement.choices,
        default=planesOfMovement.FRONTAL,
    )

    class typeOfMovement(models.TextChoices):
        PUSH = 'PS', _('Push')
        PULL = 'PL', _('Pull')
        CARRY = 'CA', _('Carry')
        LOAD = 'LO', _('Load')

    typeOfMovement = models.CharField(
        max_length=2,
        choices=typeOfMovement.choices,
        default=typeOfMovement.LOAD,
    )

class Workout(models.Model):
    date = models.DateField(default=datetime.date.today)
    exercises = models.ManyToManyField(Exercise, through='WorkoutExercise')

    def __str__(self):              # __unicode__ on Python 2
        return self.name

    # class Meta:
    #     db_table = "workoutJournal_Workout_exercises" # necessary to update migrations when modifying the through
    #                                                 # argument of an existing relation

class WorkoutExercise(models.Model):
    exercise = models.ForeignKey(Exercise, on_delete=models.DO_NOTHING)
    workout =  models.ForeignKey(Workout, on_delete = models.PROTECT)
    sets = models.PositiveIntegerField()
    reps = models.PositiveIntegerField()
    tempo = models.CharField(max_length = 11, validators=[
                                      RegexValidator(r'[0-9]{1,3}-[0-9]{1,3}-[0-9]{1,3}',
                                      message='Please format your tempo as [0-9]{1,3}-[0-9]{1,3}-[0-9]{1,3}')
                                  ])

Any idea what I am doing wrong ?

Body:
Step 1: Delete all files in the migrations folder except __init__.py.

Step 2: Comment out all the fields in models.py, and add some random field, like:

class Exercise(models.Model):
    randomfield = models.CharField(max_length=10)
    #name = models.CharField(max_length=120, default='')

    #def __repr__ (self):
     #   return 'self.name'

    #def __str__ (self):
     #   return self.name

Step 3:  Run python manage.py makemigrations and python manage.py migrate in your terminal or CMD.

Step 4: Now remove the random field and uncomment the fields, like:

class Exercise(models.Model):
    name = models.CharField(max_length=120, default='')

    def __repr__ (self):
        return 'self.name'

    def __str__ (self):
        return self.name

Step 5: Run python manage.py makemigrations and python manage.py migrate again.

I hope that this should work for you.

Note: Be sure to do this with all models!


问:
How do I open the segment index of my segment controller from app delegate?
I want to display the "Menu View Controller" when a local notification was opened. I use a segment control in the "Menu View Controller", which should be set to selectedSegmentIndex = 0, when the view was opened through local notifications. I am able to open the View Controller but I do not know how to address the segment Control from app delegate?
This is the code I use:

```<code> // open the menu view controller when notification is pressed

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

        let scene = UIApplication.shared.connectedScenes.first
        if let sceneDelegate = scene?.delegate as? SceneDelegate {
            if let tabController = sceneDelegate.window?.rootViewController as? UITabBarController {
                  tabController.selectedIndex = 0 // index for menu view conntroller
            }
        }

        // set selected index of the segment control equal to zero

        completionHandler()

    }
</code>```

This is how my storyboard looks:

答:
I am not tried your answer , but try this

steps :

initially you need to get the viewcontrollers of tabbarcontroller, like this

```<code> if  let getMenuVC = tabController.viewControllers.first, let getMenu = getMenuVC as? yourMenuController{
  }
</code>```

then you need to get the current class as your menuviewcontroller as like

```<code>  if let getMenu = getMenuVC as? yourMenuController{
  }
</code>```

finally you need to upadte the segment selected index of your current class as like

```<code>   if let getMenu = getMenuVC as? yourMenuController{
         getMenu.yourSegmentedControlName.selectedSegmentIndex = 0
getMenu.yourSegmentedControlName.sendActions(for: UIControl.Event.valueChanged)
      }
</code>```

final code as :

```<code> if let tabController = sceneDelegate.window?.rootViewController as? UITabBarController {
                  tabController.selectedIndex = 0 // index for menu view conntroller
             if  let getMenuVC = tabController.viewControllers?.first, let getMenu = getMenuVC as? yourMenuController{
         getMenu.yourSegmentedControlName.selectedSegmentIndex = 0
getMenu.yourSegmentedControlName.sendActions(for: UIControl.Event.valueChanged)
      }
            }
</code>```

Body:
I want to display the "Menu View Controller" when a local notification was opened. I use a segment control in the "Menu View Controller", which should be set to selectedSegmentIndex = 0, when the view was opened through local notifications. I am able to open the View Controller but I do not know how to address the segment Control from app delegate?
This is the code I use:

 // open the menu view controller when notification is pressed

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

        let scene = UIApplication.shared.connectedScenes.first
        if let sceneDelegate = scene?.delegate as? SceneDelegate {
            if let tabController = sceneDelegate.window?.rootViewController as? UITabBarController {
                  tabController.selectedIndex = 0 // index for menu view conntroller
            }
        }

        // set selected index of the segment control equal to zero

        completionHandler()

    }

This is how my storyboard looks:

Body:
I am not tried your answer , but try this

steps :

initially you need to get the viewcontrollers of tabbarcontroller, like this

 if  let getMenuVC = tabController.viewControllers.first, let getMenu = getMenuVC as? yourMenuController{
  }

then you need to get the current class as your menuviewcontroller as like

  if let getMenu = getMenuVC as? yourMenuController{
  }

finally you need to upadte the segment selected index of your current class as like

   if let getMenu = getMenuVC as? yourMenuController{
         getMenu.yourSegmentedControlName.selectedSegmentIndex = 0
getMenu.yourSegmentedControlName.sendActions(for: UIControl.Event.valueChanged)
      }

final code as :

 if let tabController = sceneDelegate.window?.rootViewController as? UITabBarController {
                  tabController.selectedIndex = 0 // index for menu view conntroller
             if  let getMenuVC = tabController.viewControllers?.first, let getMenu = getMenuVC as? yourMenuController{
         getMenu.yourSegmentedControlName.selectedSegmentIndex = 0
getMenu.yourSegmentedControlName.sendActions(for: UIControl.Event.valueChanged)
      }
            }


问:
i am getting exception navigation failed because browser has disconnected
I'm getting an exception: Navigation failed because browser has disconnected.

After my code gets executed, it will close by the using block.

What is the main reason for the browser to disconnect?.

Here's the exception that I get:

Error on finding navigate urls, screenshot and outgoing urls for Google id 78659 for location in in iteration 0 and error message is :
PuppeteerSharp.NavigationException: Navigation failed because browser
has disconnected! (NetworkManager failed to process
Fetch.requestPaused. Frame 6CCD5A551750D9DF102ABCF53D90B6EB not found.
at
PuppeteerSharp.Helpers.AsyncDictionaryHelper`2.<>c__DisplayClass4_0.b__0()

This is my code:

```<code>using (var destinationUrlBrowser = await Puppeteer.LaunchAsync(launchOptions))
    {
        using (var page = await destinationUrlBrowser.NewPageAsync())
        {
            try
            {
                var viewPortOptions = new ViewPortOptions{Width = 1366, Height = 768};
                await page.SetViewportAsync(viewPortOptions);
                await page.AuthenticateAsync(new Credentials{Username = _luminatiUserName, Password = _luminatiPassword});
                var timeout = new NavigationOptions{Timeout = 50000};
                Response response;
                try
                {
                    response = await page.GoToAsync(destinationUrl, 1 * 50000);
                }
                catch (Exception)
                {
                    response = await page.ReloadAsync(timeout);
                }

                await Task.Delay(2000);
                var pageSource = await page.GetContentAsync();
                if (string.IsNullOrEmpty(pageSource) || pageSource.Contains("Proxy Error"))
                {
                    isDestinationPageSourceNotFound = true;
                }

                if (!isDestinationPageSourceNotFound)
                {
                    var screenShotOptions = new ScreenshotOptions{FullPage = true, Type = ScreenshotType.Jpeg, Quality = 50};
                    Log.Info($"Taking screen shot for {network} id {Id} for location {country}!");
                    await page.ScreenshotAsync(screenShotUrl, screenShotOptions);
                    var chain = response.Request.RedirectChain;
                    var redirects = new HashSet<string>();
                    for (var index = 0; index < chain.Length - 1; index++)
                    {
                        redirects.Add(chain[index].Url);
                    }

                    destinationInfo.Redirects = redirects.ToList();
                    var currentUrl = response.Request.Url;
                    for (int i = 0; i < 2; i++)
                    {
                        response = await page.GoToAsync(currentUrl);
                        var currentUrl1 = response.Request.Url;
                        if (currentUrl != currentUrl1)
                        {
                            currentUrl = currentUrl1;
                            continue;
                        }
                        else
                        {
                            currentUrl = currentUrl1;
                            break;
                        }
                    }

                    destinationInfo.DestinationUrl = currentUrl;
                    Log.Info($"Found {destinationInfo.Redirects.Count} redirect urls from {network} id {Id} for location {country}!");
                    destinationInfo.HtmlPageSource = pageSource;
                    using (var outputFile = new StreamWriter(indexHtml))
                    {
                        await outputFile.WriteAsync(pageSource);
                    }

                    destinationInfo.HtmlContent = Helper.RemoveStyleAndScript(destinationInfo.HtmlPageSource);
                    using (var outputFile = new StreamWriter(htmlContentUrl))
                    {
                        await outputFile.WriteAsync(destinationInfo.HtmlContent);
                    }

                    ZipFile.CreateFromDirectory(basePath, zipPath);
                    destinationInfo.LocalHtmlPath = zipPath;
                    destinationInfo.LocalScreenShot = screenShotUrl;
                    outgoingUrls = Helper.GetOutgoingUrl(pageSource, currentUrl);
                    Log.Info($"Found {outgoingUrls.Count} outgoing urls from {network} id {Id} for location {country}!");
                    foundDetails = true;
                }
            }
            catch (Exception e)
            {
                Log.Info($"Error on finding navigate urls, screenshot and outgoing urls for {network} id {Id} for location {country} in iteration {iterate} and error message is : {e}");
                if (iterate > 1)
                {
                    isDestinationPageSourceNotFound = true;
                }
            }
        }
    }
</code>```

答:
If your code used to work, and it stopped working all of a sudden.

You won't believe it! Chrome version matters so basically if you are using
Version 83.0.4103.61 (Official Build) (64-bit), it will fail and show "Navigation failed because browser has disconnected!" Error.

downgrade your chrome to Version 81.0.4044.138 (Official Build) (64-bit) or below 7X.XX.XXXX.XXX

Note: Make sure you do the same in your server as well. Not just locally

Body:
I'm getting an exception: Navigation failed because browser has disconnected.

After my code gets executed, it will close by the using block.

What is the main reason for the browser to disconnect?.

Here's the exception that I get:

Error on finding navigate urls, screenshot and outgoing urls for Google id 78659 for location in in iteration 0 and error message is :
PuppeteerSharp.NavigationException: Navigation failed because browser
has disconnected! (NetworkManager failed to process
Fetch.requestPaused. Frame 6CCD5A551750D9DF102ABCF53D90B6EB not found.
at
PuppeteerSharp.Helpers.AsyncDictionaryHelper`2.<>c__DisplayClass4_0.b__0()

This is my code:

using (var destinationUrlBrowser = await Puppeteer.LaunchAsync(launchOptions))
    {
        using (var page = await destinationUrlBrowser.NewPageAsync())
        {
            try
            {
                var viewPortOptions = new ViewPortOptions{Width = 1366, Height = 768};
                await page.SetViewportAsync(viewPortOptions);
                await page.AuthenticateAsync(new Credentials{Username = _luminatiUserName, Password = _luminatiPassword});
                var timeout = new NavigationOptions{Timeout = 50000};
                Response response;
                try
                {
                    response = await page.GoToAsync(destinationUrl, 1 * 50000);
                }
                catch (Exception)
                {
                    response = await page.ReloadAsync(timeout);
                }

                await Task.Delay(2000);
                var pageSource = await page.GetContentAsync();
                if (string.IsNullOrEmpty(pageSource) || pageSource.Contains("Proxy Error"))
                {
                    isDestinationPageSourceNotFound = true;
                }

                if (!isDestinationPageSourceNotFound)
                {
                    var screenShotOptions = new ScreenshotOptions{FullPage = true, Type = ScreenshotType.Jpeg, Quality = 50};
                    Log.Info($"Taking screen shot for {network} id {Id} for location {country}!");
                    await page.ScreenshotAsync(screenShotUrl, screenShotOptions);
                    var chain = response.Request.RedirectChain;
                    var redirects = new HashSet<string>();
                    for (var index = 0; index < chain.Length - 1; index++)
                    {
                        redirects.Add(chain[index].Url);
                    }

                    destinationInfo.Redirects = redirects.ToList();
                    var currentUrl = response.Request.Url;
                    for (int i = 0; i < 2; i++)
                    {
                        response = await page.GoToAsync(currentUrl);
                        var currentUrl1 = response.Request.Url;
                        if (currentUrl != currentUrl1)
                        {
                            currentUrl = currentUrl1;
                            continue;
                        }
                        else
                        {
                            currentUrl = currentUrl1;
                            break;
                        }
                    }

                    destinationInfo.DestinationUrl = currentUrl;
                    Log.Info($"Found {destinationInfo.Redirects.Count} redirect urls from {network} id {Id} for location {country}!");
                    destinationInfo.HtmlPageSource = pageSource;
                    using (var outputFile = new StreamWriter(indexHtml))
                    {
                        await outputFile.WriteAsync(pageSource);
                    }

                    destinationInfo.HtmlContent = Helper.RemoveStyleAndScript(destinationInfo.HtmlPageSource);
                    using (var outputFile = new StreamWriter(htmlContentUrl))
                    {
                        await outputFile.WriteAsync(destinationInfo.HtmlContent);
                    }

                    ZipFile.CreateFromDirectory(basePath, zipPath);
                    destinationInfo.LocalHtmlPath = zipPath;
                    destinationInfo.LocalScreenShot = screenShotUrl;
                    outgoingUrls = Helper.GetOutgoingUrl(pageSource, currentUrl);
                    Log.Info($"Found {outgoingUrls.Count} outgoing urls from {network} id {Id} for location {country}!");
                    foundDetails = true;
                }
            }
            catch (Exception e)
            {
                Log.Info($"Error on finding navigate urls, screenshot and outgoing urls for {network} id {Id} for location {country} in iteration {iterate} and error message is : {e}");
                if (iterate > 1)
                {
                    isDestinationPageSourceNotFound = true;
                }
            }
        }
    }


问:
How to revert a Map<String, Collection<XYZ>> to Map<XYZ, Collection<String>> using streams
I have a map like this Map<String, Collection<XYZ>> which I iterated through traditional for each loop to get a result like Map<XYZ, Collection<String>> but the same I couldn't do it with stream on map. Any suggestions on how to do this?

答:
This can be done by flattening your input Map into pairs of String and XYZ, and then collecting them into the desired output Map:

```<code>Map<String, Collection<XYZ>> input = ...
Map<XYZ, List<String>> output =
   input.entrySet()
        .stream()
        .flatMap(e -> e.getValue()
                       .stream()
                       .map(xyz -> new SimpleEntry<XYZ,String>(xyz,e.getKey())))
        .collect(Collectors.groupingBy(Map.Entry::getKey,
                                       Collectors.mapping(Map.Entry::getValue,
                                                          Collectors.toList())));
</code>```

Note that the values in the output Map are Lists instead of Collections. I hope you don't mind (since Lists are also Collections).

Body:
This can be done by flattening your input Map into pairs of String and XYZ, and then collecting them into the desired output Map:

Map<String, Collection<XYZ>> input = ...
Map<XYZ, List<String>> output =
   input.entrySet()
        .stream()
        .flatMap(e -> e.getValue()
                       .stream()
                       .map(xyz -> new SimpleEntry<XYZ,String>(xyz,e.getKey())))
        .collect(Collectors.groupingBy(Map.Entry::getKey,
                                       Collectors.mapping(Map.Entry::getValue,
                                                          Collectors.toList())));

Note that the values in the output Map are Lists instead of Collections. I hope you don't mind (since Lists are also Collections).


问:
pivot rows certain values to columns
i have this table,

```<code>id activity type      start_date
1  a        type_o    01/01/20
1  b        type_o    05/01/20
1  c        type_o    07/01/20
1  d        type_o    23/01/20
1  e        type_o    24/01/20
2  a        type_k    08/01/20
2  b        type_k    10/01/20
2  c        type_k    11/01/20
2  d        type_k    12/01/20
3  a        type_h    12/01/20
3  c        type_h    13/01/20
3  e        type_h    14/01/20
</code>```

all activities are (a,b,c,d,e)
i want it to look like this,

```<code>id type     a         b         c         d         e
1  type_o   01/01/20  05/01/20  07/01/20  23/01/20  24/01/20
2  type_k   08/01/20  10/01/20  11/01/20  null      null
3  type_h   12/01/20  null      13/01/20  null      12/01/20
</code>```

where we compensate null in other activities not exists in some id's,
i don't understand the pivot keyword in sql, any help ?

答:
You must be looking for this:</p>

```<code>SELECT * FROM
(SELECT * FROM YOUR_TABLE)
PIVOT
(MAX(START_DATE) as START_DATE FOR ACTIVITY IN ('a' as a, 'b' as b, 'c' as c, 'd' as d, 'e' as e))
</code>```

Title: pivot rows certain values to columns

Body:
i have this table,

id activity type      start_date
1  a        type_o    01/01/20
1  b        type_o    05/01/20
1  c        type_o    07/01/20
1  d        type_o    23/01/20
1  e        type_o    24/01/20
2  a        type_k    08/01/20
2  b        type_k    10/01/20
2  c        type_k    11/01/20
2  d        type_k    12/01/20
3  a        type_h    12/01/20
3  c        type_h    13/01/20
3  e        type_h    14/01/20

all activities are (a,b,c,d,e)
i want it to look like this,

id type     a         b         c         d         e
1  type_o   01/01/20  05/01/20  07/01/20  23/01/20  24/01/20
2  type_k   08/01/20  10/01/20  11/01/20  null      null
3  type_h   12/01/20  null      13/01/20  null      12/01/20

where we compensate null in other activities not exists in some id's,
i don't understand the pivot keyword in sql, any help ?

Body:
You must be looking for this:

SELECT * FROM
(SELECT * FROM YOUR_TABLE)
PIVOT
(MAX(START_DATE) as START_DATE FOR ACTIVITY IN ('a' as a, 'b' as b, 'c' as c, 'd' as d, 'e' as e))


问:
What is the correct way to fill Model for UserControl?
The question is not about MVC but more about code architecture.

I have a partial view that takes a CompanyModel

```<code><%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<CompanyModel>" %>

<%: Html.TextAreaFor(m => m.Name) %>
<%: Html.TextAreaFor(m => m.Location) %>
</code>```

CompanyModel

```<code>public class CompanyModel
{
     [LocalizedDisplayName("Name", NameResourceType = typeof(Resources.Views.CompanyBackground))]
     public string Name{get;set;}
     [LocalizedDisplayName("Location", NameResourceType = typeof(Resources.Views.CompanyBackground))]
     public string Location{get;set;}

     public CompanyModel()
     {
          var info = Project.GetCompanyInfo();
     }
}
</code>```

Project.GetCompanyInfo() is the DAL layer and gets data from the DB using Entity Framework

My question: what is the "nice" and correct way to fill CompanyModel?:

Solution 1

Create CompanyBag

```<code>public class CompanyBag
{
     public string Name{get;set;}
     public string Location{get;set;}
}
</code>```

and Project.GetCompanyInfo() will return the CompanyBag and in the .ctor of CompanyModel I'll fill the Model.

Solution 2

Project.GetCompanyInfo() will return CompanyModel (and thus no helper class is needed) and I'll fill the Model in the .ctor of CompanyModel

Solution 3

maybe your solution?

UPDATE:
I have LoadController with Load action and this action is kind of a Factory. It will take list of views and will create them by reflection and then load to the page by Html.RenderPartial(viewName, viewModel). So, CompanyModel is just one example of the views and therefore I need each view to be independent.

So my question is: should GetCompanyInfo return a CompanyBag or a CompanyModel and I'll fill the Model in the .ctor?

Thank you

答:
Ok, following the question update, here's my updated answer :)

I'm assuming the different Views LoadController populates take different types of ViewModel, and each ViewModel is populated from a different part of the domain model. Here's how I'd tackle that:

Firstly, create each partial View as a strongly-typed subclass of ViewUserControl<TViewModel>, so LoadController can figure out which ViewModel type it needs for each of the Views it is told to create.

Secondly, define an IViewModelFactory<TViewModel> interface, and create one implementation for each ViewModel type you require; each implementation will know how to create and populate its ViewModel type from your domain model.

Finally, LoadController would figure out the type of ViewModel it needs for each view it's been asked to create, and use the appropriate IViewModelFactory to create it.

To avoid unnecessary overhead, LoadController could find all the available IViewModelFactory implementations at runtime, and keep a static store of them against the type of ViewModel they create.

So to sum up: I would populate CompanyViewModel from a Company using a CompanyViewModelFactory, I would populate a UserViewModel from a User using a UserViewModelFactory, etc. :)

Body:
The question is not about MVC but more about code architecture.

I have a partial view that takes a CompanyModel

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<CompanyModel>" %>

<%: Html.TextAreaFor(m => m.Name) %>
<%: Html.TextAreaFor(m => m.Location) %>

CompanyModel

public class CompanyModel
{
     [LocalizedDisplayName("Name", NameResourceType = typeof(Resources.Views.CompanyBackground))]
     public string Name{get;set;}
     [LocalizedDisplayName("Location", NameResourceType = typeof(Resources.Views.CompanyBackground))]
     public string Location{get;set;}

     public CompanyModel()
     {
          var info = Project.GetCompanyInfo();
     }
}

Project.GetCompanyInfo() is the DAL layer and gets data from the DB using Entity Framework

My question: what is the "nice" and correct way to fill CompanyModel?:

Solution 1

Create CompanyBag

public class CompanyBag
{
     public string Name{get;set;}
     public string Location{get;set;}
}

and Project.GetCompanyInfo() will return the CompanyBag and in the .ctor of CompanyModel I'll fill the Model.

Solution 2

Project.GetCompanyInfo() will return CompanyModel (and thus no helper class is needed) and I'll fill the Model in the .ctor of CompanyModel

Solution 3

maybe your solution?

UPDATE:
I have LoadController with Load action and this action is kind of a Factory. It will take list of views and will create them by reflection and then load to the page by Html.RenderPartial(viewName, viewModel). So, CompanyModel is just one example of the views and therefore I need each view to be independent.

So my question is: should GetCompanyInfo return a CompanyBag or a CompanyModel and I'll fill the Model in the .ctor?

Thank you


问:
Read file with separation in C++
I have a script which reads text file into a vector.

```<code>#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;

struct Items
{
    string Name;
    int Number1;
    double Number2;
};

int main()
{
    ifstream file("file4.txt");
    vector<Items> player_data;
    Items player_info;
    while (file >> player_info.Name >> player_info.Number1 >> player_info.Number2) {
        player_data.push_back(player_info);
    }

    for (auto &i : player_data) {
        std::cout << i.Name << ", " << i.Number1 << ", " << i.Number2 << endl;
    }
}
</code>```

The file4.txt contains as follows:

```<code>Wogger Wabbit
2
6.2
Bilbo Baggins
111
81.3
Mary Poppins
29
154.8
</code>```

How can I display the data properly? How could I give the separation which is a line break ('\n')?

答:
You have a few problems with your code; this solution works but it's not elegant. I'm sure the people here can give you or direct you to a more elegant one :)

First - after opening a file you need to check if it is open

Second - it is better to use std::getline() to read from the file because it gets the whole line. The >> stops when it gets to space.

Also, try not to use using namespace std

EDIT

added print of the error if the file doesn't open

```<code>#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cerrno>
#include  <cstring>

using namespace std;

struct Items
{
  string Name;
  int Number1;
  double Number2;
};

int main()
{
  ifstream file("text4.text");
  if(!file.is_open()) // <- check if file opened correctly
  {
    std::cout << std::strerror(errno); // <- print the reason why the file didnt open
    return 0;
  }
  vector<Items> player_data;
  Items player_info;
  std::string line;
 while(std::getline(file,line)) // <-- read lines and stop when the file is finished
 {
   player_info.Name = line;
   std::getline(file,line);
   player_info.Number1 = stoi(line);
   std::getline(file,line);
   player_info.Number2 = stod(line);
   player_data.push_back(player_info);
 }

  for (auto &i : player_data) {
    std::cout << i.Name << ", " << i.Number1 << ", " << i.Number2 << endl;
  }
}
</code>```

Title: Read file with separation in C++

Body:
I have a script which reads text file into a vector.

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;

struct Items
{
    string Name;
    int Number1;
    double Number2;
};

int main()
{
    ifstream file("file4.txt");
    vector<Items> player_data;
    Items player_info;
    while (file >> player_info.Name >> player_info.Number1 >> player_info.Number2) {
        player_data.push_back(player_info);
    }

    for (auto &i : player_data) {
        std::cout << i.Name << ", " << i.Number1 << ", " << i.Number2 << endl;
    }
}

The file4.txt contains as follows:

Wogger Wabbit
2
6.2
Bilbo Baggins
111
81.3
Mary Poppins
29
154.8

How can I display the data properly? How could I give the separation which is a line break ('\n')?

Body:
You have a few problems with your code; this solution works but it's not elegant. I'm sure the people here can give you or direct you to a more elegant one :)

First - after opening a file you need to check if it is open

Second - it is better to use std::getline() to read from the file because it gets the whole line. The >> stops when it gets to space.

Also, try not to use using namespace std

EDIT

added print of the error if the file doesn't open

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cerrno>
#include  <cstring>

using namespace std;

struct Items
{
  string Name;
  int Number1;
  double Number2;
};

int main()
{
  ifstream file("text4.text");
  if(!file.is_open()) // <- check if file opened correctly
  {
    std::cout << std::strerror(errno); // <- print the reason why the file didnt open
    return 0;
  }
  vector<Items> player_data;
  Items player_info;
  std::string line;
 while(std::getline(file,line)) // <-- read lines and stop when the file is finished
 {
   player_info.Name = line;
   std::getline(file,line);
   player_info.Number1 = stoi(line);
   std::getline(file,line);
   player_info.Number2 = stod(line);
   player_data.push_back(player_info);
 }

  for (auto &i : player_data) {
    std::cout << i.Name << ", " << i.Number1 << ", " << i.Number2 << endl;
  }
}


问:
How to display a data in loop with condition in vue.js/nuxt.js?
I have attached an image that i want to display a checkbox in a column using vue.js/nuxt.js
.I want to display all the checkbox data using for loop and with 3 items to dispaly in  a column.

checkbox

checkbox

checkbox

checkbox

checkbox

checkbox

```

答:
You can iterate over your checkbox-array and then display those checkboxes over a CSS grid.

.grid-box {
  display: grid;
  grid-template-colums: repeat(5, 1fr);
  grid-gap: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid-box">
  <Checkbox v-for="(checkbox, index) in checkboxList" :key="index" />
</div></code>```

You can read more about CSS-Grid here.

Body:
You can iterate over your checkbox-array and then display those checkboxes over a CSS grid.

.grid-box {
  display: grid;
  grid-template-colums: repeat(5, 1fr);
  grid-gap: 10px;
}

<div class="grid-box">
  <Checkbox v-for="(checkbox, index) in checkboxList" :key="index" />
</div>

You can read more about CSS-Grid here.