问:
Check uncheck all CheckBoxes on the basis of another CheckBox
I want to select and unselect all checkboxes when user clicks on the first checkbox (All). And if user unchecks any checkbox, then only that checkbox and the first checkbox (All) should be unchecked and no change to the remaining checkboxes.

I have a Checkboxlist in my page which I'm populating dynamically.

```<code><asp:CheckBoxList runat="server" ID="cbExtList" />
</code>```

Code Behind

```<code>private Extensions _extension = new Extensions();
private ExtCollection _extCollection = new ExtCollection();

_extCollection = _extension.GetAll();

Dictionary<int, string> dExtensions = new Dictionary<int, string>();

dExtensions.Add(0, "All");
foreach (Extensions ext in _extCollection)
{
    dExtensions.Add(ext.ID, ext.Extension);
}

this.cbExtList.DataSource = dExtensions;
this.cbExtList.DataTextField = "Value";
this.cbExtList.DataValueField = "Key";
this.cbExtList.DataBind();
</code>```

Now everything is working fine. I just want to select all Extensions when I click on the first checkbox "All" in this Checkboxlist.

This is what I tried with code behind approach.

With the OnSelectedIndexChanged and setting the AutoPostBack = True

```<code><asp:CheckBoxList runat="server" ID="cbExtList" OnSelectedIndexChanged="cbExtList_OnSelectedIndexChanged" AutoPostBack="True" />

protected void cbExtList_OnSelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        if (Convert.ToInt32(this.cbExtList.SelectedItem.Value) == 0)
        {
            foreach (ListItem li in cbExtList.Items)
            {
                li.Selected = true;
            }
        }
        else
        {
            foreach (ListItem li in cbExtList.Items)
            {
                li.Selected = false;
            }
        }
    }
    catch (Exception ex)
    {
        Monitoring.WriteException(ex);
    }
}
</code>```

答:
If you need to check all checkboxes on checking of an "all" checkbox and uncheck them all upon unchecking of it, but also needed to disable each checkbox (aside from the "all") checkbox when the "all" checkbox was checked, this code should work for you. It has the added benefit of not requiring JavaScript/jQuery, too.

Here's the .aspx code (for this scenario I have nine facilities that can be selected in any combination):

```<code><asp:Label ID="lblFacility" AssociatedControlID="chkFacility" runat="server" Text="Facility: "></asp:Label>
<asp:CheckBoxList ID="chkFacility" runat="server" OnSelectedIndexChanged="chkFacility_SelectedIndexChanged">
    <asp:ListItem Value="All" Text="All"></asp:ListItem>
    <asp:ListItem Value="Location1" Text="Location 1"></asp:ListItem>
    <asp:ListItem Value="Location2" Text="Location 2"></asp:ListItem>
    <asp:ListItem Value="Location3" Text="Location 3"></asp:ListItem>
    <asp:ListItem Value="Location4" Text="Location 4"></asp:ListItem>
    <asp:ListItem Value="Location5" Text="Location 5"></asp:ListItem>
    <asp:ListItem Value="Location6" Text="Location 6"></asp:ListItem>
    <asp:ListItem Value="Location7" Text="Location 7"></asp:ListItem>
    <asp:ListItem Value="Location8" Text="Location 8"></asp:ListItem>
    <asp:ListItem Value="Location9" Text="Location 9"></asp:ListItem>
</asp:CheckBoxList>
</code>```

And the Code Behind:

```<code>protected void chkFacility_SelectedIndexChanged(object sender, EventArgs e) {
    //disables all the checkboxes when "All" is selected
    if (chkFacility.SelectedIndex==0) {
        foreach(ListItem aListItem in chkFacility.Items) {
            aListItem.Selected = true;
            if (aListItem.Value != "All") {
                aListItem.Enabled = false;
            }
        }
    } else if (chkFacility.SelectedIndex > 0) {
        var i = 0;
        foreach(ListItem aListItem in chkFacility.Items) {
            if (aListItem.Selected) {
                i++;
            }
        }
        //with the i++ check above, this handles unchecking every checkbox when each location is selected and the "All" checkbox is unchecked
        if (i == 9) {
            foreach(ListItem aListItem in chkFacility.Items) {
                aListItem.Selected = false;
                aListItem.Enabled = true;
            }
        //disables the "All" checkbox in all other cases where 8 or fewer of the 9 locations are selected
        } else {
            foreach(ListItem aListItem in chkFacility.Items) {
                if (aListItem.Value == "All") {
                    aListItem.Enabled = false;
                }
            }
        }
    //if no locations are selected after PostBack, make sure all checkboxes are enabled
    } else if (chkFacility.SelectedIndex == -1) {
        foreach(ListItem aListItem in chkFacility.Items) {
            aListItem.Enabled = true;
        }
    }
}
</code>```

One caveat to this implementation, though, is that the code for whether all locations are selected will also clear out the selection if they're all currently selected by manually checking each one. When I was writing the code for work, this edge case was an acceptable risk considering it was unlikely and considering that if all locations need to be selected, the user should be checking the "All" checkbox instead, anyway.

Body:
I want to select and unselect all checkboxes when user clicks on the first checkbox (All). And if user unchecks any checkbox, then only that checkbox and the first checkbox (All) should be unchecked and no change to the remaining checkboxes.

I have a Checkboxlist in my page which I'm populating dynamically.

<asp:CheckBoxList runat="server" ID="cbExtList" />

Code Behind

private Extensions _extension = new Extensions();
private ExtCollection _extCollection = new ExtCollection();

_extCollection = _extension.GetAll();

Dictionary<int, string> dExtensions = new Dictionary<int, string>();

dExtensions.Add(0, "All");
foreach (Extensions ext in _extCollection)
{
    dExtensions.Add(ext.ID, ext.Extension);
}

this.cbExtList.DataSource = dExtensions;
this.cbExtList.DataTextField = "Value";
this.cbExtList.DataValueField = "Key";
this.cbExtList.DataBind();

Now everything is working fine. I just want to select all Extensions when I click on the first checkbox "All" in this Checkboxlist.

This is what I tried with code behind approach.

With the OnSelectedIndexChanged and setting the AutoPostBack = True

<asp:CheckBoxList runat="server" ID="cbExtList" OnSelectedIndexChanged="cbExtList_OnSelectedIndexChanged" AutoPostBack="True" />

protected void cbExtList_OnSelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        if (Convert.ToInt32(this.cbExtList.SelectedItem.Value) == 0)
        {
            foreach (ListItem li in cbExtList.Items)
            {
                li.Selected = true;
            }
        }
        else
        {
            foreach (ListItem li in cbExtList.Items)
            {
                li.Selected = false;
            }
        }
    }
    catch (Exception ex)
    {
        Monitoring.WriteException(ex);
    }
}

Body:
If you need to check all checkboxes on checking of an "all" checkbox and uncheck them all upon unchecking of it, but also needed to disable each checkbox (aside from the "all") checkbox when the "all" checkbox was checked, this code should work for you. It has the added benefit of not requiring JavaScript/jQuery, too.

Here's the .aspx code (for this scenario I have nine facilities that can be selected in any combination):

<asp:Label ID="lblFacility" AssociatedControlID="chkFacility" runat="server" Text="Facility: "></asp:Label>
<asp:CheckBoxList ID="chkFacility" runat="server" OnSelectedIndexChanged="chkFacility_SelectedIndexChanged">
    <asp:ListItem Value="All" Text="All"></asp:ListItem>
    <asp:ListItem Value="Location1" Text="Location 1"></asp:ListItem>
    <asp:ListItem Value="Location2" Text="Location 2"></asp:ListItem>
    <asp:ListItem Value="Location3" Text="Location 3"></asp:ListItem>
    <asp:ListItem Value="Location4" Text="Location 4"></asp:ListItem>
    <asp:ListItem Value="Location5" Text="Location 5"></asp:ListItem>
    <asp:ListItem Value="Location6" Text="Location 6"></asp:ListItem>
    <asp:ListItem Value="Location7" Text="Location 7"></asp:ListItem>
    <asp:ListItem Value="Location8" Text="Location 8"></asp:ListItem>
    <asp:ListItem Value="Location9" Text="Location 9"></asp:ListItem>
</asp:CheckBoxList>

And the Code Behind:

