问:
How to update state from static method in Flutter?
I have a bottom nav bar that uses this code to switch widgets:

```<code>    void _onItemTapped(int index) {
    setState(() {
      selectedIndexGlobal = index;
      print(index);
    });
  }
</code>```

And shows the needed widgets in body:

```<code>body: SafeArea(
    child: new LayoutBuilder(
          builder: (BuildContext context, BoxConstraints constraints) {
            Container con = Container(
                child: _widgetOptions.elementAt(selectedIndexGlobal)
            );
            return con;
          }
      ))
</code>```

I also have a GridView with static children list loaded from Firebase, and tried to apply a GestureDetector to it, to change selectedIndex and update screen state:

```<code>static getExpenseItems(AsyncSnapshot<QuerySnapshot> snapshot, BuildContext context) {
    try {
      snapshot.data.documents.sort((a, b) =>
          a.data["order"].compareTo(b.data["order"]));
    } on NoSuchMethodError {}

    return snapshot.data.documents
        .map((doc) =>
    new GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
        catName = doc["catName"];
        setState(() {
          selectedIndexGlobal = 4;
        });
        },
        child: new Container(
            child: Container(
                    padding: EdgeInsets.only(top: 15, left: 10, bottom: 15),
                    decoration: new BoxDecoration(
                        border: new Border.all(color: Colors.grey[200],
                        width: 0.8)),
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: Text(doc["name"],
                          style: TextStyle(fontSize: categoriesFont),
                          textAlign: TextAlign.center),
                    )
                )
        )

    )
    ).toList();
  }
</code>```

But setState can't be called from a static method, as well as GridView.count doesn't let me use non-static widgets as child. What should I do then to update state on click?

答:
This line will help you get the instance of the Widget State object you need.

All you need access to is the current context object:

```<code>  _HomeState stateObject = context.findAncestorStateOfType<_HomeState>();

  stateObject.setState(() {
     _tabIndex = index;
  });
</code>```

For this to work, ensure that the context you use to access the State Object is from a child widget of the State object you are trying to find.

Body:
I have a bottom nav bar that uses this code to switch widgets:

    void _onItemTapped(int index) {
    setState(() {
      selectedIndexGlobal = index;
      print(index);
    });
  }

And shows the needed widgets in body:

body: SafeArea(
    child: new LayoutBuilder(
          builder: (BuildContext context, BoxConstraints constraints) {
            Container con = Container(
                child: _widgetOptions.elementAt(selectedIndexGlobal)
            );
            return con;
          }
      ))

I also have a GridView with static children list loaded from Firebase, and tried to apply a GestureDetector to it, to change selectedIndex and update screen state:

static getExpenseItems(AsyncSnapshot<QuerySnapshot> snapshot, BuildContext context) {
    try {
      snapshot.data.documents.sort((a, b) =>
          a.data["order"].compareTo(b.data["order"]));
    } on NoSuchMethodError {}

    return snapshot.data.documents
        .map((doc) =>
    new GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
        catName = doc["catName"];
        setState(() {
          selectedIndexGlobal = 4;
        });
        },
        child: new Container(
            child: Container(
                    padding: EdgeInsets.only(top: 15, left: 10, bottom: 15),
                    decoration: new BoxDecoration(
                        border: new Border.all(color: Colors.grey[200],
                        width: 0.8)),
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: Text(doc["name"],
                          style: TextStyle(fontSize: categoriesFont),
                          textAlign: TextAlign.center),
                    )
                )
        )

    )
    ).toList();
  }

But setState can't be called from a static method, as well as GridView.count doesn't let me use non-static widgets as child. What should I do then to update state on click?

Body:
This line will help you get the instance of the Widget State object you need.

All you need access to is the current context object:

  _HomeState stateObject = context.findAncestorStateOfType<_HomeState>();

  stateObject.setState(() {
     _tabIndex = index;
  });

For this to work, ensure that the context you use to access the State Object is from a child widget of the State object you are trying to find.


来源: stackexchange

问:
The column of the csv file in google automl tables is recognised as text or categorical instead of numeric as i would like
I tried to train a model using google automl tables but i have the following problem

The csv file is correctly imported, it has 2 columns and about 1870 rows, all numeric.
The system recognises only 1 column as numeric but not the other.
The column, where the problem is, has 5 digits in each row separated with space.

Is there anything i should do in order for the system to properly recognise the data as numeric?

Thanks in advance for your help

答:
The issue is with the Data type Numeric definition, the number needs to be comparable (greater than, smaller than, equal).

Two different list of numbers are not comparable, for example 2 4 7 is not comparable to 1 5 7. To solve this, without using strings and therefore losing the "information" of those numbers, you have several options.

For example:

Create an array of numbers, by inserting [ ] in the limits of the second entrance. Take into consideration the Array Data type relative weighted approach in AutoMl tables as it may affect the "information" extracted from the sequence.

Create additional columns for every entry of the second column so each one is a single number and hence truly numeric.

I would personally go for the second option.

If you are afraid of losing "information" by splitting the numbers take into consideration that after training, the model should deduce by itself the importance of the position and other "information" those number sequences might contain (mean, norm/modulus,relative increase,...) provided the training data is representative.

ContentLicense: CC BY-SA 4.0


问:
Problem of large size of .apk file in android?
I have a problem that arise due to large size and no. of images in app, my app stopped installing on emulator. It gives an error report " No Space Left". Size of .apk file is about 60MB. Now, I would like to ask the following questions:

What could be done in this situation, so that it gets installed and doesn't gives this error?

Does android market allow to install app of this size?

Thanks in advance

答: At Present limit of android market is 50 MB. so you can compress your images with some image compression and if you have used video or audio then also you can compress so you can achieved 50 MB. many compression tool is available.</p>

ContentLicense: CC BY-SA 3.0


问:
SwiftUI - Save results of a Form to JSON
I'm new to SwiftUI, haven't coded in 15 years, but taking this on as a hobby. I am trying to take the results of a form and convert it to JSON so that I can save the output to a database. Can anyone provide some guidance?

```<code>var body: some View {
   Form {
      Section(header: Text("Section 1")) {
          Toggle(isOn: $answer1) {
             Text("How would you like to answer this question?")
          }
          ...
      }
      ...
   }
   NavigationLink(destination: FormResult()) {
      Text("Submit")
   }
}
</code>```

How do I make that form into a JSON? Does it need to be codable?

答:
You don't convert a Form directly to JSON. You rather bind the form to an object of a new type that you declare, and work with the object in code.

When you need to serialize the data, either for a network request or for storage, you can convert your object to JSON. If your type conforms to Codable, you can use JSONEncoder/JSONDecoder to convert to/from its JSON representation.

So here's the concept:

```<code>struct Answer: Codable {
  var isOn: Bool = false
  var question: String
  var answer: String = ""
}

struct IntroForm: Codable {
  var nameAnswer    = Answer(question: "What's your name?")
  var meaningAnswer = Answer(question: "What's the meaning of life?")
}
</code>```

```<code>@State var form = IntroForm()
var body: some View {
   Form {
      Section(header: Text("Section 1")) {
          Toggle(isOn: $form.nameAnswer.isOn) {
             Text("How would you like to answer this question?")
          }
          if form.nameAnswer.isOn {
             TextField(form.nameAnswer.question, text: $form.nameAnswer.answer)
          }
          ...
      }
   ...
}
</code>```

When you need to serialize, you can use JSONEncoder:

```<code>let encoder = JSONEncoder()
let jsonData = try? encoder.encode(form)
let jsonStr = String(data: jsonData, encoding: .utf8)

</code>```

Body:
I'm new to SwiftUI, haven't coded in 15 years, but taking this on as a hobby. I am trying to take the results of a form and convert it to JSON so that I can save the output to a database. Can anyone provide some guidance?

var body: some View {
   Form {
      Section(header: Text("Section 1")) {
          Toggle(isOn: $answer1) {
             Text("How would you like to answer this question?")
          }
          ...
      }
      ...
   }
   NavigationLink(destination: FormResult()) {
      Text("Submit")
   }
}

How do I make that form into a JSON? Does it need to be codable?

Body:
You don't convert a Form directly to JSON. You rather bind the form to an object of a new type that you declare, and work with the object in code.

When you need to serialize the data, either for a network request or for storage, you can convert your object to JSON. If your type conforms to Codable, you can use JSONEncoder/JSONDecoder to convert to/from its JSON representation.

So here's the concept:

struct Answer: Codable {
  var isOn: Bool = false
  var question: String
  var answer: String = ""
}

struct IntroForm: Codable {
  var nameAnswer    = Answer(question: "What's your name?")
  var meaningAnswer = Answer(question: "What's the meaning of life?")
}