protected void chkFacility_SelectedIndexChanged(object sender, EventArgs e) {
    //disables all the checkboxes when "All" is selected
    if (chkFacility.SelectedIndex==0) {
        foreach(ListItem aListItem in chkFacility.Items) {
            aListItem.Selected = true;
            if (aListItem.Value != "All") {
                aListItem.Enabled = false;
            }
        }
    } else if (chkFacility.SelectedIndex > 0) {
        var i = 0;
        foreach(ListItem aListItem in chkFacility.Items) {
            if (aListItem.Selected) {
                i++;
            }
        }
        //with the i++ check above, this handles unchecking every checkbox when each location is selected and the "All" checkbox is unchecked
        if (i == 9) {
            foreach(ListItem aListItem in chkFacility.Items) {
                aListItem.Selected = false;
                aListItem.Enabled = true;
            }
        //disables the "All" checkbox in all other cases where 8 or fewer of the 9 locations are selected
        } else {
            foreach(ListItem aListItem in chkFacility.Items) {
                if (aListItem.Value == "All") {
                    aListItem.Enabled = false;
                }
            }
        }
    //if no locations are selected after PostBack, make sure all checkboxes are enabled
    } else if (chkFacility.SelectedIndex == -1) {
        foreach(ListItem aListItem in chkFacility.Items) {
            aListItem.Enabled = true;
        }
    }
}

One caveat to this implementation, though, is that the code for whether all locations are selected will also clear out the selection if they're all currently selected by manually checking each one. When I was writing the code for work, this edge case was an acceptable risk considering it was unlikely and considering that if all locations need to be selected, the user should be checking the "All" checkbox instead, anyway.


来源: stackexchange

问:
How to call a function that has a function pointer as an argument in C?
I'm writing a program that finds solutions to an equation using Newton's method. I need to use function pointers so that the equation can be quickly replaced if needed.

Function pointers work as long as I just need the value returned by the function, but not when I try to call a function that has function pointers as arguments inside another function.

```<code>#define _CRT_SECURE_NO_WARNINGS
#define M_PI 3.14159265358979323846
#define N 2
#include <stdio.h>
#include <math.h>

struct data{
    double theta;
    double gamma;
    double M;
    double epsilon;
    double dx;
};

double funct(double, data);
double derivative(double, data, double(*f)(double, data));
double MST(double, data, double(*f)(double, data));

void main(){
    double results[N];
    data parameters;
    parameters.gamma = 1.4, parameters.epsilon = 0.001;
    printf("Podaj parametry:\nTheta = ");
    scanf("%lf", &parameters.theta);
    printf("M = ");
    scanf("%lf", &parameters.M);

    int index = 0;
    for (int x = 0; x < M_PI / 2.; x++){
        if (funct(x, parameters)*funct(x + 1, parameters) < 0){
            results[index] = MST(x, parameters, (*funct)(x, parameters));
            index++;
        }
    }
}

double funct(double sigma, data parameters){
    return 2. / ((parameters.gamma + 1)*parameters.M*parameters.M*sin(sigma)*sin(sigma)) - tan(sigma - parameters.theta) / tan(sigma) + (parameters.gamma - 1) / (parameters.gamma + 1);
}

double derivative(double x, data parameters, double (*f)(double x, data parameters)){
    double dx = 0.0001;
    return (f(x + dx, parameters) - f(x, parameters)) / dx;
}

double MST(double sigma_0, data parameters, double(*funct)(double sigma, data parameters)){
    double sigma_1 = sigma_0 - funct(sigma_0, parameters) / derivative(sigma_0, parameters, (*funct)(sigma_0, parameters));
    while (fabs(sigma_1 - sigma_0) < parameters.epsilon){
        sigma_0 = sigma_1;
        sigma_1 = sigma_0 - funct(sigma_0, parameters) / derivative(sigma_0, parameters, (*funct)(sigma_0, parameters));
    }
    return sigma_1;
}
</code>```

I get errors in lines 31, 47, 50 on (*funct).

Error: argument of type "double" in incompatible with parameter of type "double (*)(double x, data parameters)".

答:
Here you have an example:</p>

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

int function1(int x)
{
    return x + x;
}

int function2(int x)
{
    return x * x;
}

int function3(int x)
{
    int result = 1;
    for(int i = 1; i <= x; i++)
        result *= i;
    return result;
}

int ffunction(int (*f)(int), int arg)
{
    return f(arg);
}