@State var form = IntroForm()
var body: some View {
   Form {
      Section(header: Text("Section 1")) {
          Toggle(isOn: $form.nameAnswer.isOn) {
             Text("How would you like to answer this question?")
          }
          if form.nameAnswer.isOn {
             TextField(form.nameAnswer.question, text: $form.nameAnswer.answer)
          }
          ...
      }
   ...
}

When you need to serialize, you can use JSONEncoder:

let encoder = JSONEncoder()
let jsonData = try? encoder.encode(form)
let jsonStr = String(data: jsonData, encoding: .utf8)


问:
How can I convert the datetime intervals into a dataframe?
I would like to make a dataframe of dates with an interval of a week. I have used the following codes to generate a list of dates but when I want to make this into a dataframe, I got this error:

ValueError: DataFrame constructor not properly called!

Could you give me a hlep?

```<code>import pandas as pd

from datetime import date, datetime, timedelta

def perdelta(start, end, delta):
    curr = start
    while curr < end:
        yield curr
        curr += delta

for dates in perdelta(date(1997, 7, 19), date(2020, 5, 25), timedelta(days=7)):
    OP_dates = pd.DataFrame(dates)

print(OP_dates.head(3))
</code>```

答:
Don't need a loop here:

```<code>OP_dates = pd.DataFrame(perdelta(date(1997, 7, 19), date(2020, 5, 25), timedelta(days=7)))
</code>```

Using a loop:

```<code>OP_dates = pd.DataFrame()
for dates in perdelta(date(1997, 7, 19), date(2020, 5, 25), timedelta(days=7)):
    OP_dates = pd.DataFrame.append(OP_dates, [dates])
</code>```

Body:
I would like to make a dataframe of dates with an interval of a week. I have used the following codes to generate a list of dates but when I want to make this into a dataframe, I got this error:

ValueError: DataFrame constructor not properly called!

Could you give me a hlep?

import pandas as pd

from datetime import date, datetime, timedelta

def perdelta(start, end, delta):
    curr = start
    while curr < end:
        yield curr
        curr += delta

for dates in perdelta(date(1997, 7, 19), date(2020, 5, 25), timedelta(days=7)):
    OP_dates = pd.DataFrame(dates)

print(OP_dates.head(3))

Body:
Don't need a loop here:

OP_dates = pd.DataFrame(perdelta(date(1997, 7, 19), date(2020, 5, 25), timedelta(days=7)))

Using a loop:

OP_dates = pd.DataFrame()
for dates in perdelta(date(1997, 7, 19), date(2020, 5, 25), timedelta(days=7)):
    OP_dates = pd.DataFrame.append(OP_dates, [dates])


问:
fpdi with tcpdf new added text not showing in the pdf
I am trying to adding text in existing pdf using fpdi with tcpdf library. but text are not showing on the pdf. if i search pdf text can be highlighted but it is hidden on pdf. i have tried z-index too but still not appear.

please see below is my code.

```<code>$pdf = new FPDI();
$pageCount = $pdf->setSourceFile('102215_2019_unlocked.pdf');
for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
// import a page
$templateId = $pdf->importPage($pageNo);
// get the size of the imported page
$size = $pdf->getTemplateSize($templateId);
//$pdf->setPrintHeader(false);

// create a page (landscape or portrait depending on the imported page size)
if ($size['w'] > $size['h']) {
$pdf->AddPage('L', array($size['w'], $size['h']));
// Font size 1/3 Height if it landscape
$fontsize = $size['h'] / 3;
} else {
$pdf->AddPage('P', array($size['w'], $size['h']));

// Font size 1/3 Width if it portrait
$fontsize = $size['w'] / 3;
}

$html = '<h1 style="z-index:-1;color:black;">[![HTML Example][1]][1]</h1>';

// output the HTML content
$pdf->writeHTML($html, true, false, true, false, '');

$pdf->useTemplate($templateId);

// $pdf->SetAlpha(1);
}

$pdf->output();
</code>```

答:
ok i have found answer myself finally.

usetemplate function was needed to put before the text and my image applied.

like this

```<code>$pdf->useTemplate($templateId);

$pdf->StartTransform();

$pdf->Image('logo.png', 175, 5, 35, 0, 'PNG','https://franchimp.com');

$pdf->SetFont('Helvetica', 'B', 70);
$pdf->SetTextColor(31, 156, 239);
$pdf->SetAlpha(0.5);
$pdf->SetXY(20, 180);
$pdf->Rotate(35);
$pdf->Write(0, 'franchimp.com');
$pdf->StopTransform();
</code>```

Body:
I am trying to adding text in existing pdf using fpdi with tcpdf library. but text are not showing on the pdf. if i search pdf text can be highlighted but it is hidden on pdf. i have tried z-index too but still not appear.

please see below is my code.

$pdf = new FPDI();
$pageCount = $pdf->setSourceFile('102215_2019_unlocked.pdf');
for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
// import a page
$templateId = $pdf->importPage($pageNo);
// get the size of the imported page
$size = $pdf->getTemplateSize($templateId);
//$pdf->setPrintHeader(false);

// create a page (landscape or portrait depending on the imported page size)
if ($size['w'] > $size['h']) {
$pdf->AddPage('L', array($size['w'], $size['h']));
// Font size 1/3 Height if it landscape
$fontsize = $size['h'] / 3;
} else {
$pdf->AddPage('P', array($size['w'], $size['h']));

// Font size 1/3 Width if it portrait
$fontsize = $size['w'] / 3;
}

$html = '
[![HTML Example][1]][1]
';

// output the HTML content
$pdf->writeHTML($html, true, false, true, false, '');

$pdf->useTemplate($templateId);

// $pdf->SetAlpha(1);
}

$pdf->output();

Body:
ok i have found answer myself finally.

usetemplate function was needed to put before the text and my image applied.

like this

$pdf->useTemplate($templateId);

$pdf->StartTransform();

$pdf->Image('logo.png', 175, 5, 35, 0, 'PNG','https://franchimp.com');

$pdf->SetFont('Helvetica', 'B', 70);
$pdf->SetTextColor(31, 156, 239);
$pdf->SetAlpha(0.5);
$pdf->SetXY(20, 180);
$pdf->Rotate(35);
$pdf->Write(0, 'franchimp.com');
$pdf->StopTransform();


问:
Formatting table in Jupyter
I was trying to make a table in Python, but there are some elements that don't fit... I've tried everything that I know and I'm not getting why this is getting like this

The code is this:

```<code>    print("Year nº \t\t Stdts 1st year \t\t Stdts 2nd year \t\t Stdts 3rd years \t\t Stdts 4th year \t\t Stdts 5th year \n") #1st line of the table
    print(" %d \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t \n" %(actualYear, N1, N2, N3, N4, N5)) #Year 0 of the table

    while actualYear < 19:
          ...
    print(" %d \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t \n" %(actualYear, N1, N2, N3, N4, N5))
</code>```

Thanks in advance.

答:
The easiest way to do this, is using pandas.DataFrame.
There are two ways to reach the result you want:

Method 1: typing values in Python to create Pandas DataFrame

```<code>import pandas as pd

cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'],
        'Price': [22000,25000,27000,35000]
        }

df = pd.DataFrame(cars, columns = ['Brand', 'Price'])

print (df)
</code>```

Method 2: importing values from an Excel file to create Pandas DataFrame

```<code>import pandas as pd

data = pd.read_excel(r'Path where the Excel file is stored\File name.xlsx')
df = pd.DataFrame(data, columns = ['First Column Name','Second Column Name',...])

print (df)
</code>```

Hope this helped you.

Title: Formatting table in Jupyter

Body:
I was trying to make a table in Python, but there are some elements that don't fit... I've tried everything that I know and I'm not getting why this is getting like this

The code is this:

    print("Year nº \t\t Stdts 1st year \t\t Stdts 2nd year \t\t Stdts 3rd years \t\t Stdts 4th year \t\t Stdts 5th year \n") #1st line of the table
    print(" %d \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t \n" %(actualYear, N1, N2, N3, N4, N5)) #Year 0 of the table

    while actualYear < 19:
          ...
    print(" %d \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t \n" %(actualYear, N1, N2, N3, N4, N5))

Thanks in advance.

Body:
The easiest way to do this, is using pandas.DataFrame.
There are two ways to reach the result you want:

Method 1: typing values in Python to create Pandas DataFrame

import pandas as pd

cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'],
        'Price': [22000,25000,27000,35000]
        }

df = pd.DataFrame(cars, columns = ['Brand', 'Price'])

print (df)

Method 2: importing values from an Excel file to create Pandas DataFrame

import pandas as pd

data = pd.read_excel(r'Path where the Excel file is stored\File name.xlsx')
df = pd.DataFrame(data, columns = ['First Column Name','Second Column Name',...])

print (df)

Hope this helped you.


问:
extract mean of circle patche in python
i have some X/Y coordinates that represent the center of a circle somewhere in an image. From that circle, i want to compoute the mean of all the point contained inside the circle.

currently, i compute the mean of a square patche as follow, but a square is not relevent for the project. Ideally, i would like to do it only with numpy. but if it is not possible, i would concidere something else.

```<code>mean = np.mean(image[Y - margin : Y + margin, X - margin, X + margin])
</code>```

答:
i found a solution where I compute all indexes contained in a centered disk.

I calculate the squarred euclidean distance of each X/Y coordinate of a squarre array.

I compare it to the squarred radius of the circle.

If it is superior, the point is not contained in the circle. Mark it as 0, 1 otherwise

I extract indexes where the array is equal to one (disk-shaped)

I center the computed indexes. To use them, i add the X/Y coordinate of a specific image point.

NOTE: I used the squarred euclidean distance because the square root function is monotonic (i.e constantly increasing). So, it saves compational power to keep with the squarred version.

```<code>radius = 4
size = 2 * radius + 1
radiusSquarred= radius**2
mask = np.zeros((size, size))
distance = lambda x, y: (x-radius)**2 + (y-radius)**2
for i in range(size):
    for j in range (2 * radius+ 1):
        if distance(i, j) <= radiusSquarred:
            mask[i, j] = 1
index = np.where(mask == 1)
diskIndexes = (index[0] - radius, index[1] - radius)

X, Y = 100, 150
np.mean(image[diskIndexes[0] + Y, diskIndexes[1] + X])
</code>```

Title: extract mean of circle patche in python

Body:
i have some X/Y coordinates that represent the center of a circle somewhere in an image. From that circle, i want to compoute the mean of all the point contained inside the circle.

currently, i compute the mean of a square patche as follow, but a square is not relevent for the project. Ideally, i would like to do it only with numpy. but if it is not possible, i would concidere something else.

mean = np.mean(image[Y - margin : Y + margin, X - margin, X + margin])

Body:
i found a solution where I compute all indexes contained in a centered disk.

I calculate the squarred euclidean distance of each X/Y coordinate of a squarre array.

I compare it to the squarred radius of the circle.

If it is superior, the point is not contained in the circle. Mark it as 0, 1 otherwise

I extract indexes where the array is equal to one (disk-shaped)

I center the computed indexes. To use them, i add the X/Y coordinate of a specific image point.

NOTE: I used the squarred euclidean distance because the square root function is monotonic (i.e constantly increasing). So, it saves compational power to keep with the squarred version.

radius = 4
size = 2 * radius + 1
radiusSquarred= radius**2
mask = np.zeros((size, size))
distance = lambda x, y: (x-radius)**2 + (y-radius)**2
for i in range(size):
    for j in range (2 * radius+ 1):
        if distance(i, j) <= radiusSquarred:
            mask[i, j] = 1
index = np.where(mask == 1)
diskIndexes = (index[0] - radius, index[1] - radius)

X, Y = 100, 150
np.mean(image[diskIndexes[0] + Y, diskIndexes[1] + X])


问:
Why does Bootstrap only have classes for up to 12 columns? Why not more?
Why am I limited to 12 columns? Why isn't by default more, for more flexibility?

Let me explain what confuses me. Let's say I want to create a simple page with a left menu, and a content on the right.

```<code><div class="col-sm-3">Left menu</div> <!-- 258px -->
<div class="col-sm-9">Content</div> <!-- 772px -->

<div class="col-sm-4">Left menu</div> <!-- 343px -->
<div class="col-sm-8">Content</div> <!-- 687px -->
</code>```

As seen in this example above, the difference between sm-3 and sm-4 is almost 100px for the menu! If I want the menu to be 300px, I can't use the grid. If I had more columns, I could be more precise than that.

Am I using the grid system the wrong way? Why is the grid divided into so few columns?

答: As it would appear 12 is an arbitrary value, could it be 12 as there are 12" in a foot?</p>

Body:
Why am I limited to 12 columns? Why isn't by default more, for more flexibility?

Let me explain what confuses me. Let's say I want to create a simple page with a left menu, and a content on the right.

Left menu

Content

Left menu

Content

As seen in this example above, the difference between sm-3 and sm-4 is almost 100px for the menu! If I want the menu to be 300px, I can't use the grid. If I had more columns, I could be more precise than that.

Am I using the grid system the wrong way? Why is the grid divided into so few columns?


问:
Columns children cannot return null, but returning would stop the loop
I am trying to iterate through a list and produce a widget (Text) for now for each 'step' in the list.

When printing I get exactly as expected, however, I get the error Column's children must not contain any null values, but a null value was found at index 0.

Which I understand as I am not returning anything. But if I do return something the loop stops, so I just get the first step.

```<code>recipeMethodList(recipeMethod) {
for (var step in recipeMethod) {
  stepNumber = stepNumber + 1;
  Row(
    children: <Widget>[
      Text('$stepNumber. $step'),
    ],
  );
  print('$stepNumber. $step');
}
</code>```

I call this with:

```<code>Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[recipeMethodList(recipeMethod)],
            ),
</code>```

答:
I solved this by building a new list. One which contains widgets of my choosing. Then returning that list to the builder.</p>

```<code>    methodCard(recipeMethod, context) {
    List<Padding> methodList = [];
    for (var step in recipeMethod) {
      stepNumber++;
      methodList.add(
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Container(
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(15), color: Colors.white),
            padding: EdgeInsets.symmetric(horizontal: 10.0),
            width: MediaQuery.of(context).size.width,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 12.0),
                  child: Text(
                    '$stepNumber. $step',
                    style: TextStyle(
                        fontSize: 16.0,
                        fontFamily: 'NotoSans',
                        color: Colors.black),
                  ),
                ),
              ],
            ),
          ),
        ),
      );
    }
    return methodList;
  }
</code>```

Body:
I am trying to iterate through a list and produce a widget (Text) for now for each 'step' in the list.

When printing I get exactly as expected, however, I get the error Column's children must not contain any null values, but a null value was found at index 0.

Which I understand as I am not returning anything. But if I do return something the loop stops, so I just get the first step.

recipeMethodList(recipeMethod) {
for (var step in recipeMethod) {
  stepNumber = stepNumber + 1;
  Row(
    children: <Widget>[
      Text('$stepNumber. $step'),
    ],
  );
  print('$stepNumber. $step');
}

I call this with:

Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[recipeMethodList(recipeMethod)],
            ),

Body:
I solved this by building a new list. One which contains widgets of my choosing. Then returning that list to the builder.

    methodCard(recipeMethod, context) {
    List<Padding> methodList = [];
    for (var step in recipeMethod) {
      stepNumber++;
      methodList.add(
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Container(
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(15), color: Colors.white),
            padding: EdgeInsets.symmetric(horizontal: 10.0),
            width: MediaQuery.of(context).size.width,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 12.0),
                  child: Text(
                    '$stepNumber. $step',
                    style: TextStyle(
                        fontSize: 16.0,
                        fontFamily: 'NotoSans',
                        color: Colors.black),
                  ),
                ),
              ],
            ),
          ),
        ),
      );
    }
    return methodList;
  }


问:
Changing image in django user change form
I am making a django webapp where users can upload profile image. I have also created an EDIT PROFILE page by using the default USERCHANGEFORM. But the problem is, that I cannot update the profile picture from that form. I can delete it but not upload new one? Help needed.
This is my USER CREATION FORM:

```<code>
class SignUpForm(UserCreationForm):

    photo               = forms.ImageField(required=False)
    bio                 = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your bio'}))
    designation         = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your designation'}))
    university          = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your university'}))

    company_name        = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's name"}))
    grad_year           = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'What year did you graduate in?'}))
    phone               = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your phone number'}))
    address             = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your present address'}))
    city                = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your city'}))
    company_category    = forms.CharField(widget=forms.TextInput(attrs={'placeholder':  "Enter your company's category"}))
    company_desc        = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's description"}))
    company_site        = forms.CharField()
    no_employees        = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'Enter no. of employees in your company'}))
    technologies        = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'What technologies are you interested in?'}))
    markets             = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'What markets are you interested in?'}))
    linkedin            = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your Linked In profile'}))

    def __init__(self, *args, **kwargs):
        super(UserCreationForm, self).__init__(*args, **kwargs)
        del self.fields['password2']

        for fieldname in ['password1']:
            self.fields[fieldname].help_text = None

        self.fields['password1'].widget.attrs.update({'placeholder': 'Enter your password'})
        self.fields['first_name'].widget.attrs.update({'placeholder': 'Enter your first name'})
        self.fields['last_name'].widget.attrs.update({'placeholder': 'Enter your last name'})
        self.fields['company_site'].widget.attrs.update({'placeholder': "Enter company's website"})
        for field in ['email',
                   'password1',
                   'first_name',
                   'last_name',
                   'bio',
                   'designation',
                   'university',
                   'company_name',
                   'grad_year',
                   'phone',
                   'photo',
                   'address',
                   'city',
                   'company_category',
                   'company_desc',
                   'company_site',
                   'no_employees',
                   'technologies',
                   'markets',
                   'linkedin']:

                   self.fields[field].widget.attrs['class'] = "col-lg-4 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6 form-control"
                   self.fields[field].widget.attrs['style'] = "padding:20px;"

        self.fields['photo'].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-1 "

    class Meta:
        model = User
        widgets = {
        "email": forms.fields.TextInput(attrs={'placeholder':'Enter your email'}),
        }
        fields = ('email',
                   'password1',
                  'first_name',
                  'last_name',
                   'photo',
                   'bio',
                   'designation',
                   'university',
                   'company_name',
                   'grad_year',
                   'phone',
                   'address',
                   'city',
                   'company_category',
                   'company_desc',
                    'company_site',
                   'no_employees',
                   'technologies',
                   'markets',
                   'linkedin')

</code>```

This is my USER CHANGE FORM

```<code>class EditProfileForm(UserChangeForm):

    def __init__(self, *args, **kwargs):
        super(UserChangeForm, self).__init__(*args, **kwargs)

        for field in [
                    'first_name',
                    'last_name',
                    'bio',
                    'designation',
                    'university',
                    'company_name',
                    'grad_year',
                    'phone',
                    'address',
                    'city',
                    'company_category',
                    'company_desc',
                    'company_site',
                    'no_employees',
                    'technologies',
                    'markets',
                    'linkedin']:
            self.fields[field].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6 form-control"
            self.fields[field].widget.attrs['style'] = "padding:20px;"

        self.fields['photo'].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6"
        self.fields['password'].widget.attrs['class'] = "hidden"

    class Meta:
        model = User
        fields = ('first_name',
        'last_name',
        "photo",
        "bio",
        "designation",
        "university",
        "company_name",
        "grad_year",
        "phone",
        "address",
        "city",
        "company_category",
        "company_desc",
         "company_site",
        "no_employees",
        "technologies",
        "markets",
        "linkedin"
        )```
```

答:
Try this!

In your EditProfileForm

replace

```<code>super(UserChangeForm, self).__init__(*args, **kwargs)
</code>```

to

```<code>super(EditProfileForm, self).__init__(*args, **kwargs)
</code>```

same in your SignUpForm
replace

```<code>super(UserCreationForm, self).__init__(*args, **kwargs)
</code>```

to

```<code>super(SignUpForm, self).__init__(*args, **kwargs)
</code>```

And you forgot to add photo inside EditProfileForm for field in [...]

Body:
I am making a django webapp where users can upload profile image. I have also created an EDIT PROFILE page by using the default USERCHANGEFORM. But the problem is, that I cannot update the profile picture from that form. I can delete it but not upload new one? Help needed.
This is my USER CREATION FORM:

class SignUpForm(UserCreationForm):

    photo               = forms.ImageField(required=False)
    bio                 = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your bio'}))
    designation         = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your designation'}))
    university          = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your university'}))

    company_name        = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's name"}))
    grad_year           = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'What year did you graduate in?'}))
    phone               = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your phone number'}))
    address             = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your present address'}))
    city                = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your city'}))
    company_category    = forms.CharField(widget=forms.TextInput(attrs={'placeholder':  "Enter your company's category"}))
    company_desc        = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's description"}))
    company_site        = forms.CharField()
    no_employees        = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'Enter no. of employees in your company'}))
    technologies        = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'What technologies are you interested in?'}))
    markets             = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'What markets are you interested in?'}))
    linkedin            = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your Linked In profile'}))

    def __init__(self, *args, **kwargs):
        super(UserCreationForm, self).__init__(*args, **kwargs)
        del self.fields['password2']

        for fieldname in ['password1']:
            self.fields[fieldname].help_text = None

        self.fields['password1'].widget.attrs.update({'placeholder': 'Enter your password'})
        self.fields['first_name'].widget.attrs.update({'placeholder': 'Enter your first name'})
        self.fields['last_name'].widget.attrs.update({'placeholder': 'Enter your last name'})
        self.fields['company_site'].widget.attrs.update({'placeholder': "Enter company's website"})
        for field in ['email',
                   'password1',
                   'first_name',
                   'last_name',
                   'bio',
                   'designation',
                   'university',
                   'company_name',
                   'grad_year',
                   'phone',
                   'photo',
                   'address',
                   'city',
                   'company_category',
                   'company_desc',
                   'company_site',
                   'no_employees',
                   'technologies',
                   'markets',
                   'linkedin']:

                   self.fields[field].widget.attrs['class'] = "col-lg-4 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6 form-control"
                   self.fields[field].widget.attrs['style'] = "padding:20px;"

        self.fields['photo'].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-1 "

    class Meta:
        model = User
        widgets = {
        "email": forms.fields.TextInput(attrs={'placeholder':'Enter your email'}),
        }
        fields = ('email',
                   'password1',
                  'first_name',
                  'last_name',
                   'photo',
                   'bio',
                   'designation',
                   'university',
                   'company_name',
                   'grad_year',
                   'phone',
                   'address',
                   'city',
                   'company_category',
                   'company_desc',
                    'company_site',
                   'no_employees',
                   'technologies',
                   'markets',
                   'linkedin')

This is my USER CHANGE FORM

class EditProfileForm(UserChangeForm):

    def __init__(self, *args, **kwargs):
        super(UserChangeForm, self).__init__(*args, **kwargs)

        for field in [
                    'first_name',
                    'last_name',
                    'bio',
                    'designation',
                    'university',
                    'company_name',
                    'grad_year',
                    'phone',
                    'address',
                    'city',
                    'company_category',
                    'company_desc',
                    'company_site',
                    'no_employees',
                    'technologies',
                    'markets',
                    'linkedin']:
            self.fields[field].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6 form-control"
            self.fields[field].widget.attrs['style'] = "padding:20px;"

        self.fields['photo'].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6"
        self.fields['password'].widget.attrs['class'] = "hidden"

    class Meta:
        model = User
        fields = ('first_name',
        'last_name',
        "photo",
        "bio",
        "designation",
        "university",
        "company_name",
        "grad_year",
        "phone",
        "address",
        "city",
        "company_category",
        "company_desc",
         "company_site",
        "no_employees",
        "technologies",
        "markets",
        "linkedin"
        )```