int main()
{
    printf("Function1 call %d\n", ffunction(function1, 5));
    printf("Function2 call %d\n", ffunction(function2, 5));
    printf("Function3 call %d\n", ffunction(function3, 5));

    return 0;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm writing a program that finds solutions to an equation using Newton's method. I need to use function pointers so that the equation can be quickly replaced if needed.

Function pointers work as long as I just need the value returned by the function, but not when I try to call a function that has function pointers as arguments inside another function.

#define _CRT_SECURE_NO_WARNINGS
#define M_PI 3.14159265358979323846
#define N 2
#include <stdio.h>
#include <math.h>

struct data{
    double theta;
    double gamma;
    double M;
    double epsilon;
    double dx;
};

double funct(double, data);
double derivative(double, data, double(*f)(double, data));
double MST(double, data, double(*f)(double, data));

void main(){
    double results[N];
    data parameters;
    parameters.gamma = 1.4, parameters.epsilon = 0.001;
    printf("Podaj parametry:\nTheta = ");
    scanf("%lf", &parameters.theta);
    printf("M = ");
    scanf("%lf", &parameters.M);

    int index = 0;
    for (int x = 0; x < M_PI / 2.; x++){
        if (funct(x, parameters)*funct(x + 1, parameters) < 0){
            results[index] = MST(x, parameters, (*funct)(x, parameters));
            index++;
        }
    }
}

double funct(double sigma, data parameters){
    return 2. / ((parameters.gamma + 1)*parameters.M*parameters.M*sin(sigma)*sin(sigma)) - tan(sigma - parameters.theta) / tan(sigma) + (parameters.gamma - 1) / (parameters.gamma + 1);
}

double derivative(double x, data parameters, double (*f)(double x, data parameters)){
    double dx = 0.0001;
    return (f(x + dx, parameters) - f(x, parameters)) / dx;
}

double MST(double sigma_0, data parameters, double(*funct)(double sigma, data parameters)){
    double sigma_1 = sigma_0 - funct(sigma_0, parameters) / derivative(sigma_0, parameters, (*funct)(sigma_0, parameters));
    while (fabs(sigma_1 - sigma_0) < parameters.epsilon){
        sigma_0 = sigma_1;
        sigma_1 = sigma_0 - funct(sigma_0, parameters) / derivative(sigma_0, parameters, (*funct)(sigma_0, parameters));
    }
    return sigma_1;
}

I get errors in lines 31, 47, 50 on (*funct).

Error: argument of type "double" in incompatible with parameter of type "double (*)(double x, data parameters)".

Body:
Here you have an example:

#include <stdio.h>

int function1(int x)
{
    return x + x;
}

int function2(int x)
{
    return x * x;
}

int function3(int x)
{
    int result = 1;
    for(int i = 1; i <= x; i++)
        result *= i;
    return result;
}

int ffunction(int (*f)(int), int arg)
{
    return f(arg);
}

int main()
{
    printf("Function1 call %d\n", ffunction(function1, 5));
    printf("Function2 call %d\n", ffunction(function2, 5));
    printf("Function3 call %d\n", ffunction(function3, 5));

    return 0;
}


问:
Draggable widget does not change its position
I'm trying to achieve the following logic:

User clicks on area;

A new widget is generated at the specified coordinates;

User can drag a new widget to a new position.

Steps 1 and 2 work well, but in step 3, the user can drag the widget, but it does not change his position

That's how it works now:
https://media.giphy.com/media/h4Hhm5vchkcJi3IFqH/giphy.gif

Code:

```<code>class WidgetPaint extends StatefulWidget {
  WidgetPaint({this.imagefromcam});
  File imagefromcam;

  @override
  _WidgetPaintState createState() => _WidgetPaintState();
}

class _WidgetPaintState extends State<WidgetPaint> {
  GlobalKey _globalKey2 = new GlobalKey();
  Offset locationPoints;
  var commentWidgets = List<Widget>();
  var btn;

  @override
  void initState() {
    super.initState();
    locationPoints = Offset(100.0, 100.0);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 800.0,
      height: 500.0,
      child: RepaintBoundary(
          key: _globalKey2,
          child: Stack(
              children: <Widget>[

                    GestureDetector(
                      onTapUp: (TapUpDetails detail) {
                        setState(() {
                          RenderBox _object = context.findRenderObject();
                          locationPoints =
                              _object.globalToLocal(detail.globalPosition);

                          print("locpoints: $locationPoints");

                          addButton();
                        });
                      },
                  ] +
                  commentWidgets)),
    );
  }

  Widget dragButton() {
    return RawMaterialButton(
      onPressed: () {},
      child: new Icon(
        Icons.pause,
        color: Colors.blue,
        size: 15.0,
      ),
      shape: new CircleBorder(),
      fillColor: Colors.white,
    );
  }

  void addButton() {
    btn = new Positioned(
        left: locationPoints.dx,
        top: locationPoints.dy,
        child: Draggable(
          child: dragButton(),
          feedback: dragButton(),
          onDraggableCanceled: (Velocity velocity, Offset offset) {
            setState(() {
              print("Location points: $locationPoints");
              locationPoints = offset;
            });
          },
        ));

    setState(() {
      commentWidgets.add(btn);
    });
  }
</code>```

How to change position of draggable widget?

Update
If I remove GestureDetector and put a draggable widget directly to stack, everything is ok, but in that case I can't add a new widgets dynamicaly

```<code>Widget build(BuildContext context) {
    return Container(
      width: 800.0,
      height: 500.0,
      child: RepaintBoundary(
          key: _globalKey2,
          child: Stack(
              children: <Widget>[
                    Positioned(
                      left: 100.0,
                      height: 50.0,
                      child: Text(locationPoints.dx.toString()),
                    ),
                    Positioned(
                      left: 100.0,
                      top: 20.0,
                      child: Text(locationPoints.dy.toString()),
                    ),
                    Positioned(
                        left: locationPoints.dx,
                        top: locationPoints.dy,
                        child: Draggable(
                          child: dragButton(),
                          feedback: dragButton(),
                          onDraggableCanceled:
                              (Velocity velocity, Offset offset) {
                            setState(() {
                              print("Location points: $locationPoints");
                              RenderBox _object = context.findRenderObject();
                              locationPoints = _object.globalToLocal(offset);
                            });
                          },
                        )),]
</code>```

答: As you already mentioned it by yourself in your update: GestureRecognizer consumes the user input (the dragging for instance). For cases like this where you just want to register the user input you can use the Listener widget. It has the same callbacks as the GestureRecognizer but won't consume it.

Body:
I'm trying to achieve the following logic:

User clicks on area;

A new widget is generated at the specified coordinates;

User can drag a new widget to a new position.

Steps 1 and 2 work well, but in step 3, the user can drag the widget, but it does not change his position

That's how it works now:
https://media.giphy.com/media/h4Hhm5vchkcJi3IFqH/giphy.gif

Code:

class WidgetPaint extends StatefulWidget {
  WidgetPaint({this.imagefromcam});
  File imagefromcam;

  @override
  _WidgetPaintState createState() => _WidgetPaintState();
}

class _WidgetPaintState extends State<WidgetPaint> {
  GlobalKey _globalKey2 = new GlobalKey();
  Offset locationPoints;
  var commentWidgets = List<Widget>();
  var btn;

  @override
  void initState() {
    super.initState();
    locationPoints = Offset(100.0, 100.0);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 800.0,
      height: 500.0,
      child: RepaintBoundary(
          key: _globalKey2,
          child: Stack(
              children: <Widget>[

                    GestureDetector(
                      onTapUp: (TapUpDetails detail) {
                        setState(() {
                          RenderBox _object = context.findRenderObject();
                          locationPoints =
                              _object.globalToLocal(detail.globalPosition);

                          print("locpoints: $locationPoints");

                          addButton();
                        });
                      },
                  ] +
                  commentWidgets)),
    );
  }

  Widget dragButton() {
    return RawMaterialButton(
      onPressed: () {},
      child: new Icon(
        Icons.pause,
        color: Colors.blue,
        size: 15.0,
      ),
      shape: new CircleBorder(),
      fillColor: Colors.white,
    );
  }

  void addButton() {
    btn = new Positioned(
        left: locationPoints.dx,
        top: locationPoints.dy,
        child: Draggable(
          child: dragButton(),
          feedback: dragButton(),
          onDraggableCanceled: (Velocity velocity, Offset offset) {
            setState(() {
              print("Location points: $locationPoints");
              locationPoints = offset;
            });
          },
        ));

    setState(() {
      commentWidgets.add(btn);
    });
  }

How to change position of draggable widget?

Update
If I remove GestureDetector and put a draggable widget directly to stack, everything is ok, but in that case I can't add a new widgets dynamicaly

Widget build(BuildContext context) {
    return Container(
      width: 800.0,
      height: 500.0,
      child: RepaintBoundary(
          key: _globalKey2,
          child: Stack(
              children: <Widget>[
                    Positioned(
                      left: 100.0,
                      height: 50.0,
                      child: Text(locationPoints.dx.toString()),
                    ),
                    Positioned(
                      left: 100.0,
                      top: 20.0,
                      child: Text(locationPoints.dy.toString()),
                    ),
                    Positioned(
                        left: locationPoints.dx,
                        top: locationPoints.dy,
                        child: Draggable(
                          child: dragButton(),
                          feedback: dragButton(),
                          onDraggableCanceled:
                              (Velocity velocity, Offset offset) {
                            setState(() {
                              print("Location points: $locationPoints");
                              RenderBox _object = context.findRenderObject();
                              locationPoints = _object.globalToLocal(offset);
                            });
                          },
                        )),]


问:
Simple CSS Positioning Question
Basically I'm trying to create a small div (header class) that sits on top of a main banner image div (banner class). I've been able to position it correctly when my browser window is maximized, but when I resize the browser the header div maintains the margins and shrinks down to much less than the banner's width. I realize this is because I have the margins set at fixed positions on the left and right so they're maintaining those positions... I'm just new to CSS and am not sure exactly what to do to prevent this from happening. I've been messing around with positioning for about an hour and just can't get it right.

CSS:

```<code><style type = "text/css">

body {
    background-color: #595959;
}

.header {
   background-color: #4CBB17;
    padding: 12px 0px 12px 0px;
    margin: 0px 137px 0px; 137px;
}

.banner {
    text-align: center;
}

</style>
</code>```

HTML:

```<code><html>
<head>
    <title>Thanks!</title>
    <link type="text/css" rel="stylesheet" href="style.css" />
</head>

<body>

    <div class="header">
    </div>

    <div class="banner">
        <img src="banner.jpg" />
    </div>

</body>
</html>
</code>```

Any help would be much appreciated!

答: Maybe you can add a min-width: property to the header?

ContentLicense: CC BY-SA 3.0

Title: Simple CSS Positioning Question

Body:
Basically I'm trying to create a small div (header class) that sits on top of a main banner image div (banner class). I've been able to position it correctly when my browser window is maximized, but when I resize the browser the header div maintains the margins and shrinks down to much less than the banner's width. I realize this is because I have the margins set at fixed positions on the left and right so they're maintaining those positions... I'm just new to CSS and am not sure exactly what to do to prevent this from happening. I've been messing around with positioning for about an hour and just can't get it right.

CSS:

HTML:

    <title>Thanks!</title>
    <link type="text/css" rel="stylesheet" href="style.css" />

Any help would be much appreciated!


问:
Borders when row has data but no border if empty
I have a sheet that I want to dynamically add borders to filter results.  I have it working where it adds the borders, but when i select another filter it keeps the rows with previous data borders.  So if data set is smaller it has all empty borders under it.  How would I fix this with this script?</p>

```<code>function onEdit(ss) {
  var classeur = SpreadsheetApp.getActiveSpreadsheet();
  var ss = classeur.getActiveSheet();
  var range = ss.getRange("A5:a"); // Modified
  range.setBorder(false, false, false, false, false, false);
  var values = range.getValues();
  var offsetRow = range.getRowIndex(); // Added
  for (var i = 0; i < values.length; i++) {
    if (values[i][0]) { // Modified
      ss.getRange("A" + (i + offsetRow) + ":P" + (i + offsetRow))
      .setBorder(true, true, true, true, true, true, "black",
       SpreadsheetApp.BorderStyle.SOLID_MEDIUM) // Modified
      .setBackground('#FFFFFF');
    }
  }
}
</code>```

答:
Try this:

```<code>function onEdit(e) {
  var sh=e.range.getSheet();
  sh.getRange(1,1,sh.getMaxRows(),sh.getMaxColumns()).setBorder(false, false, false, false, false, false);
  var range = sh.getRange(5,1,sh.getLastRow()-4,1); // Modified
  range.setBorder(false, false, false, false, false, false);
  var values = range.getValues();
  for (var i=0;i<values.length;i++) {
    if (values[i][0]) { // Modified
       sh.getRange(i+5,1,1,16).setBorder(true, true, true, true, true, true, "black",SpreadsheetApp.BorderStyle.SOLID_MEDIUM).setBackground('#FFFFFF');
    }
  }
}
</code>```

You cannot call this function from the script editor unless you supply the event object.

Body:
I have a sheet that I want to dynamically add borders to filter results.  I have it working where it adds the borders, but when i select another filter it keeps the rows with previous data borders.  So if data set is smaller it has all empty borders under it.  How would I fix this with this script?

function onEdit(ss) {
  var classeur = SpreadsheetApp.getActiveSpreadsheet();
  var ss = classeur.getActiveSheet();
  var range = ss.getRange("A5:a"); // Modified
  range.setBorder(false, false, false, false, false, false);
  var values = range.getValues();
  var offsetRow = range.getRowIndex(); // Added
  for (var i = 0; i < values.length; i++) {
    if (values[i][0]) { // Modified
      ss.getRange("A" + (i + offsetRow) + ":P" + (i + offsetRow))
      .setBorder(true, true, true, true, true, true, "black",
       SpreadsheetApp.BorderStyle.SOLID_MEDIUM) // Modified
      .setBackground('#FFFFFF');
    }
  }
}

Body:
Try this:

function onEdit(e) {
  var sh=e.range.getSheet();
  sh.getRange(1,1,sh.getMaxRows(),sh.getMaxColumns()).setBorder(false, false, false, false, false, false);
  var range = sh.getRange(5,1,sh.getLastRow()-4,1); // Modified
  range.setBorder(false, false, false, false, false, false);
  var values = range.getValues();
  for (var i=0;i<values.length;i++) {
    if (values[i][0]) { // Modified
       sh.getRange(i+5,1,1,16).setBorder(true, true, true, true, true, true, "black",SpreadsheetApp.BorderStyle.SOLID_MEDIUM).setBackground('#FFFFFF');
    }
  }
}

You cannot call this function from the script editor unless you supply the event object.


问:
Screenshot : RasterFormatException (y+ height) is outside Raster
Using Selenium Webdriver to take screenshot for specific UI Element as suggested by other post, I am using getSubimage method to capture the screenelement. But, receiving failure exception.

I am unsure about the difference in uielement's getLocation().getX() and getSize().getWidth().getX(). If someone can clarify this, as inside the WritableRaster method's condition it always checks for y+height

```<code>File imgSrc=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        Point point = uiElem.getLocation();
         Point bottomright = new Point(uiElem.getSize().getWidth(),
                 uiElem.getSize().getHeight());
          int xcord = point.getX();
          int ycord = point.getY();

          BufferedImage img;
        try {
            img = ImageIO.read(imgSrc);
             BufferedImage dest = img.getSubimage(xcord, ycord, bottomright.getX(), bottomright.getY());
              ImageIO.write(dest, "png", imgSrc);
              FileUtils.copyFile(imgSrc, new File(".\\Screenshots\\123.png"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
</code>```

While debugging, I noticed that the img (width 1366 and height = 613). and getSubImage() has (194,1335,960,15). It will always fail for condition (y+ height) >(this.minY + this.height ) inside createWritableChildMethod. So,can anyone point,where it's going wrong, also it doesn't make sense , as why we adding (y+height)of sub-image is greater?

答:
Found a workaround, just notices it's better to use getScreenshotAs() directly on UIElement without doing alot of manipulation on the element.</p>

```<code>public void takeSmallScreenshot(WebDriver driver, WebElement uiElem)
{
         File uiElementSrc = uiElem.getScreenshotAs(OutputType.FILE);
         try {
            FileUtils.copyFile(uiElementSrc, new File(".\\Screenshots\\"+uiElem.getText().substring(0,5)+".png"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}
</code>```

Body:
Using Selenium Webdriver to take screenshot for specific UI Element as suggested by other post, I am using getSubimage method to capture the screenelement. But, receiving failure exception.

I am unsure about the difference in uielement's getLocation().getX() and getSize().getWidth().getX(). If someone can clarify this, as inside the WritableRaster method's condition it always checks for y+height

File imgSrc=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        Point point = uiElem.getLocation();
         Point bottomright = new Point(uiElem.getSize().getWidth(),
                 uiElem.getSize().getHeight());
          int xcord = point.getX();
          int ycord = point.getY();

          BufferedImage img;
        try {
            img = ImageIO.read(imgSrc);
             BufferedImage dest = img.getSubimage(xcord, ycord, bottomright.getX(), bottomright.getY());
              ImageIO.write(dest, "png", imgSrc);
              FileUtils.copyFile(imgSrc, new File(".\\Screenshots\\123.png"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

While debugging, I noticed that the img (width 1366 and height = 613). and getSubImage() has (194,1335,960,15). It will always fail for condition (y+ height) >(this.minY + this.height ) inside createWritableChildMethod. So,can anyone point,where it's going wrong, also it doesn't make sense , as why we adding (y+height)of sub-image is greater?

Body:
Found a workaround, just notices it's better to use getScreenshotAs() directly on UIElement without doing alot of manipulation on the element.

public void takeSmallScreenshot(WebDriver driver, WebElement uiElem)
{
         File uiElementSrc = uiElem.getScreenshotAs(OutputType.FILE);
         try {
            FileUtils.copyFile(uiElementSrc, new File(".\\Screenshots\\"+uiElem.getText().substring(0,5)+".png"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}


问:
Issues Setting Up NLTK within Python Environment
I am new to programming and I am in the process of attempting to download NLTK to work on a chatbot with Python. At the moment, I am running Python 2.7. As per the documentation for the NLTK available, "NLTK requires Python versions 2.7, 3.5, 3.6, or 3.7."

I downloaded Homebrew and ran the commands the documentation suggested, but have gotten error messages.

```<code>Leonas-MacBook-Air:~ leonaadriennestephanieponce$ sudo pip install -U nltk
Password:
Sorry, try again.
Password:
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.
WARNING: The directory '/Users/leonaadriennestephanieponce/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
WARNING: The directory '/Users/leonaadriennestephanieponce/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting nltk
  Downloading https://files.pythonhosted.org/packages/73/56/90178929712ce427ebad179f8dc46c8deef4e89d4c853092bee1efd57d05/nltk-3.4.1.zip (3.1MB)
     |████████████████████████████████| 3.1MB 548kB/s
    ERROR: Complete output from command python setup.py egg_info:
    ERROR: error in nltk setup command: 'install_requires' must be a string or list of strings containing valid project/version requirement specifiers; Expected version spec in singledispatch; python_version < "3.4" at ; python_version < "3.4"
    ----------------------------------------
ERROR: Command "python setup.py egg_info" failed with error code 1 in /private/tmp/pip-install-OTcEsN/nltk/
Leonas-MacBook-Air:~ leonaadriennestephanieponce$ sudo easy_install pip
Password:
Sorry, try again.
Password:
Sorry, try again.
Password:
Searching for pip
Best match: pip 19.1.1
Processing pip-19.1.1-py2.7.egg
pip 19.1.1 is already the active version in easy-install.pth
Installing pip script to /usr/local/bin
Installing pip2.7 script to /usr/local/bin
Installing pip2 script to /usr/local/bin

Using /Library/Python/2.7/site-packages/pip-19.1.1-py2.7.egg
Processing dependencies for pip
Finished processing dependencies for pip
Leonas-MacBook-Air:~ leonaadriennestephanieponce$ sudo pip install -U nltk
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.
WARNING: The directory '/Users/leonaadriennestephanieponce/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
WARNING: The directory '/Users/leonaadriennestephanieponce/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting nltk
  Downloading https://files.pythonhosted.org/packages/73/56/90178929712ce427ebad179f8dc46c8deef4e89d4c853092bee1efd57d05/nltk-3.4.1.zip (3.1MB)
     |████████████████████████████████| 3.1MB 465kB/s
    ERROR: Complete output from command python setup.py egg_info:
    ERROR: error in nltk setup command: 'install_requires' must be a string or list of strings containing valid project/version requirement specifiers; Expected version spec in singledispatch; python_version < "3.4" at ; python_version < "3.4"
    ----------------------------------------
ERROR: Command "python setup.py egg_info" failed with error code 1 in /private/tmp/pip-install-vY99RW/nltk/
Leonas-MacBook-Air:~ leonaadriennestephanieponce$
</code>```

Per the documentation available at: https://www.nltk.org/install.html

I attempted the " sudo pip install -U nltk" command, which returned the errors:

```<code>ERROR: Complete output from command python setup.py egg_info:
ERROR: error in nltk setup command: 'install_requires' must be a string or list of strings containing valid project/version requirement specifiers; Expected version spec in singledispatch; python_version < "3.4" at ; python_version < "3.4"
    ----------------------------------------
ERROR: Command "python setup.py egg_info" failed with error code 1 in /private/tmp/pip-install-OTcEsN/nltk/

</code>```

I also tried the suggestion on the bottom of the documentation page with no luck, specifically "For older versions of Python it might be necessary to install setuptools (see http://pypi.python.org/pypi/setuptools) and to install pip (sudo easy_install pip)." The following errors resulted:

```<code>ERROR: Complete output from command python setup.py egg_info:
ERROR: error in nltk setup command: 'install_requires' must be a string or list of strings containing valid project/version requirement specifiers; Expected version spec in singledispatch; python_version < "3.4" at ; python_version < "3.4"
    ----------------------------------------
ERROR: Command "python setup.py egg_info" failed with error code 1 in /private/tmp/pip-install-vY99RW/nltk/
</code>```

Your help is much appreciated! Many thanks from Jupiter, FL, USA!

答: Try running sudo -H pip3 install -U nltk

Body:
I am new to programming and I am in the process of attempting to download NLTK to work on a chatbot with Python. At the moment, I am running Python 2.7. As per the documentation for the NLTK available, "NLTK requires Python versions 2.7, 3.5, 3.6, or 3.7."

I downloaded Homebrew and ran the commands the documentation suggested, but have gotten error messages.

Leonas-MacBook-Air:~ leonaadriennestephanieponce$ sudo pip install -U nltk
Password:
Sorry, try again.
Password:
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.
WARNING: The directory '/Users/leonaadriennestephanieponce/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
WARNING: The directory '/Users/leonaadriennestephanieponce/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting nltk
  Downloading https://files.pythonhosted.org/packages/73/56/90178929712ce427ebad179f8dc46c8deef4e89d4c853092bee1efd57d05/nltk-3.4.1.zip (3.1MB)
     |████████████████████████████████| 3.1MB 548kB/s
    ERROR: Complete output from command python setup.py egg_info:
    ERROR: error in nltk setup command: 'install_requires' must be a string or list of strings containing valid project/version requirement specifiers; Expected version spec in singledispatch; python_version < "3.4" at ; python_version < "3.4"
    ----------------------------------------
ERROR: Command "python setup.py egg_info" failed with error code 1 in /private/tmp/pip-install-OTcEsN/nltk/
Leonas-MacBook-Air:~ leonaadriennestephanieponce$ sudo easy_install pip
Password:
Sorry, try again.
Password:
Sorry, try again.
Password:
Searching for pip
Best match: pip 19.1.1
Processing pip-19.1.1-py2.7.egg
pip 19.1.1 is already the active version in easy-install.pth
Installing pip script to /usr/local/bin
Installing pip2.7 script to /usr/local/bin
Installing pip2 script to /usr/local/bin

Using /Library/Python/2.7/site-packages/pip-19.1.1-py2.7.egg
Processing dependencies for pip
Finished processing dependencies for pip
Leonas-MacBook-Air:~ leonaadriennestephanieponce$ sudo pip install -U nltk
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.
WARNING: The directory '/Users/leonaadriennestephanieponce/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
WARNING: The directory '/Users/leonaadriennestephanieponce/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting nltk
  Downloading https://files.pythonhosted.org/packages/73/56/90178929712ce427ebad179f8dc46c8deef4e89d4c853092bee1efd57d05/nltk-3.4.1.zip (3.1MB)
     |████████████████████████████████| 3.1MB 465kB/s
    ERROR: Complete output from command python setup.py egg_info:
    ERROR: error in nltk setup command: 'install_requires' must be a string or list of strings containing valid project/version requirement specifiers; Expected version spec in singledispatch; python_version < "3.4" at ; python_version < "3.4"
    ----------------------------------------
ERROR: Command "python setup.py egg_info" failed with error code 1 in /private/tmp/pip-install-vY99RW/nltk/
Leonas-MacBook-Air:~ leonaadriennestephanieponce$

Per the documentation available at: https://www.nltk.org/install.html

I attempted the " sudo pip install -U nltk" command, which returned the errors:

ERROR: Complete output from command python setup.py egg_info:
ERROR: error in nltk setup command: 'install_requires' must be a string or list of strings containing valid project/version requirement specifiers; Expected version spec in singledispatch; python_version < "3.4" at ; python_version < "3.4"
    ----------------------------------------
ERROR: Command "python setup.py egg_info" failed with error code 1 in /private/tmp/pip-install-OTcEsN/nltk/

I also tried the suggestion on the bottom of the documentation page with no luck, specifically "For older versions of Python it might be necessary to install setuptools (see http://pypi.python.org/pypi/setuptools) and to install pip (sudo easy_install pip)." The following errors resulted:

ERROR: Complete output from command python setup.py egg_info:
ERROR: error in nltk setup command: 'install_requires' must be a string or list of strings containing valid project/version requirement specifiers; Expected version spec in singledispatch; python_version < "3.4" at ; python_version < "3.4"
    ----------------------------------------
ERROR: Command "python setup.py egg_info" failed with error code 1 in /private/tmp/pip-install-vY99RW/nltk/

Your help is much appreciated! Many thanks from Jupiter, FL, USA!


问:
gcc-8 -Wstringop-truncation what is the good practice?
GCC 8 added a -Wstringop-truncation warning. From https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82944 :

The -Wstringop-truncation warning added in GCC 8.0 via r254630 for bug 81117 is specifically intended to highlight likely unintended uses of the strncpy function that truncate the terminating NUL charcter from the source string.  An example of such a misuse given in the request is the following:

```<code>char buf[2];

void test (const char* str)
{
  strncpy (buf, str, strlen (str));
}
</code>```

I get the same warning with this code.

```<code>strncpy(this->name, name, 32);

warning: 'char* strncpy(char*, const char*, size_t)' specified bound 32 equals destination size [-Wstringop-truncation`]
</code>```

Considering that this->name is char name[32] and name is a char* with a length potentially greater than 32. I would like to copy name into this->name and truncate it if it is greater than 32. Should size_t be 31 instead of 32? I'm confused. It is not mandatory for this->name to be NUL-terminated.

答:
I found the best way to suppress the warning is to put the expression in parentheses like this gRPC patch:

```<code>(strncpy(req->initial_request.name, lb_service_name,
         GRPC_GRPCLB_SERVICE_NAME_MAX_LENGTH));
</code>```

The problem with #pragma diagnostics suppression solution is that the #pragma itself will cause a warning when the compiler does not recognize either the pragma or the particular warning; also it is too verbose.

Body:
GCC 8 added a -Wstringop-truncation warning. From https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82944 :

The -Wstringop-truncation warning added in GCC 8.0 via r254630 for bug 81117 is specifically intended to highlight likely unintended uses of the strncpy function that truncate the terminating NUL charcter from the source string.  An example of such a misuse given in the request is the following:

char buf[2];

void test (const char* str)
{
  strncpy (buf, str, strlen (str));
}

I get the same warning with this code.

strncpy(this->name, name, 32);

warning: 'char* strncpy(char*, const char*, size_t)' specified bound 32 equals destination size [-Wstringop-truncation`]

Considering that this->name is char name[32] and name is a char* with a length potentially greater than 32. I would like to copy name into this->name and truncate it if it is greater than 32. Should size_t be 31 instead of 32? I'm confused. It is not mandatory for this->name to be NUL-terminated.

Body:
I found the best way to suppress the warning is to put the expression in parentheses like this gRPC patch:

(strncpy(req->initial_request.name, lb_service_name,
         GRPC_GRPCLB_SERVICE_NAME_MAX_LENGTH));

The problem with #pragma diagnostics suppression solution is that the #pragma itself will cause a warning when the compiler does not recognize either the pragma or the particular warning; also it is too verbose.


问:
Flutter: How to use HapticFeedback
I have imported

```<code>import 'package:flutter/services.dart';
</code>```

and then called

```<code>HapticFeedback.lightImpact();
</code>```

nothing happens. What do I need to do to get it working?
I am testing with the latest Flutter version 1.6.6 on a Galaxy S8 running Android 9.0

答:
Try using this for Android:

```<code>Feedback.forTap(context);
</code>```

More info: https://api.flutter.dev/flutter/material/Feedback-class.html

Title: Flutter: How to use HapticFeedback

Body:
I have imported

import 'package:flutter/services.dart';

and then called

HapticFeedback.lightImpact();

nothing happens. What do I need to do to get it working?
I am testing with the latest Flutter version 1.6.6 on a Galaxy S8 running Android 9.0

Body:
Try using this for Android:

Feedback.forTap(context);

More info: https://api.flutter.dev/flutter/material/Feedback-class.html


问:
I want to run a function that creates images through a dataframe in python
This is a screenshot of the dataframeI'm really new to python and I would appreciate any help or recommendations for my problem.
So I created a few really simple lines of code that merge two images next to each other, but now I want to do that operation for a list of 80 pairs of images, that I have already put into a 80 x 2 dataframe using pd.read_excel from pandas. Any suggestions, even if just about where to search to find out more, are greatly appreciated, since I'm just stuck as to where to look.</p>

```<code> from PIL import Image
import os
os.chdir("/Users/someone/Documents/stimuli_final")

img = Image.open("/Users/me/Documents/StimuliOnly/1_5_1_n1.bmp")
img = img.resize((1280, 1280))
img1 = Image.open("/Users/me/Documents/StimuliOnly/1_10_1_n2.bmp")
img1 = img1.resize((1280, 1280))
bi = Image.new("RGBA", (2760, 1280), ("#808080"))
bi.paste(img, (0,0,1280,1280))
bi.paste(img1, (1480,0,2760,1280))
bi.save("stim5with14vs28congruent.png")
</code>```

答:
If you added another column to your excel file titled "output file name" and filled that column, you could use something like the following:

def helper(data):
    path1, path2, output_file_name = data["Bild 1"], data["Bild 2"], data["output file name"]
    img = Image.open(path1)
    img = img.resize((1280, 1280))
    img1 = Image.open(path2)
    img1 = img1.resize((1280, 1280))
    bi = Image.new("RGBA", (2760, 1280), ("#808080"))
    bi.paste(img, (0,0,1280,1280))
    bi.paste(img1, (1480,0,2760,1280))
    bi.save(output_file_name)

df.apply(helper, axis=1)
```

Body:
This is a screenshot of the dataframeI'm really new to python and I would appreciate any help or recommendations for my problem.
So I created a few really simple lines of code that merge two images next to each other, but now I want to do that operation for a list of 80 pairs of images, that I have already put into a 80 x 2 dataframe using pd.read_excel from pandas. Any suggestions, even if just about where to search to find out more, are greatly appreciated, since I'm just stuck as to where to look.

 from PIL import Image
import os
os.chdir("/Users/someone/Documents/stimuli_final")

img = Image.open("/Users/me/Documents/StimuliOnly/1_5_1_n1.bmp")
img = img.resize((1280, 1280))
img1 = Image.open("/Users/me/Documents/StimuliOnly/1_10_1_n2.bmp")
img1 = img1.resize((1280, 1280))
bi = Image.new("RGBA", (2760, 1280), ("#808080"))
bi.paste(img, (0,0,1280,1280))
bi.paste(img1, (1480,0,2760,1280))
bi.save("stim5with14vs28congruent.png")


问:
PG_SEARCH gem search specific columns only for JSON
I have jsonb column in my postgres table and i want to search only one key not all the keys.

e.g.

```<code>Book.create!(details: {authour: 'example', title: 'something'}

class Book < ApplicationRecord
  include PgSearch
  pg_search_scope :search,
                  against: [
                    :details
                  ]
end
</code>```

I want to search titles and ignore the author names.

答: There is a request for this on their GitHub page, however it is not supported at the moment. </p>

Body:
I have jsonb column in my postgres table and i want to search only one key not all the keys.

e.g.

Book.create!(details: {authour: 'example', title: 'something'}

class Book < ApplicationRecord
  include PgSearch
  pg_search_scope :search,
                  against: [
                    :details
                  ]
end

I want to search titles and ignore the author names.


问:
When the deadline starts to count down?
I have a question about when the deadline starts to count down? Does the deadline start to count down when arguments are marshaled and waiting to be sent, or after the arguments are sent out? </p>

答:
A deadline refers to a specific moment in time, usually in the future. It's like an alarm for a specific time, rather than a timer for a specific amount of time. So, for example, if you set a deadline of now + 1 second, it is by definition counting 1 second from when you performed that calculation. If you set the deadline to 4:30 PM today, it doesn't matter when you start counting, because that doesn't change when the deadline will be reached.

The client converts the deadline to a duration when sending it to the server, and then the server counts from when it receives it. Those calculations do not account for the transit time, so that timer will have a slight delay added. However, he deadline on the server is just for determining when it is no longer useful to continue processing a request, so it doesn't need to be precise.

Title: When the deadline starts to count down?


问:
How to make an EditText automatically scroll after an X amount of lines
I have found plenty of answers on how to make scrollable EditText, but none mentions how to make the text scroll after an X amount of lines. In my app i need the text scrolling on its own after 5 lines, otherwise text gets mixed up with icons bellow. So far i have been restricting maxLength to avoid this, but i need to be able to write more characters without worrying that they get mixed up with icons. </p>

```<code><EditText
    android:id="@+id/resultText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="10dp"
    android:textColorHint="@color/white"
    android:textColor="@color/colorPrimaryDark"
    android:textIsSelectable="true"
    android:gravity="top"
    android:fontFamily="sans-serif"
    android:textSize="25dp"
    android:textStyle="normal"
    android:ems="30"
    android:maxLength="180"
    android:hint="Input here..."
    android:textAlignment="center"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:inputType="textMultiLine"
    android:overScrollMode="always"
    android:scrollbarStyle="insideInset"/>
</code>```

答:
Turns out what i was searching for was:</p>

```<code>android:lines="5"
</code>```

Body:
I have found plenty of answers on how to make scrollable EditText, but none mentions how to make the text scroll after an X amount of lines. In my app i need the text scrolling on its own after 5 lines, otherwise text gets mixed up with icons bellow. So far i have been restricting maxLength to avoid this, but i need to be able to write more characters without worrying that they get mixed up with icons.

<EditText
    android:id="@+id/resultText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="10dp"
    android:textColorHint="@color/white"
    android:textColor="@color/colorPrimaryDark"
    android:textIsSelectable="true"
    android:gravity="top"
    android:fontFamily="sans-serif"
    android:textSize="25dp"
    android:textStyle="normal"
    android:ems="30"
    android:maxLength="180"
    android:hint="Input here..."
    android:textAlignment="center"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:inputType="textMultiLine"
    android:overScrollMode="always"
    android:scrollbarStyle="insideInset"/>

Body:
Turns out what i was searching for was:

android:lines="5"


问:
Floating right pushes div to the end of the page
I am trying to put 2 divs side by side. However, when doing this, one div is pushed to the very right of the page? I am not sure why it is doing this. Any help is appreciated :)

JSFIDDLE:
https://jsfiddle.net/7crhg2L8/

HTML:

```<code><div class="navrectangle"></div>
<div class="addrectangle"></div>
</code>```

CSS:

```<code>.navrectangle{
  width: 20Vw;
  height: 100vh;
background-image: linear-gradient(to right, #002067, #013d98);
float: left;
}
/** SECOND RECTANGLE **/
.addrectangle{
  float:right;
  width: 20Vw;
  height: 100vh;
background-image: linear-gradient(to right, #002067, #013d98);
}
</code>```

答:
You need to float both divs left to have them next to each other.</p>

```<code>.navrectangle{
  width: 20Vw;
  height: 100vh;
background-image: linear-gradient(to right, #002067, #013d98);
float: left;
}
/** SECOND RECTANGLE **/
.addrectangle{
  float:left;
  display: inline-block;
  width: 20Vw;
  height: 100vh;
background-image: linear-gradient(to right, #002067, #013d98);
}
</code>```

Body:
I am trying to put 2 divs side by side. However, when doing this, one div is pushed to the very right of the page? I am not sure why it is doing this. Any help is appreciated :)

JSFIDDLE:
https://jsfiddle.net/7crhg2L8/

HTML:

CSS:

.navrectangle{
  width: 20Vw;
  height: 100vh;
background-image: linear-gradient(to right, #002067, #013d98);
float: left;
}
/** SECOND RECTANGLE **/
.addrectangle{
  float:right;
  width: 20Vw;
  height: 100vh;
background-image: linear-gradient(to right, #002067, #013d98);
}

Body:
You need to float both divs left to have them next to each other.

.navrectangle{
  width: 20Vw;
  height: 100vh;
background-image: linear-gradient(to right, #002067, #013d98);
float: left;
}
/** SECOND RECTANGLE **/
.addrectangle{
  float:left;
  display: inline-block;
  width: 20Vw;
  height: 100vh;
background-image: linear-gradient(to right, #002067, #013d98);
}


问:
Custom transition between two UIViews
I have two views "A" and "B". A floats in the middle of the window (it's not full screen). B, the view which will replace A, is full screen. I'd like to write a custom transition that flips A to reveal B on the back side, but simultaneously scales the flipping rectangle so that when the flip is finished, B is full screen.

I've tried using the flip transitions available with transitionFromView:toView:duration:options:completion, but I can only get it to flip the entire screen instead of starting the flip with A's frame and ending with B's frame.

I know I can do 3D-like transforms to the view's layers, but I'm not sure which set of animation APIs I should use to accomplish this. One thing I tried is to modify the view's layer properties in the animations block of transitionWithView:duration:options:animations:completion: but that didn't work as it only seems to honor view property modifications.

Can someone point me in the right direction? I'd much appreciate it.

UPDATE: Here is my code thus far for this effect. You can see a video of what it does here: http://www.youtube.com/watch?v=-xNMD2fGRwg

```<code>CGRect frame = [[UIApplication easybookDelegate] rootViewController].view.bounds ;
float statusHeight = [UIApplication sharedApplication].statusBarFrame.size.height ;
frame.origin.y = statusHeight ;
frame.size.height -= statusHeight ;
self.view.frame = frame ; // self.view is view "B"

// Put the snapshot as thet topmost view of our view
UIImageView *imageView = [[UIImageView alloc] initWithImage:image] ; // image is a snapshot of view "A"
imageView.frame = self.view.bounds ;
[self.view addSubview:imageView] ;
[self.view bringSubviewToFront:imageView] ;

// Pre-transform our view (s=target/current, d=target-current)
CGAffineTransform transform = CGAffineTransformIdentity ;

// Translate our view
CGPoint center  = CGPointMake(screenOrigin.x + (image.size.width/2.0), screenOrigin.y + (image.size.height/2.0)) ;
float dX = center.x - self.view.center.x ;
float dY = center.y - self.view.center.y ;
NSLog( @"dx: %f, dy: %f" , dX, dY ) ;

transform = CGAffineTransformTranslate(transform, dX, dY) ;

// Scale our view
float scaleWFactor = image.size.width / self.view.frame.size.width ;
float scaleHFactor = image.size.height / self.view.frame.size.height ;
transform = CGAffineTransformScale(transform,scaleWFactor, scaleHFactor) ;

self.view.transform = transform ;

[[[UIApplication easybookDelegate] rootViewController].view addSubview:self.view] ;

// Perform the animation later since implicit animations don't seem to work due to
// view "B" just being added above and hasn't had a chance to become visible. Right now
// this is just on a timer for debugging purposes. It'll probably be moved elsewhere, probably
// to view "B"'s -didMoveToSuperview
double delayInSeconds = 0.3;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    [UIView transitionWithView:self.view duration:3 options:UIViewAnimationOptionTransitionFlipFromRight| UIViewAnimationOptionCurveEaseOut animations:^(void)
        {
        [imageView removeFromSuperview] ;
        self.view.transform = CGAffineTransformIdentity ;
        }
        completion:^(BOOL finished){
                [self.view removeFromSuperview] ;
                [navController presentModalViewController:self animated:NO] ;
        }] ;
});

[imageView release];
</code>```

答:
I've done this before. Here's the gist of how I did it:

View A is on screen

Create View B, give it a frame that makes it fullscreen, but don't add it to the screen yet

View B has a UIImageView as it's topmost view

Capture a UIImage of View A, and set it as the image of View B's image view

```<code>UIGraphicsBeginImageContext(view.bounds.size);
[viewA.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
viewB.imageView.image = image;
</code>```

Set View B's transform (scale and translation) so that it is shrunk to the size of View A and is positioned where View A is on the screen

Add View B to the screen

At this point, the user hasn't noticed anything change, because View B looks exactly like View A

Now start an animation block, in which you

Set [UIView setAnimationTransition: UIViewAnimationTransitionFlipFromLeft forView:ViewB

set View B's transform to CGAffineTransformIdentity

remove View B's imageview from View B

The result is an animation that looks like View A is flipping over and zooming to fill the screen with View B as the opposite side.

Title: Custom transition between two UIViews

Body:
I have two views "A" and "B". A floats in the middle of the window (it's not full screen). B, the view which will replace A, is full screen. I'd like to write a custom transition that flips A to reveal B on the back side, but simultaneously scales the flipping rectangle so that when the flip is finished, B is full screen.

I've tried using the flip transitions available with transitionFromView:toView:duration:options:completion, but I can only get it to flip the entire screen instead of starting the flip with A's frame and ending with B's frame.

I know I can do 3D-like transforms to the view's layers, but I'm not sure which set of animation APIs I should use to accomplish this. One thing I tried is to modify the view's layer properties in the animations block of transitionWithView:duration:options:animations:completion: but that didn't work as it only seems to honor view property modifications.

Can someone point me in the right direction? I'd much appreciate it.

UPDATE: Here is my code thus far for this effect. You can see a video of what it does here: http://www.youtube.com/watch?v=-xNMD2fGRwg

CGRect frame = [[UIApplication easybookDelegate] rootViewController].view.bounds ;
float statusHeight = [UIApplication sharedApplication].statusBarFrame.size.height ;
frame.origin.y = statusHeight ;
frame.size.height -= statusHeight ;
self.view.frame = frame ; // self.view is view "B"

// Put the snapshot as thet topmost view of our view
UIImageView *imageView = [[UIImageView alloc] initWithImage:image] ; // image is a snapshot of view "A"
imageView.frame = self.view.bounds ;
[self.view addSubview:imageView] ;
[self.view bringSubviewToFront:imageView] ;

// Pre-transform our view (s=target/current, d=target-current)
CGAffineTransform transform = CGAffineTransformIdentity ;

// Translate our view
CGPoint center  = CGPointMake(screenOrigin.x + (image.size.width/2.0), screenOrigin.y + (image.size.height/2.0)) ;
float dX = center.x - self.view.center.x ;
float dY = center.y - self.view.center.y ;
NSLog( @"dx: %f, dy: %f" , dX, dY ) ;

transform = CGAffineTransformTranslate(transform, dX, dY) ;

// Scale our view
float scaleWFactor = image.size.width / self.view.frame.size.width ;
float scaleHFactor = image.size.height / self.view.frame.size.height ;
transform = CGAffineTransformScale(transform,scaleWFactor, scaleHFactor) ;

self.view.transform = transform ;

[[[UIApplication easybookDelegate] rootViewController].view addSubview:self.view] ;

// Perform the animation later since implicit animations don't seem to work due to
// view "B" just being added above and hasn't had a chance to become visible. Right now
// this is just on a timer for debugging purposes. It'll probably be moved elsewhere, probably
// to view "B"'s -didMoveToSuperview
double delayInSeconds = 0.3;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    [UIView transitionWithView:self.view duration:3 options:UIViewAnimationOptionTransitionFlipFromRight| UIViewAnimationOptionCurveEaseOut animations:^(void)
        {
        [imageView removeFromSuperview] ;
        self.view.transform = CGAffineTransformIdentity ;
        }
        completion:^(BOOL finished){
                [self.view removeFromSuperview] ;
                [navController presentModalViewController:self animated:NO] ;
        }] ;
});

[imageView release];

Body:
I've done this before. Here's the gist of how I did it:

View A is on screen

Create View B, give it a frame that makes it fullscreen, but don't add it to the screen yet

View B has a UIImageView as it's topmost view

Capture a UIImage of View A, and set it as the image of View B's image view

UIGraphicsBeginImageContext(view.bounds.size);
[viewA.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
viewB.imageView.image = image;

Set View B's transform (scale and translation) so that it is shrunk to the size of View A and is positioned where View A is on the screen

Add View B to the screen

At this point, the user hasn't noticed anything change, because View B looks exactly like View A

Now start an animation block, in which you

Set [UIView setAnimationTransition: UIViewAnimationTransitionFlipFromLeft forView:ViewB

set View B's transform to CGAffineTransformIdentity

remove View B's imageview from View B

The result is an animation that looks like View A is flipping over and zooming to fill the screen with View B as the opposite side.


问:
Can I export a tensorflow summary to CSV?
Is there a way to extract scalar summaries to CSV (preferably from within tensorboard) from tfevents files?

Example code

The following code generates tfevent files in a summary_dir within the same directory. Suppose you let it run and you find something interesting. You want to get the raw data for further investigation. How would you do that?

#!/usr/bin/env python
"""A very simple MNIST classifier."""
import argparse
import sys

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf
ce_with_logits = tf.nn.softmax_cross_entropy_with_logits

FLAGS = None

def inference(x):
    """
    Build the inference graph.

    Parameters
    ----------
    x : placeholder

    Returns
    -------
    Output tensor with the computed logits.
    """
    W = tf.Variable(tf.zeros([784, 10]))
    b = tf.Variable(tf.zeros([10]))
    y = tf.matmul(x, W) + b
    return y

def loss(logits, labels):
    """
    Calculate the loss from the logits and the labels.

    Parameters
    ----------
    logits : Logits tensor, float - [batch_size, NUM_CLASSES].
    labels : Labels tensor, int32 - [batch_size]
    """
    cross_entropy = tf.reduce_mean(ce_with_logits(labels=labels,
                                                  logits=logits))
    return cross_entropy

def training(loss, learning_rate=0.5):
    """
    Set up the training Ops.

    Parameters
    ----------
    loss : Loss tensor, from loss().
    learning_rate : The learning rate to use for gradient descent.

    Returns
    -------
    train_op: The Op for training.
    """
    optimizer = tf.train.GradientDescentOptimizer(learning_rate)
    train_step = optimizer.minimize(loss)
    return train_step

def main(_):
    # Import data
    mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)

    # Create the model
    x = tf.placeholder(tf.float32, [None, 784])
    y = inference(x)

    # Define loss and optimizer
    y_ = tf.placeholder(tf.float32, [None, 10])
    loss_ = loss(logits=y, labels=y_)
    train_step = training(loss_)

    # Test trained model
    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

    with tf.name_scope('accuracy'):
        tf.summary.scalar('accuracy', accuracy)
    merged = tf.summary.merge_all()

    sess = tf.InteractiveSession()
    train_writer = tf.summary.FileWriter('summary_dir/train', sess.graph)
    test_writer = tf.summary.FileWriter('summary_dir/test', sess.graph)
    tf.global_variables_initializer().run()

    for train_step_i in range(100000):
        if train_step_i % 100 == 0:
            summary, acc = sess.run([merged, accuracy],
                                    feed_dict={x: mnist.test.images,
                                               y_: mnist.test.labels})
            test_writer.add_summary(summary, train_step_i)
            summary, acc = sess.run([merged, accuracy],
                                    feed_dict={x: mnist.train.images,
                                               y_: mnist.train.labels})
            train_writer.add_summary(summary, train_step_i)
        batch_xs, batch_ys = mnist.train.next_batch(100)
        sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

    print(sess.run(accuracy, feed_dict={x: mnist.test.images,
                                        y_: mnist.test.labels}))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--data_dir',
                        type=str,
                        default='/tmp/tensorflow/mnist/input_data',
                        help='Directory for storing input data')
    FLAGS, unparsed = parser.parse_known_args()
    tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
```

答:
Just to add to @Spen

in case you want to export the data when you have varying numbers of steps.
This will make one large csv file.
Might need to change around the keys for it to work for you.

```<code>import os
import numpy as np
import pandas as pd

from collections import defaultdict
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
import glob
import pandas as pd
listOutput = (glob.glob("*/"))

listDF = []

for tb_output_folder in listOutput:
 print(tb_output_folder)
 x = EventAccumulator(path=tb_output_folder)
 x.Reload()
 x.FirstEventTimestamp()
 keys = ['loss', 'mean_absolute_error', 'val_loss', 'val_mean_absolute_error']

 listValues = {}

 steps = [e.step for e in x.Scalars(keys[0])]
 wall_time = [e.wall_time for e in x.Scalars(keys[0])]
 index = [e.index for e in x.Scalars(keys[0])]
 count = [e.count for e in x.Scalars(keys[0])]
 n_steps = len(steps)
 listRun = [tb_output_folder] * n_steps
 printOutDict = {}

 data = np.zeros((n_steps, len(keys)))
 for i in range(len(keys)):
     data[:,i] = [e.value for e in x.Scalars(keys[i])]

 printOutDict = {keys[0]: data[:,0], keys[1]: data[:,1],keys[2]: data[:,2],keys[3]: data[:,3]}

 printOutDict['Name'] = listRun

 DF = pd.DataFrame(data=printOutDict)

 listDF.append(DF)

df = pd.concat(listDF)
df.to_csv('Output.csv')

</code>```

Body:
Just to add to @Spen

in case you want to export the data when you have varying numbers of steps.
This will make one large csv file.
Might need to change around the keys for it to work for you.

import os
import numpy as np
import pandas as pd

from collections import defaultdict
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
import glob
import pandas as pd
listOutput = (glob.glob("*/"))

listDF = []

for tb_output_folder in listOutput:
 print(tb_output_folder)
 x = EventAccumulator(path=tb_output_folder)
 x.Reload()
 x.FirstEventTimestamp()
 keys = ['loss', 'mean_absolute_error', 'val_loss', 'val_mean_absolute_error']

 listValues = {}

 steps = [e.step for e in x.Scalars(keys[0])]
 wall_time = [e.wall_time for e in x.Scalars(keys[0])]
 index = [e.index for e in x.Scalars(keys[0])]
 count = [e.count for e in x.Scalars(keys[0])]
 n_steps = len(steps)
 listRun = [tb_output_folder] * n_steps
 printOutDict = {}

 data = np.zeros((n_steps, len(keys)))
 for i in range(len(keys)):
     data[:,i] = [e.value for e in x.Scalars(keys[i])]

 printOutDict = {keys[0]: data[:,0], keys[1]: data[:,1],keys[2]: data[:,2],keys[3]: data[:,3]}

 printOutDict['Name'] = listRun

 DF = pd.DataFrame(data=printOutDict)

 listDF.append(DF)

df = pd.concat(listDF)
df.to_csv('Output.csv')


问:
Passing additional vs one argument into the function
I am implementing compose function using reduceRight menthod as follows

const compose = fns => (...args) =>
  fns.reduceRight((acc, fn) => fn(acc, ...[args.slice(1)]), args[0]);

const func3 = (x, y) => (y > 0 ? x + 3 : x - 3);

const func2 = x => x ** 2;

const func1 = x => x - 8;

const fnOne = compose([func1, func2, func3])('3', 1);
console.log(fnOne); // should be 1081

const fnTwo = compose([func1, func2, func3])('3', -1);
console.log(fnTwo); //should be -8```

the first function is supposed to receive two arguments and return the result to the next function as the only one argument. The problem is that the first function is passing two arguments to the next function instead of one. Let me know if you have any ideas how to fix it. Any help is very much appreciated.

答:
You need to call the first function outside the reduceRight() loop, since it's not being called the same way as all the other functions. It gets its arguments from ...args and its value should be used as the initial accumulator argument to reduce.

const compose = fns => (...args) => {
  let last = fns.pop();
  return fns.reduceRight((acc, fn) => fn(acc), last(...args))
};

const func3 = function(x, y) {
  console.log(`func3 got ${arguments.length} arguments`);
  return (y > 0 ? x + 3 : x - 3);
};

const func2 = function(x) {
  console.log(`func2 got ${arguments.length} arguments`);
  return x ** 2;
};

const func1 = function(x) {
  console.log(`func2 got ${arguments.length} arguments`);
  return x - 8;
};

const fnOne = compose([func1, func2, func3])('3', 1);
console.log(fnOne); // should be 1081

const fnTwo = compose([func1, func2, func3])('3', -1);
console.log(fnTwo); //should be -8```

Body:
I am implementing compose function using reduceRight menthod as follows

const compose = fns => (...args) =>
  fns.reduceRight((acc, fn) => fn(acc, ...[args.slice(1)]), args[0]);

const func3 = (x, y) => (y > 0 ? x + 3 : x - 3);

const func2 = x => x ** 2;

const func1 = x => x - 8;

const fnOne = compose([func1, func2, func3])('3', 1);
console.log(fnOne); // should be 1081

const fnTwo = compose([func1, func2, func3])('3', -1);
console.log(fnTwo); //should be -8

the first function is supposed to receive two arguments and return the result to the next function as the only one argument. The problem is that the first function is passing two arguments to the next function instead of one. Let me know if you have any ideas how to fix it. Any help is very much appreciated.