Body:
Try this!

In your EditProfileForm

replace

super(UserChangeForm, self).__init__(*args, **kwargs)

to

super(EditProfileForm, self).__init__(*args, **kwargs)

same in your SignUpForm
replace

super(UserCreationForm, self).__init__(*args, **kwargs)

to

super(SignUpForm, self).__init__(*args, **kwargs)

And you forgot to add photo inside EditProfileForm for field in [...]


问:
Windows Batch - For Loop - NOT IN
Most of the examples on using Windows Batch For Loop is about using "IN".

```<code>FOR %%A IN (1 2 3 4) DO ECHO %%A
</code>```

I need to use NOT IN instead. When I type something as:

```<code>FOR %%A NOT IN (1 2 3 4) DO ECHO %%A
</code>```

It says "NOT was not expected at that time".

Thanks

答:
I had the same problem, but no solution.
So... that's my personal, simple, solution:</p>

```<code>@echo off
rem set the path to check
set sourcePath=C:\Program Files (x86)\MySoftware
set destPath=c:\temp\MySoftware-StrangerFiles
set tempPath=c:\temp
set currentFilesListTxtFileName=MySoftware-allfiles.txt
set correctFilesListTxtFileName=MySoftware-correctFilesList.txt
set moveFilesListTxtFileName=MySoftware-moveFilesList.txt
echo Move not allowed files in a different path
cd "%sourcePath%"
mkdir %destPath%

call :correctFilesList

dir /B > c:\temp\MySoftware-allfiles.txt
findstr /V /G:%tempPath%\%correctFilesListTxtFileName% %tempPath%\%currentFilesListTxtFileName% > %tempPath%\%moveFilesListTxtFileName%
for /f "delims=" %%a in (' type "%tempPath%\%moveFilesListTxtFileName%" ') do move %%a %destPath%
pause

:correctFilesList
rem files whitelist
rem correctfiles can be changed with "dir /B path>>c:\temp\correctFilesList.txt" from a correct source. Or you can generate a list of correct files via command as below.
echo correctfile1.dll>> %tempPath%\%correctFilesListTxtFileName%.txt
echo correctfile2.log.xml>> %tempPath%\%correctFilesListTxtFileName%.txt
echo correctfile2.log.xml>> %tempPath%\MySoftware-correctFilesList.txt
</code>```

Title: Windows Batch - For Loop - NOT IN

Body:
Most of the examples on using Windows Batch For Loop is about using "IN".

FOR %%A IN (1 2 3 4) DO ECHO %%A

I need to use NOT IN instead. When I type something as:

FOR %%A NOT IN (1 2 3 4) DO ECHO %%A

It says "NOT was not expected at that time".

Thanks

Body:
I had the same problem, but no solution.
So... that's my personal, simple, solution:

@echo off
rem set the path to check
set sourcePath=C:\Program Files (x86)\MySoftware
set destPath=c:\temp\MySoftware-StrangerFiles
set tempPath=c:\temp
set currentFilesListTxtFileName=MySoftware-allfiles.txt
set correctFilesListTxtFileName=MySoftware-correctFilesList.txt
set moveFilesListTxtFileName=MySoftware-moveFilesList.txt
echo Move not allowed files in a different path
cd "%sourcePath%"
mkdir %destPath%

call :correctFilesList

dir /B > c:\temp\MySoftware-allfiles.txt
findstr /V /G:%tempPath%\%correctFilesListTxtFileName% %tempPath%\%currentFilesListTxtFileName% > %tempPath%\%moveFilesListTxtFileName%
for /f "delims=" %%a in (' type "%tempPath%\%moveFilesListTxtFileName%" ') do move %%a %destPath%
pause

:correctFilesList
rem files whitelist
rem correctfiles can be changed with "dir /B path>>c:\temp\correctFilesList.txt" from a correct source. Or you can generate a list of correct files via command as below.
echo correctfile1.dll>> %tempPath%\%correctFilesListTxtFileName%.txt
echo correctfile2.log.xml>> %tempPath%\%correctFilesListTxtFileName%.txt
echo correctfile2.log.xml>> %tempPath%\MySoftware-correctFilesList.txt


问:
What's wrong with this code for multiplying two matrices in C?
The aim of the matrixMultiplier function is to multiply A * B, and then show the resulting matrix C, for any two square matrices A and B. A and B sizes are limited by 10*10.

When the user is asked the size of the matrix they wish to introduce, although A and B are 10*10, the function only works with the submatrices in A and B up to the dimension which the user has specified, say 3*3.

I've tested this out multiplying the 3*3 identity matrix by itself and it's not giving me the correct answer.

#include <stdio.h>

void matrixMultiplier(int A[][10], int B[][10], int C[][10], int n) {
    int i, j, k;
    for (i = 0; i < n; i++) {
        for (k = 0; k < n; k++) {
            C[i][k] = 0;               /* Initialize output matrix to zero */
        }
    }

    for (i = 0; i < n; i++) {
        for (k = 0; k < n; k++) {
            for (j = 0; j < n; j++) {
                C[i][k] += A[i][j] * B[j][k];
            }
        }
    }
    printf("\n");

    for (i = 0; i < n; i++) {
        for (k = 0; k < n; k++) {
            printf("%4d", C[i][k]);
        }
        printf("\n");
    }
}

int main(void) {
    int A[][10] = {{0}};
    int B[][10] = {{0}};
    int C[][10] = {{0}}; /* Initialize output matrix to zero */
    int i, j;
    int n;

    printf("Enter square matrix dimension: ");
    scanf("%d", &n);
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            printf("Assign a value: ");
            scanf("%d", &A[i][j]);
        }
        printf("New row.\n");
    }
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            printf("%4d", A[i][j]);
        }
        printf("\n");
    }
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            printf("Assign a value: ");
            scanf("%d", &B[i][j]);
        }
        printf("New row.\n");
    }
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            printf("%4d", B[i][j]);
        }
        printf("\n");
    }
    matrixMultiplier(A, B, C, n);
    return 0;
}
```

答:
You need to use statically allocated arrays like this:

```<code> int A[10][10] = {{0}};
 int B[10][10] = {{0}};
 int C[10][10] = {{0}};  /* Initialize output matrix to zero */
</code>```

As other commentators noticed, in C int A[][10] = {{0}}; is basically an equivalent of int A[1][10] = {{0}};, so only first rows are correctly set.

Body:
You need to use statically allocated arrays like this:

 int A[10][10] = {{0}};
 int B[10][10] = {{0}};
 int C[10][10] = {{0}};  /* Initialize output matrix to zero */

As other commentators noticed, in C int A[][10] = {{0}}; is basically an equivalent of int A[1][10] = {{0}};, so only first rows are correctly set.


问:
Excel to Google Sheets - Error: Formula parse error
I have created a simple league spreadsheet in Excel but when I try and use it in Google Sheets I am getting formula errors. This is the first time I have used Google Sheets and I would like to use it to make my league public.

An example of a invalid formula :

```<code>=IF(C3=0,"",VLOOKUP(MIN(Calculations!$A$3:$A$12),Calculations!$A$3:$N$12,3,FALSE))
</code>```

https://docs.google.com/spreadsheets/d/1gYOJcJPHstD1NPwIkKRr2lejbfidnqyFIRqXeQgVi-E/edit?usp=sharing

答:
Here's a free google-sheet formula parse and evaluate tool for untangling formulae:

https://docs.google.com/spreadsheets/d/1wwclmAMXGaFanVLlyvzv63fDx6JkwOcT6Dkisac-sXI/copy

It's free. It's tiny. It's just a simple shared google-sheet file (with no macros, add-ons or fancy stuff). Click the link to make your own copy. Have a try, and if you like it, bookmark it for future use while fighting formulae in google-sheet.

I made it to make up for the lack in google sheet of the Evaluate Formula (F9) parser native to Excel. It analyses any formula pasted into yellow cell G1, splitting and colouring them by depth or by chosen characters, and referencing them against the available formulae to see where brackets or commas are likely to have been omitted or put in the wrong place. A handy tool for simple checks, and for making or parsing complex or nested formulas, and for finding 'Parse Error', and diagnosing #REF!, #NAME?, #N/A, #NUM!, #VALUE! error codes.

Enjoy!

Body:
I have created a simple league spreadsheet in Excel but when I try and use it in Google Sheets I am getting formula errors. This is the first time I have used Google Sheets and I would like to use it to make my league public.

An example of a invalid formula :

=IF(C3=0,"",VLOOKUP(MIN(Calculations!$A$3:$A$12),Calculations!$A$3:$N$12,3,FALSE))

https://docs.google.com/spreadsheets/d/1gYOJcJPHstD1NPwIkKRr2lejbfidnqyFIRqXeQgVi-E/edit?usp=sharing


问:
Can you manually set the SSL cert_store for the Savon client gem?
Context

I'm currently trying to get my Savon client to read a peer certificate from the default system SSL cert folder. Basically, the effect I want to produce is calling set_default_paths on the Savon client's http cert store.

Essentially, I'm attempting to explicitly set the cert_store for a Savon client to OpenSSL::X509::Store.new so that I can manually call set_default_paths and force it to use the system certificates.

I've been looking through the Savon documentation and while I see that there are ways to pass in certs/keys, there's no obvious way to do this that I can find.

答:
Following works:</p>

```<code>client = Savon.client wsdl:'https://tckimlik.nvi.gov.tr/Service/KPSPublicV2.asmx?WSDL', convert_request_keys_to: :none
cert_store = OpenSSL::X509::Store.new
cert_store.set_default_paths
client.globals.ssl_cert_store cert_store
response = client.call :kisi_ve_cuzdan_dogrula, message: message
</code>```

Body:
Following works:

client = Savon.client wsdl:'https://tckimlik.nvi.gov.tr/Service/KPSPublicV2.asmx?WSDL', convert_request_keys_to: :none
cert_store = OpenSSL::X509::Store.new
cert_store.set_default_paths
client.globals.ssl_cert_store cert_store
response = client.call :kisi_ve_cuzdan_dogrula, message: message


问:
WebDriverIO: browser.pause does not working
I have used browser.sleep in protractor to hold the execution for a particular amount of time. In similar way I have tried the browser.pause in WebDriverIO. But it is not pausing for the given amount of time.

Even for browser pause I referred the WebDriverIO official documentation, there also the same thing is given

Step Definition Code:

```<code>Given(/^Verify the title of Salesforce web page$/,function(){
    browser.url('https://login.salesforce.com/');
    browser.pause(10000);
});
</code>```

I use async mode in the configuration

WebDriverIO Version: ^5.22.4

wdio.config.js

```<code>exports.config = {
    //
    // ====================
    // Runner Configuration
    // ====================
    //
    // WebdriverIO allows it to run your tests in arbitrary locations (e.g. locally or
    // on a remote machine).
    runner: 'local',
    //
    // Override default path ('/wd/hub') for chromedriver service.
    path: '/',
    //
    // ==================
    // Specify Test Files
    // ==================
    // Define which test specs should run. The pattern is relative to the directory
    // from which `wdio` was called. Notice that, if you are calling `wdio` from an
    // NPM script (see https://docs.npmjs.com/cli/run-script) then the current working
    // directory is where your package.json resides, so `wdio` will be called from there.
    //
    specs: [
        './test/features/*.feature'
    ],
    // Patterns to exclude.
    exclude: [
        // 'path/to/excluded/files'
    ],
    //
    // ============
    // Capabilities
    // ============
    // Define your capabilities here. WebdriverIO can run multiple capabilities at the same
    // time. Depending on the number of capabilities, WebdriverIO launches several test
    // sessions. Within your capabilities you can overwrite the spec and exclude options in
    // order to group specific specs to a specific capability.
    //
    // First, you can define how many instances should be started at the same time. Let's
    // say you have 3 different capabilities (Chrome, Firefox, and Safari) and you have
    // set maxInstances to 1; wdio will spawn 3 processes. Therefore, if you have 10 spec
    // files and you set maxInstances to 10, all spec files will get tested at the same time
    // and 30 processes will get spawned. The property handles how many capabilities
    // from the same test should run tests.
    //
    maxInstances: 10,
    //
    // If you have trouble getting all important capabilities together, check out the
    // Sauce Labs platform configurator - a great tool to configure your capabilities:
    // https://docs.saucelabs.com/reference/platforms-configurator
    //
    capabilities: [{

        // maxInstances can get overwritten per capability. So if you have an in-house Selenium
        // grid with only 5 firefox instances available you can make sure that not more than
        // 5 instances get started at a time.
        maxInstances: 5,
        //
        browserName: 'chrome',
        // If outputDir is provided WebdriverIO can capture driver session logs
        // it is possible to configure which logTypes to include/exclude.
        // excludeDriverLogs: ['*'], // pass '*' to exclude all driver session logs
        // excludeDriverLogs: ['bugreport', 'server'],
    }],
    //
    // ===================
    // Test Configurations
    // ===================
    // Define all options that are relevant for the WebdriverIO instance here
    //
    // Level of logging verbosity: trace | debug | info | warn | error | silent
    logLevel: 'info',
    //
    // Set specific log levels per logger
    // loggers:
    // - webdriver, webdriverio
    // - @wdio/applitools-service, @wdio/browserstack-service, @wdio/devtools-service, @wdio/sauce-service
    // - @wdio/mocha-framework, @wdio/jasmine-framework
    // - @wdio/local-runner, @wdio/lambda-runner
    // - @wdio/sumologic-reporter
    // - @wdio/cli, @wdio/config, @wdio/sync, @wdio/utils
    // Level of logging verbosity: trace | debug | info | warn | error | silent
    // logLevels: {
    //     webdriver: 'info',
    //     '@wdio/applitools-service': 'info'
    // },
    //
    // If you only want to run your tests until a specific amount of tests have failed use
    // bail (default is 0 - don't bail, run all tests).
    bail: 0,
    //
    // Set a base URL in order to shorten url command calls. If your `url` parameter starts
    // with `/`, the base url gets prepended, not including the path portion of your baseUrl.
    // If your `url` parameter starts without a scheme or `/` (like `some/path`), the base url
    // gets prepended directly.
    baseUrl: 'https://login.salesforce.com/',
    //
    // Default timeout for all waitFor* commands.
    waitforTimeout: 10000,
    //
    // Default timeout in milliseconds for request
    // if browser driver or grid doesn't send response
    connectionRetryTimeout: 90000,
    //
    // Default request retries count
    connectionRetryCount: 0,
    //
    // Test runner services
    // Services take over a specific job you don't want to take care of. They enhance
    // your test setup with almost no effort. Unlike plugins, they don't add new
    // commands. Instead, they hook themselves up into the test process.
    services: ['chromedriver','firefox-profile'],

    // Framework you want to run your specs with.
    // The following are supported: Mocha, Jasmine, and Cucumber
    // see also: https://webdriver.io/docs/frameworks.html
    //
    // Make sure you have the wdio adapter package for the specific framework installed
    // before running any tests.
    framework: 'cucumber',
    //
    // The number of times to retry the entire specfile when it fails as a whole
    // specFileRetries: 1,
    //
    // Test reporter for stdout.
    // The only one supported by default is 'dot'
    // see also: https://webdriver.io/docs/dot-reporter.html
    reporters: ['spec',['allure', {
        outputDir: 'allure-results',
        disableWebdriverStepsReporting: true,
        disableWebdriverScreenshotsReporting: false,
        useCucumberStepReporter:true
    }]],
    // If you are using Cucumber you need to specify the location of your step definitions.
    cucumberOpts: {
        require: ['./built/**/*.js'],        // <string[]> (file/dir) require files before executing features
        backtrace: false,   // <boolean> show full backtrace for errors
        requireModule: [],  // <string[]> ("extension:module") require files with the given EXTENSION after requiring MODULE (repeatable)
        dryRun: false,      // <boolean> invoke formatters without executing steps
        failFast: false,    // <boolean> abort the run on first failure
        format: ['pretty'], // <string[]> (type[:path]) specify the output format, optionally supply PATH to redirect formatter output (repeatable)
        colors: true,       // <boolean> disable colors in formatter output
        snippets: true,     // <boolean> hide step definition snippets for pending steps
        source: true,       // <boolean> hide source uris
        profile: [],        // <string[]> (name) specify the profile to use
        strict: false,      // <boolean> fail if there are any undefined or pending steps
        tagExpression: '',  // <string> (expression) only execute the features or scenarios with tags matching the expression
        timeout: 60000,     // <number> timeout for step definitions
        ignoreUndefinedDefinitions: false, // <boolean> Enable this config to treat undefined definitions as warnings.
    },

    //
    // =====
    // Hooks
    // =====
    // WebdriverIO provides several hooks you can use to interfere with the test process in order to enhance
    // it and to build services around it. You can either apply a single function or an array of
    // methods to it. If one of them returns with a promise, WebdriverIO will wait until that promise got
    // resolved to continue.
    /**
     * Gets executed once before all workers get launched.
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     */
    // onPrepare: function (config, capabilities) {
    // },
    /**
     * Gets executed just before initialising the webdriver session and test framework. It allows you
     * to manipulate configurations depending on the capability or spec.
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that are to be run
     */
    // beforeSession: function (config, capabilities, specs) {
    // },
    /**
     * Gets executed before test execution begins. At this point you can access to all global
     * variables like `browser`. It is the perfect place to define custom commands.
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that are to be run
     */
    before: function (_capabilities) {
           // =================
        // Assertion Library
        // =================
        const chai    = require('chai');
        global.expect = chai.expect;
        global.assert = chai.assert;
        global.should = chai.should();
        require('ts-node').register({ files: true });
    },
    /**
     * Runs before a WebdriverIO command gets executed.
     * @param {String} commandName hook command name
     * @param {Array} args arguments that command would receive
     */
    // beforeCommand: function (commandName, args) {
    // },
    /**
     * Runs before a Cucumber feature
     */
    beforeFeature: function (uri, feature, scenarios) {
        scenarioCounter = 0;
    },
    /**
     * Runs before a Cucumber scenario
     */
    // beforeScenario: function (uri, feature, scenario, sourceLocation) {
    // },
    /**
     * Runs before a Cucumber step
     */
    // beforeStep: function (uri, feature, stepData, context) {
    // },
    /**
     * Runs after a Cucumber step
     */
    afterStep: function (uri, feature, { error, result, duration, passed }, stepData, context) {
        if (error !== undefined) {
            browser.takeScreenshot();
        }
    },
    /**
     * Runs after a Cucumber scenario
     */
    afterScenario: function (uri, feature, scenario, result, sourceLocation) {
        scenarioCounter += 1;
        addArgument('Scenario #', scenarioCounter);
    },
    /**
     * Runs after a Cucumber feature
     */
    // afterFeature: function (uri, feature, scenarios) {
    // },

    /**
     * Runs after a WebdriverIO command gets executed
     * @param {String} commandName hook command name
     * @param {Array} args arguments that command would receive
     * @param {Number} result 0 - command success, 1 - command error
     * @param {Object} error error object if any
     */
    // afterCommand: function (commandName, args, result, error) {
    // },
    /**
     * Gets executed after all tests are done. You still have access to all global variables from
     * the test.
     * @param {Number} result 0 - test pass, 1 - test fail
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that ran
     */
    // after: function (result, capabilities, specs) {
    // },
    /**
     * Gets executed right after terminating the webdriver session.
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that ran
     */
    // afterSession: function (config, capabilities, specs) {
    // },
    /**
     * Gets executed after all workers got shut down and the process is about to exit. An error
     * thrown in the onComplete hook will result in the test run failing.
     * @param {Object} exitCode 0 - success, 1 - fail
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {<Object>} results object containing test results
     */
    // onComplete: function(exitCode, config, capabilities, results) {
    // },
    /**
    * Gets executed when a refresh happens.
    * @param {String} oldSessionId session ID of the old session
    * @param {String} newSessionId session ID of the new session
    */
    //onReload: function(oldSessionId, newSessionId) {
    //}
}
</code>```

答:
Since, it was an async mode in WebDriverIO, have to add the await in both of the lines as below.

```<code>Given(/^Verify the title of Salesforce web page$/, async function(){
    await browser.url('https://login.salesforce.com/');
    await browser.pause(10000);
});
</code>```

Body:
I have used browser.sleep in protractor to hold the execution for a particular amount of time. In similar way I have tried the browser.pause in WebDriverIO. But it is not pausing for the given amount of time.

Even for browser pause I referred the WebDriverIO official documentation, there also the same thing is given

Step Definition Code:

Given(/^Verify the title of Salesforce web page$/,function(){
    browser.url('https://login.salesforce.com/');
    browser.pause(10000);
});

I use async mode in the configuration

WebDriverIO Version: ^5.22.4

wdio.config.js

exports.config = {
    //
    // ====================
    // Runner Configuration
    // ====================
    //
    // WebdriverIO allows it to run your tests in arbitrary locations (e.g. locally or
    // on a remote machine).
    runner: 'local',
    //
    // Override default path ('/wd/hub') for chromedriver service.
    path: '/',
    //
    // ==================
    // Specify Test Files
    // ==================
    // Define which test specs should run. The pattern is relative to the directory
    // from which `wdio` was called. Notice that, if you are calling `wdio` from an
    // NPM script (see https://docs.npmjs.com/cli/run-script) then the current working
    // directory is where your package.json resides, so `wdio` will be called from there.
    //
    specs: [
        './test/features/*.feature'
    ],
    // Patterns to exclude.
    exclude: [
        // 'path/to/excluded/files'
    ],
    //
    // ============
    // Capabilities
    // ============
    // Define your capabilities here. WebdriverIO can run multiple capabilities at the same
    // time. Depending on the number of capabilities, WebdriverIO launches several test
    // sessions. Within your capabilities you can overwrite the spec and exclude options in
    // order to group specific specs to a specific capability.
    //
    // First, you can define how many instances should be started at the same time. Let's
    // say you have 3 different capabilities (Chrome, Firefox, and Safari) and you have
    // set maxInstances to 1; wdio will spawn 3 processes. Therefore, if you have 10 spec
    // files and you set maxInstances to 10, all spec files will get tested at the same time
    // and 30 processes will get spawned. The property handles how many capabilities
    // from the same test should run tests.
    //
    maxInstances: 10,
    //
    // If you have trouble getting all important capabilities together, check out the
    // Sauce Labs platform configurator - a great tool to configure your capabilities:
    // https://docs.saucelabs.com/reference/platforms-configurator
    //
    capabilities: [{

        // maxInstances can get overwritten per capability. So if you have an in-house Selenium
        // grid with only 5 firefox instances available you can make sure that not more than
        // 5 instances get started at a time.
        maxInstances: 5,
        //
        browserName: 'chrome',
        // If outputDir is provided WebdriverIO can capture driver session logs
        // it is possible to configure which logTypes to include/exclude.
        // excludeDriverLogs: ['*'], // pass '*' to exclude all driver session logs
        // excludeDriverLogs: ['bugreport', 'server'],
    }],
    //
    // ===================
    // Test Configurations
    // ===================
    // Define all options that are relevant for the WebdriverIO instance here
    //
    // Level of logging verbosity: trace | debug | info | warn | error | silent
    logLevel: 'info',
    //
    // Set specific log levels per logger
    // loggers:
    // - webdriver, webdriverio
    // - @wdio/applitools-service, @wdio/browserstack-service, @wdio/devtools-service, @wdio/sauce-service
    // - @wdio/mocha-framework, @wdio/jasmine-framework
    // - @wdio/local-runner, @wdio/lambda-runner
    // - @wdio/sumologic-reporter
    // - @wdio/cli, @wdio/config, @wdio/sync, @wdio/utils
    // Level of logging verbosity: trace | debug | info | warn | error | silent
    // logLevels: {
    //     webdriver: 'info',
    //     '@wdio/applitools-service': 'info'
    // },
    //
    // If you only want to run your tests until a specific amount of tests have failed use
    // bail (default is 0 - don't bail, run all tests).
    bail: 0,
    //
    // Set a base URL in order to shorten url command calls. If your `url` parameter starts
    // with `/`, the base url gets prepended, not including the path portion of your baseUrl.
    // If your `url` parameter starts without a scheme or `/` (like `some/path`), the base url
    // gets prepended directly.
    baseUrl: 'https://login.salesforce.com/',
    //
    // Default timeout for all waitFor* commands.
    waitforTimeout: 10000,
    //
    // Default timeout in milliseconds for request
    // if browser driver or grid doesn't send response
    connectionRetryTimeout: 90000,
    //
    // Default request retries count
    connectionRetryCount: 0,
    //
    // Test runner services
    // Services take over a specific job you don't want to take care of. They enhance
    // your test setup with almost no effort. Unlike plugins, they don't add new
    // commands. Instead, they hook themselves up into the test process.
    services: ['chromedriver','firefox-profile'],

    // Framework you want to run your specs with.
    // The following are supported: Mocha, Jasmine, and Cucumber
    // see also: https://webdriver.io/docs/frameworks.html
    //
    // Make sure you have the wdio adapter package for the specific framework installed
    // before running any tests.
    framework: 'cucumber',
    //
    // The number of times to retry the entire specfile when it fails as a whole
    // specFileRetries: 1,
    //
    // Test reporter for stdout.
    // The only one supported by default is 'dot'
    // see also: https://webdriver.io/docs/dot-reporter.html
    reporters: ['spec',['allure', {
        outputDir: 'allure-results',
        disableWebdriverStepsReporting: true,
        disableWebdriverScreenshotsReporting: false,
        useCucumberStepReporter:true
    }]],
    // If you are using Cucumber you need to specify the location of your step definitions.
    cucumberOpts: {
        require: ['./built/**/*.js'],        // <string[]> (file/dir) require files before executing features
        backtrace: false,   // <boolean> show full backtrace for errors
        requireModule: [],  // <string[]> ("extension:module") require files with the given EXTENSION after requiring MODULE (repeatable)
        dryRun: false,      // <boolean> invoke formatters without executing steps
        failFast: false,    // <boolean> abort the run on first failure
        format: ['pretty'], // <string[]> (type[:path]) specify the output format, optionally supply PATH to redirect formatter output (repeatable)
        colors: true,       // <boolean> disable colors in formatter output
        snippets: true,     // <boolean> hide step definition snippets for pending steps
        source: true,       // <boolean> hide source uris
        profile: [],        // <string[]> (name) specify the profile to use
        strict: false,      // <boolean> fail if there are any undefined or pending steps
        tagExpression: '',  // <string> (expression) only execute the features or scenarios with tags matching the expression
        timeout: 60000,     // <number> timeout for step definitions
        ignoreUndefinedDefinitions: false, // <boolean> Enable this config to treat undefined definitions as warnings.
    },

    //
    // =====
    // Hooks
    // =====
    // WebdriverIO provides several hooks you can use to interfere with the test process in order to enhance
    // it and to build services around it. You can either apply a single function or an array of
    // methods to it. If one of them returns with a promise, WebdriverIO will wait until that promise got
    // resolved to continue.
    /**
     * Gets executed once before all workers get launched.
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     */
    // onPrepare: function (config, capabilities) {
    // },
    /**
     * Gets executed just before initialising the webdriver session and test framework. It allows you
     * to manipulate configurations depending on the capability or spec.
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that are to be run
     */
    // beforeSession: function (config, capabilities, specs) {
    // },
    /**
     * Gets executed before test execution begins. At this point you can access to all global
     * variables like `browser`. It is the perfect place to define custom commands.
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that are to be run
     */
    before: function (_capabilities) {
           // =================
        // Assertion Library
        // =================
        const chai    = require('chai');
        global.expect = chai.expect;
        global.assert = chai.assert;
        global.should = chai.should();
        require('ts-node').register({ files: true });
    },
    /**
     * Runs before a WebdriverIO command gets executed.
     * @param {String} commandName hook command name
     * @param {Array} args arguments that command would receive
     */
    // beforeCommand: function (commandName, args) {
    // },
    /**
     * Runs before a Cucumber feature
     */
    beforeFeature: function (uri, feature, scenarios) {
        scenarioCounter = 0;
    },
    /**
     * Runs before a Cucumber scenario
     */
    // beforeScenario: function (uri, feature, scenario, sourceLocation) {
    // },
    /**
     * Runs before a Cucumber step
     */
    // beforeStep: function (uri, feature, stepData, context) {
    // },
    /**
     * Runs after a Cucumber step
     */
    afterStep: function (uri, feature, { error, result, duration, passed }, stepData, context) {
        if (error !== undefined) {
            browser.takeScreenshot();
        }
    },
    /**
     * Runs after a Cucumber scenario
     */
    afterScenario: function (uri, feature, scenario, result, sourceLocation) {
        scenarioCounter += 1;
        addArgument('Scenario #', scenarioCounter);
    },
    /**
     * Runs after a Cucumber feature
     */
    // afterFeature: function (uri, feature, scenarios) {
    // },

    /**
     * Runs after a WebdriverIO command gets executed
     * @param {String} commandName hook command name
     * @param {Array} args arguments that command would receive
     * @param {Number} result 0 - command success, 1 - command error
     * @param {Object} error error object if any
     */
    // afterCommand: function (commandName, args, result, error) {
    // },
    /**
     * Gets executed after all tests are done. You still have access to all global variables from
     * the test.
     * @param {Number} result 0 - test pass, 1 - test fail
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that ran
     */
    // after: function (result, capabilities, specs) {
    // },
    /**
     * Gets executed right after terminating the webdriver session.
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that ran
     */
    // afterSession: function (config, capabilities, specs) {
    // },
    /**
     * Gets executed after all workers got shut down and the process is about to exit. An error
     * thrown in the onComplete hook will result in the test run failing.
     * @param {Object} exitCode 0 - success, 1 - fail
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {<Object>} results object containing test results
     */
    // onComplete: function(exitCode, config, capabilities, results) {
    // },
    /**
    * Gets executed when a refresh happens.
    * @param {String} oldSessionId session ID of the old session
    * @param {String} newSessionId session ID of the new session
    */
    //onReload: function(oldSessionId, newSessionId) {
    //}
}

Body:
Since, it was an async mode in WebDriverIO, have to add the await in both of the lines as below.

Given(/^Verify the title of Salesforce web page$/, async function(){
    await browser.url('https://login.salesforce.com/');
    await browser.pause(10000);
});


问:
How do you convert a variable from an integer to a string in base R?
I've just started using R and I have no aptitude for coding.  I don't speak the language so I can't follow the examples I've seen (sorry!).

I have a variable called Gender which has levels 1 and 2, which I created like this:

```<code>factor(Gender, levels = c(1,2), labels = c("Male","Female"))
</code>```

It appears that the 1's and 2's for the variable are registering as "integers" but I want them to be registered as string variables (ie nominal values).

How do I tell R to change 1 and 2 to "1" and "2", please?

答: you can use as.character(...) to treat objects as character strings.

Body:
I've just started using R and I have no aptitude for coding.  I don't speak the language so I can't follow the examples I've seen (sorry!).

I have a variable called Gender which has levels 1 and 2, which I created like this:

factor(Gender, levels = c(1,2), labels = c("Male","Female"))

It appears that the 1's and 2's for the variable are registering as "integers" but I want them to be registered as string variables (ie nominal values).

How do I tell R to change 1 and 2 to "1" and "2", please?


问:
setting up local dev enviroment with htaccess
I'm setting up my local test pc (WIN10 with xampp) to dev my web projects.
What I achieved:

visiting https://example.com will show the remote production version

visiting http://local.example.com will show the local development version (http so i dont have to deal with certificate issues)

The piece I'm missing is the /public/.htaccess, that I still have to comment each time I'm testing something. The condition and rule are:

```<code>RewriteCond %{SERVER_PORT} 80

RewriteRule ^(.*)$ https://example.com/$1 [R,L]
</code>```

How do I rewrite this condition to ignore the rule if the request is made from local.example.com

Thanks

答:
You can use the below rewrite rule. </p>

```<code>RewriteEngine on
RewriteCond %{SERVER_PORT} =80 [NC]
RewriteCond %{HTTP_HOST} !^local\.example\.com
RewriteRule ^(.*)$ https://example.com/$1 [R,L]

</code>```

Body:
I'm setting up my local test pc (WIN10 with xampp) to dev my web projects.
What I achieved:

visiting https://example.com will show the remote production version

visiting http://local.example.com will show the local development version (http so i dont have to deal with certificate issues)

The piece I'm missing is the /public/.htaccess, that I still have to comment each time I'm testing something. The condition and rule are:

RewriteCond %{SERVER_PORT} 80

RewriteRule ^(.*)$ https://example.com/$1 [R,L]

How do I rewrite this condition to ignore the rule if the request is made from local.example.com

Thanks

Body:
You can use the below rewrite rule.

RewriteEngine on
RewriteCond %{SERVER_PORT} =80 [NC]
RewriteCond %{HTTP_HOST} !^local\.example\.com
RewriteRule ^(.*)$ https://example.com/$1 [R,L]


问:
How to transform wide type to long type in Stata when the data set is big
I have the following panel data set:

```<code>ID SEX    age_t1 age_t2 C1_Q1 C1_Q2 ...  C2_Q1 C2_Q2 ... C3_Q1 .... C4_Q1
1  female   17    20      1    2           3     5        2           4
</code>```

C1 is year 2014 and C4 is 2017.

The problem is that the number of questions are different by year.
I speculate that using stack by designating the number of columns might work.
For example, from column 5 to 10 becomes the first group, and column 6 to 12 becomes the second group.
But I don't know how to do it.

答:
If the number of questions differs by year, then the logic of your suggestion is hard to follow.

The Stata tag wiki gives advice on how to present data examples, which typically need to be simplified but should be as realistic as possible, rather than schematic.

This may help:

```<code>clear
input ID SEX    age_t1 age_t2 C1_Q1 C1_Q2 C2_Q1 C2_Q2 C3_Q1 C3_Q2
1  1   17    20      1    2     3     5   2     4
end

rename (C*_Q*) (Q*_C*)
unab stubs : *_C1
local stubs : subinstr local stubs "_C1" "", all
reshape long `stubs', i(ID SEX age*) j(year) string
destring year, ignore(_C) replace
replace year = year + 2013

list

     +--------------------------------------------------+
     | ID   SEX   age_t1   age_t2   year   Q1   Q2   Q3 |
     |--------------------------------------------------|
  1. |  1     1       17       20   2014    1    3    2 |
  2. |  1     1       17       20   2015    2    5    4 |
     +--------------------------------------------------+
</code>```

How to get the stubs is documented in this FAQ.

Body:
I have the following panel data set:

ID SEX    age_t1 age_t2 C1_Q1 C1_Q2 ...  C2_Q1 C2_Q2 ... C3_Q1 .... C4_Q1
1  female   17    20      1    2           3     5        2           4

C1 is year 2014 and C4 is 2017.

The problem is that the number of questions are different by year.
I speculate that using stack by designating the number of columns might work.
For example, from column 5 to 10 becomes the first group, and column 6 to 12 becomes the second group.
But I don't know how to do it.

Body:
If the number of questions differs by year, then the logic of your suggestion is hard to follow.

The Stata tag wiki gives advice on how to present data examples, which typically need to be simplified but should be as realistic as possible, rather than schematic.

This may help:

clear
input ID SEX    age_t1 age_t2 C1_Q1 C1_Q2 C2_Q1 C2_Q2 C3_Q1 C3_Q2
1  1   17    20      1    2     3     5   2     4
end

rename (C*_Q*) (Q*_C*)
unab stubs : *_C1
local stubs : subinstr local stubs "_C1" "", all
reshape long `stubs', i(ID SEX age*) j(year) string
destring year, ignore(_C) replace
replace year = year + 2013

list

     +--------------------------------------------------+
     | ID   SEX   age_t1   age_t2   year   Q1   Q2   Q3 |
     |--------------------------------------------------|
  1. |  1     1       17       20   2014    1    3    2 |
  2. |  1     1       17       20   2015    2    5    4 |
     +--------------------------------------------------+

How to get the stubs is documented in this FAQ.


问:
Getting length of
 when using Bootstrap 4 tab-content
I am a bit stuck on this. I am trying to get the length of a list using Bootstrap 4's tab-content. Since the tab is not active on page load, the length is 0. When I open the tab, it is still 0.

I added the html that gets printed as well as the ajax call to get the data.

// print applicant status
if (applicantStatus == 'true') {
  $('#aStatus').html('Applicant');

  // video module count
  var totalModCount = $("#vidList").find("li").length;
  console.log(totalModCount); // 0 Supposed to be 9
  $('#totalCount').html(totalModCount)

  // form total count
  var totalFormCount = $("#vidList").find("li").length;
  console.log(totalFormCount); // 0 Supposed to be 4
  $('#formTotalCount').html(totalFormCount);
}
else {
  $('#aStatus').html('Employee');
};

var listOfTypes = "";
$.each(parsedData, function (index, item) {

  var dateOfCompletion = moment(item.DateCompleted).format('MM/DD/YYYY');
  lastAttempt = moment(item.DateOfExam).format('MM/DD/YYYY');
  isValid = item.Valid;
  isOrientation = item.IsOrientation;
  isInservice = item.IsInservice;

  if (applicantStatus == "true") {
    if (isOrientation) {
      if (isValid) {
        if (item.IsComplete == true) {
          listOfTypes += "
";
          listOfTypes += item.TypeName + "";
          listOfTypes += "

Completed on: " + dateOfCompletion + "

";

        }
        else {
          listOfTypes += "
";
          listOfTypes += item.TypeName + "";
          listOfTypes += "

Time Duration: " + item.Duration + "

";
        }
      }
      else {
        listOfTypes += "
";
        listOfTypes += item.TypeName + "";
      }
    }
  }
});
```

<pre class="lang-html prettyprint-override"><code><div class='tab-content'>
  <div id="videoList" class="tab-pane fade">
    <ul class='list-group' id='vidList'>
      <li class="list-group-item videoItem"></li>
      <li class="list-group-item videoItem"></li>
      <li class="list-group-item videoItem"></li>
      <li class="list-group-item videoItem"></li>
      <li class="list-group-item videoItem"></li>
      <li class="list-group-item videoItem"></li>
    </ul>
  </div>
  <div id="formsList" class="tab-pane fade">
    <ul class='list-group' id='fList'>
      <li class="list-group-item formItem"></li>
      <li class="list-group-item formItem"></li>
      <li class="list-group-item formItem"></li>
      <li class="list-group-item formItem"></li>
    </ul>
  </div>
</div>
</code>```

答:
I imagine that the lists are loaded from an ajax call ? in this case the code you entered must be executed at the callback in the success of the call

```<code>$ajax({
    url : '',
    type: ...,
    success : function(response) {
    // add the <li> </li> AND THEN DO THE COUNT
    var totalModCount = $("#vidList").find("li").length;
    }

})
</code>```

Title: Getting length of <li> when using Bootstrap 4 tab-content

Body:
I imagine that the lists are loaded from an ajax call ? in this case the code you entered must be executed at the callback in the success of the call

$ajax({
    url : '',
    type: ...,
    success : function(response) {
    // add the <li> </li> AND THEN DO THE COUNT
    var totalModCount = $("#vidList").find("li").length;
    }

})


问:
How to save text of FCKEditor on database?
I am using FCKEditor on my page.

and i want to save its content on database..but on doing this error A potentially dangerous Request.Form value was detected from the client (LongDescriptionVal="
hello..
"). occur on my page..

what i am doing is here:-

aspx.cs:-

```<code>protected void btnadd_Click(object sender, EventArgs e)

{
    string _detail = Request["LongDescriptionVal"].ToString();
    string query = "insert into Description(description) values('" + _detail.Trim() + "')";
    SqlCommand cmd = new SqlCommand(query, con);
    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();
}
</code>```

and aspx:-

```<code><strong>Full Description :</strong>
                <br />
                            <!--Editor Code comes here  -->

                            <script type="text/javascript">
                                <!--
                                var oFCKeditor = new FCKeditor( 'LongDescriptionVal') ;
                                oFCKeditor.BasePath = 'fckeditor/';
                                oFCKeditor.Height   = 300;
                                oFCKeditor.Value    = '<%=FullDescription%>';
                                oFCKeditor.Create() ;
                                //-->
                            </script>
                  <br />
                  <asp:Button ID="btnadd" runat="server" Text="Add" OnClick="btnadd_Click" />
</code>```

anyone can tell me that how can i save data on database...

Thanks in advance..

答:
add validateRequest="false" into your page;

Sample;

```<code><%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" ValidateRequest="false" Inherits="MyApp.Default" %>
</code>```

Body:
I am using FCKEditor on my page.

and i want to save its content on database..but on doing this error A potentially dangerous Request.Form value was detected from the client (LongDescriptionVal="
hello..
"). occur on my page..

what i am doing is here:-

aspx.cs:-

protected void btnadd_Click(object sender, EventArgs e)

{
    string _detail = Request["LongDescriptionVal"].ToString();
    string query = "insert into Description(description) values('" + _detail.Trim() + "')";
    SqlCommand cmd = new SqlCommand(query, con);
    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();
}

and aspx:-

Full Description :

                  <asp:Button ID="btnadd" runat="server" Text="Add" OnClick="btnadd_Click" />

anyone can tell me that how can i save data on database...

Thanks in advance..

Body:
add validateRequest="false" into your page;

Sample;

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" ValidateRequest="false" Inherits="MyApp.Default" %>


问:
Top-level function for onClick in Android
Writing an Android app with Kotlin using Android Studio. I have several activities and each of them has similar buttons. I added global variable ACTID which references each Activity I have through the map.

Every button has android: onClick="onClick" in its XML file.

So, I tried to make a public function:

```<code>public fun allClick(view: View){
    val context = ACTIVITY_DICT[ACTID]
    val toast = Toast.makeText(context, ACTID.toString(), Toast.LENGTH_LONG)
    toast.show()
    when (view.id)
    {
        R.id.nextBtn ->    {
            val intentNext = Intent(context, ACTIVITY_DICT[ACTID+1]!!::class.java)
            context?.startActivity(intentNext)
            context?.finish()}
        R.id.backBtn ->    {
            val intentBack = Intent(context, ACTIVITY_DICT[ACTID-1]!!::class.java)
            context?.startActivity(intentBack)
            context?.finish()}
    }
}
</code>```

However, I cannot set allCLick for onClick. How can I fix it? Would be grateful for any possible help.

答:
You can make a base activity BaseActivity, implement allClick(view: View) method in it and inherit from it other activities:

```<code>class BaseActivity : AppCompatActivity() {

    public fun allClick(view: View) {
        val context = ACTIVITY_DICT[ACTID]
        val toast = Toast.makeText(context, ACTID.toString(), Toast.LENGTH_LONG)
        toast.show()
        when (view.id) {
            R.id.nextBtn -> {
                val intentNext = Intent(context, ACTIVITY_DICT[ACTID+1]!!::class.java)
                context?.startActivity(intentNext)
                context?.finish()
            }
            R.id.backBtn -> {
                val intentBack = Intent(context, ACTIVITY_DICT[ACTID-1]!!::class.java)
                context?.startActivity(intentBack)
                context?.finish()
            }
        }
    }
}
</code>```

Also add android: onClick="allClick" for every button in its XML file.

Body:
Writing an Android app with Kotlin using Android Studio. I have several activities and each of them has similar buttons. I added global variable ACTID which references each Activity I have through the map.

Every button has android: onClick="onClick" in its XML file.

So, I tried to make a public function:

public fun allClick(view: View){
    val context = ACTIVITY_DICT[ACTID]
    val toast = Toast.makeText(context, ACTID.toString(), Toast.LENGTH_LONG)
    toast.show()
    when (view.id)
    {
        R.id.nextBtn ->    {
            val intentNext = Intent(context, ACTIVITY_DICT[ACTID+1]!!::class.java)
            context?.startActivity(intentNext)
            context?.finish()}
        R.id.backBtn ->    {
            val intentBack = Intent(context, ACTIVITY_DICT[ACTID-1]!!::class.java)
            context?.startActivity(intentBack)
            context?.finish()}
    }
}

However, I cannot set allCLick for onClick. How can I fix it? Would be grateful for any possible help.

Body:
You can make a base activity BaseActivity, implement allClick(view: View) method in it and inherit from it other activities:

class BaseActivity : AppCompatActivity() {

    public fun allClick(view: View) {
        val context = ACTIVITY_DICT[ACTID]
        val toast = Toast.makeText(context, ACTID.toString(), Toast.LENGTH_LONG)
        toast.show()
        when (view.id) {
            R.id.nextBtn -> {
                val intentNext = Intent(context, ACTIVITY_DICT[ACTID+1]!!::class.java)
                context?.startActivity(intentNext)
                context?.finish()
            }
            R.id.backBtn -> {
                val intentBack = Intent(context, ACTIVITY_DICT[ACTID-1]!!::class.java)
                context?.startActivity(intentBack)
                context?.finish()
            }
        }
    }
}

Also add android: onClick="allClick" for every button in its XML file.


问:
Adding new column, based on values of another column pandas
Can anyone help, i'm new to Python so bear with me.

My data looks like this but has all the region information available. I'm trying to create a new column 'actual price' that works out the price based on the region. as for every entry I have each price for every region. is this possible.

```<code>data = [[1, 'EDF', 'Eastern', 400, 500, 300], [2, 'EDF', 'Southern', 200, 100, 300], [3, 'NPower',
        'Eastern', 600, 500, 700]]

df = pd.DataFrame(data, columns = ['ID', 'Supplier', 'Region', 'Av Price', 'Eastern Price',
'Southern Price'])

df
</code>```

答:
IIUC, you can do df.lookup here after adding " Price" to the values of the Region column to match the column names of the Price by region:

```<code>m = df.loc[:,df.columns.str.endswith("Price")]
df['actual_Price'] = m.lookup(df.index,df['Region'].add(" Price"))
</code>```

```<code>print(df)
   ID Supplier    Region  Av Price  Eastern Price  Southern Price  \
0   1      EDF   Eastern       400            500             300
1   2      EDF  Southern       200            100             300
2   3   NPower   Eastern       600            500             700

   actual_Price
0           500
1           300
2           500
</code>```

Body:
Can anyone help, i'm new to Python so bear with me.

My data looks like this but has all the region information available. I'm trying to create a new column 'actual price' that works out the price based on the region. as for every entry I have each price for every region. is this possible.

data = [[1, 'EDF', 'Eastern', 400, 500, 300], [2, 'EDF', 'Southern', 200, 100, 300], [3, 'NPower',
        'Eastern', 600, 500, 700]]

df = pd.DataFrame(data, columns = ['ID', 'Supplier', 'Region', 'Av Price', 'Eastern Price',
'Southern Price'])

df

Body:
IIUC, you can do df.lookup here after adding " Price" to the values of the Region column to match the column names of the Price by region:

m = df.loc[:,df.columns.str.endswith("Price")]
df['actual_Price'] = m.lookup(df.index,df['Region'].add(" Price"))

print(df)
   ID Supplier    Region  Av Price  Eastern Price  Southern Price  \
0   1      EDF   Eastern       400            500             300
1   2      EDF  Southern       200            100             300
2   3   NPower   Eastern       600            500             700

   actual_Price
0           500
1           300
2           500


答: in aspx page, set the property ValidateRequest="False", but don't forget to encode input before saving in database.

Title: How to save text of FCKEditor on database?


问:
Fast check of first inequality
I am looking for a function similar to match, but it should have an inequality as test and stop at the first occurrence.

```<code>a <- c(1,3,5,7,9,12)
b <- 6
# the output should be 4
# i tried this one:  match(min(a [b <= a ]),a ), but with much data it is slow
</code>```

答:
1) if you have large vectors, where the stop should happen in the beginning, like:

```<code>a <- c(1,3,5,7,9,12, 100:1e6)
b <- 6
</code>```

other approaches could be faster.

2) as we are benchmarking such a fast functions also compilation could make a difference, so I defined the approaches separately:

```<code>v1 <- function() match(min(a[b <= a ]), a)
v2 <- function() min(which(a >= b))
v3 <- function() which(b <= a)[1]
v4 <- function() match(TRUE, b <= a)
v5 <- function() Position(function(x) b <= x, a)

microbenchmark::microbenchmark(
 v1(), v2(), v3(), v4(), v5()
)
# Unit: microseconds
# expr     min       lq      mean   median       uq      max neval cld
# v1() 10109.4 13822.10 23205.556 23481.95 26661.30 152809.4   100   c
# v2()  5796.8  6475.75 10404.439  6839.30 16991.90  34333.7   100  b
# v3()  5144.8  5648.75  9381.664  5963.05  6801.25 142202.0   100  b
# v4()  3963.0  4497.35  6938.296  4799.55  5419.80  22011.4   100  b
# v5()     4.3    14.20    35.509    16.85    18.45   1858.8   100 a
</code>```

For original data, the last approach isn't the fastest:

```<code>a <- c(1,3,5,7,9,12)
b <- 6
microbenchmark::microbenchmark(
  v1(), v2(), v3(), v4(), v5()
)
# Unit: nanoseconds
# expr  min   lq mean median   uq   max neval cld
# v1()  800  900 1151   1000 1100 12600   100  b
# v2()  900 1000 1105   1000 1100  5600   100  b
# v3()  800  900  953    900 1000  2700   100  b
# v4()  400  500  584    600  600  1500   100 a
# v5() 3600 3700 3983   3800 3900 10600   100   c
</code>```

Additional comments on this can been seen, here:
Find position of first value greater than X in a vector

Title: Fast check of first inequality

Body:
I am looking for a function similar to match, but it should have an inequality as test and stop at the first occurrence.

a <- c(1,3,5,7,9,12)
b <- 6
# the output should be 4
# i tried this one:  match(min(a [b <= a ]),a ), but with much data it is slow

Body:
1) if you have large vectors, where the stop should happen in the beginning, like:

a <- c(1,3,5,7,9,12, 100:1e6)
b <- 6

other approaches could be faster.

2) as we are benchmarking such a fast functions also compilation could make a difference, so I defined the approaches separately:

v1 <- function() match(min(a[b <= a ]), a)
v2 <- function() min(which(a >= b))
v3 <- function() which(b <= a)[1]
v4 <- function() match(TRUE, b <= a)
v5 <- function() Position(function(x) b <= x, a)

microbenchmark::microbenchmark(
 v1(), v2(), v3(), v4(), v5()
)
# Unit: microseconds
# expr     min       lq      mean   median       uq      max neval cld
# v1() 10109.4 13822.10 23205.556 23481.95 26661.30 152809.4   100   c
# v2()  5796.8  6475.75 10404.439  6839.30 16991.90  34333.7   100  b
# v3()  5144.8  5648.75  9381.664  5963.05  6801.25 142202.0   100  b
# v4()  3963.0  4497.35  6938.296  4799.55  5419.80  22011.4   100  b
# v5()     4.3    14.20    35.509    16.85    18.45   1858.8   100 a

For original data, the last approach isn't the fastest:

a <- c(1,3,5,7,9,12)
b <- 6
microbenchmark::microbenchmark(
  v1(), v2(), v3(), v4(), v5()
)
# Unit: nanoseconds
# expr  min   lq mean median   uq   max neval cld
# v1()  800  900 1151   1000 1100 12600   100  b
# v2()  900 1000 1105   1000 1100  5600   100  b
# v3()  800  900  953    900 1000  2700   100  b
# v4()  400  500  584    600  600  1500   100 a
# v5() 3600 3700 3983   3800 3900 10600   100   c

Additional comments on this can been seen, here:
Find position of first value greater than X in a vector