问:
click() in jquery run function without to realy click on element
I have some question about my code i dont realy understand how is working :
I call function submitColumn , the function check if a have the element in my array , if i dont have will append an <li>list with the element name and id </li>
in the same time will append to that list an span whit a id an class , that span i want to use on click to remove element from my array and remove element from my list , but span.click(deleteColumn()) is call automatic and that is what im not understand .
Thanks for helping me , have a great day all of you  </p>

```<code>function submitColumn() {
    //get textual input from the user.
    var colName = document.querySelector("#txtCol").value;
    var colType = document.querySelector("#selectType").value;

    if (columnsArray.length > 0) {
        for (var i = 0; i < columnsArray.length; i++) {
            var count = undefined;
            if (columnsArray[i] === colName) {
                count = true;
            } else if (columnsArray[i] !== colName) {
                count = false;
            }
        }

        if (count) {
            return alert("You can not call two column with the same name");
        } else {
            $("<li/>").attr("id", colName + "id").addClass("colAndType").text("New column added with name: " + colName + " and  type " + colType).appendTo("#colListUl");
            $("#" + colName + "id").append('<span class="nav-click" />');
            $(".nav-click").addClass("ui-icon ui-icon-closethick").attr("id", "close" + colName).click(deleteColumn(colName));
            columnsArray.push(colName);
            columnsTypeArray.push(colType);
        }
    } else {
        $("<li/>").attr("id", colName + "id").addClass("colAndType").text("New column added with name: " + colName + " and  type " + colType).appendTo("#colListUl");
        $("#" + colName + "id").append('<span class="nav-click" />');
        $(".nav-click").addClass("ui-icon ui-icon-closethick").attr("id", "close" + colName).click(deleteColumn(colName));
        columnsArray.push(colName);
        columnsTypeArray.push(colType);
    }
}

function deleteColumn(idColumn) {
    var idLi = idColumn + "id";
    var close = "close" + idColumn;
    console.log(close, idLi);
}
</code>```

答:
This line of code is executing the deleteColumn function, rather than referencing it...

```<code>$(".nav-click").addClass("ui-icon ui-icon-closethick")
    .attr("id", "close" + colName).click(deleteColumn(colName));
</code>```

If you change it so you add a reference to the function, rather than execute it, then it should resolve your problem...

```<code>$(".nav-click").addClass("ui-icon ui-icon-closethick")
    .attr("id", "close" + colName).click((function(columnId) {
        deleteColumn(columnId)
    })(colName));
</code>```

Don't forget to change it in both places where you have that same code.

Body:
I have some question about my code i dont realy understand how is working :
I call function submitColumn , the function check if a have the element in my array , if i dont have will append an
list with the element name and id

in the same time will append to that list an span whit a id an class , that span i want to use on click to remove element from my array and remove element from my list , but span.click(deleteColumn()) is call automatic and that is what im not understand .
Thanks for helping me , have a great day all of you

function submitColumn() {
    //get textual input from the user.
    var colName = document.querySelector("#txtCol").value;
    var colType = document.querySelector("#selectType").value;

    if (columnsArray.length > 0) {
        for (var i = 0; i < columnsArray.length; i++) {
            var count = undefined;
            if (columnsArray[i] === colName) {
                count = true;
            } else if (columnsArray[i] !== colName) {
                count = false;
            }
        }

        if (count) {
            return alert("You can not call two column with the same name");
        } else {
            $("
").attr("id", colName + "id").addClass("colAndType").text("New column added with name: " + colName + " and  type " + colType).appendTo("#colListUl");
            $("#" + colName + "id").append('');
            $(".nav-click").addClass("ui-icon ui-icon-closethick").attr("id", "close" + colName).click(deleteColumn(colName));
            columnsArray.push(colName);
            columnsTypeArray.push(colType);
        }
    } else {
        $("
").attr("id", colName + "id").addClass("colAndType").text("New column added with name: " + colName + " and  type " + colType).appendTo("#colListUl");
        $("#" + colName + "id").append('');
        $(".nav-click").addClass("ui-icon ui-icon-closethick").attr("id", "close" + colName).click(deleteColumn(colName));
        columnsArray.push(colName);
        columnsTypeArray.push(colType);
    }
}

function deleteColumn(idColumn) {
    var idLi = idColumn + "id";
    var close = "close" + idColumn;
    console.log(close, idLi);
}

Body:
This line of code is executing the deleteColumn function, rather than referencing it...

$(".nav-click").addClass("ui-icon ui-icon-closethick")
    .attr("id", "close" + colName).click(deleteColumn(colName));

If you change it so you add a reference to the function, rather than execute it, then it should resolve your problem...

$(".nav-click").addClass("ui-icon ui-icon-closethick")
    .attr("id", "close" + colName).click((function(columnId) {
        deleteColumn(columnId)
    })(colName));

Don't forget to change it in both places where you have that same code.


来源: stackexchange

问:
Hadoop - Avro : java.lang.Exception: java.lang.NoClassDefFoundError: org/apache/avro/hadoop/io/AvroKeyComparator
I am developing a Map Reduce program to read the fixed length record and write as avro file. This is in draft form. While executing, I get the below error:

```<code>java.lang.Exception: java.lang.NoClassDefFoundError: org/apache/avro/hadoop/io/AvroKeyComparator
    at org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:406)
Caused by: java.lang.NoClassDefFoundError: org/apache/avro/hadoop/io/AvroKeyComparator
    at org.apache.avro.mapreduce.AvroJob.setMapOutputKeySchema(AvroJob.java:93)
    at org.apache.avro.mapreduce.AvroMultipleOutputs.setSchema(AvroMultipleOutputs.java:511)
    at org.apache.avro.mapreduce.AvroMultipleOutputs.getContext(AvroMultipleOutputs.java:547)
    at org.apache.avro.mapreduce.AvroMultipleOutputs.write(AvroMultipleOutputs.java:399)
    at org.apache.avro.mapreduce.AvroMultipleOutputs.write(AvroMultipleOutputs.java:378)
    at com.visa.edp.common.vssParser.CustomTestMapper.map(CustomTestMapper.java:98)
    at com.visa.edp.common.vssParser.CustomTestMapper.map(CustomTestMapper.java:32)
    at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:140)
    at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:672)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:330)
    at org.apache.hadoop.mapred.LocalJobRunner$Job$MapTaskRunnable.run(LocalJobRunner.java:268)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassNotFoundException: org.apache.avro.hadoop.io.AvroKeyComparator
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 16 more
17/11/10 18:13:28 INFO mapred.JobClient:  map 0% reduce 0%
</code>```

I have the following dependencies in my project:

```<code><dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-client</artifactId>
    <version>2.6.0-mr1-cdh5.8.3</version>
    <scope>provided</scope>
</dependency>

<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-core</artifactId>
    <version>2.6.0-mr1-cdh5.8.3</version>
</dependency>

<dependency>
    <groupId>org.apache.avro</groupId>
    <artifactId>avro</artifactId>
    <version>1.7.6-cdh5.8.3</version>
</dependency>

<dependency>
    <groupId>org.apache.avro</groupId>
    <artifactId>avro-mapred</artifactId>
    <version>1.7.6-cdh5.8.3</version>
</dependency>
</code>```

And could not find org.apache.avro.hadoop package under the project dependency. Am I missing any dependencies?

Thank you.

答: Added the dependency to the module and worked fine.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am developing a Map Reduce program to read the fixed length record and write as avro file. This is in draft form. While executing, I get the below error:

java.lang.Exception: java.lang.NoClassDefFoundError: org/apache/avro/hadoop/io/AvroKeyComparator
    at org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:406)
Caused by: java.lang.NoClassDefFoundError: org/apache/avro/hadoop/io/AvroKeyComparator
    at org.apache.avro.mapreduce.AvroJob.setMapOutputKeySchema(AvroJob.java:93)
    at org.apache.avro.mapreduce.AvroMultipleOutputs.setSchema(AvroMultipleOutputs.java:511)
    at org.apache.avro.mapreduce.AvroMultipleOutputs.getContext(AvroMultipleOutputs.java:547)
    at org.apache.avro.mapreduce.AvroMultipleOutputs.write(AvroMultipleOutputs.java:399)
    at org.apache.avro.mapreduce.AvroMultipleOutputs.write(AvroMultipleOutputs.java:378)
    at com.visa.edp.common.vssParser.CustomTestMapper.map(CustomTestMapper.java:98)
    at com.visa.edp.common.vssParser.CustomTestMapper.map(CustomTestMapper.java:32)
    at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:140)
    at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:672)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:330)
    at org.apache.hadoop.mapred.LocalJobRunner$Job$MapTaskRunnable.run(LocalJobRunner.java:268)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassNotFoundException: org.apache.avro.hadoop.io.AvroKeyComparator
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 16 more
17/11/10 18:13:28 INFO mapred.JobClient:  map 0% reduce 0%

I have the following dependencies in my project:

<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-client</artifactId>
    <version>2.6.0-mr1-cdh5.8.3</version>
    <scope>provided</scope>
</dependency>

<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-core</artifactId>
    <version>2.6.0-mr1-cdh5.8.3</version>
</dependency>

<dependency>
    <groupId>org.apache.avro</groupId>
    <artifactId>avro</artifactId>
    <version>1.7.6-cdh5.8.3</version>
</dependency>

<dependency>
    <groupId>org.apache.avro</groupId>
    <artifactId>avro-mapred</artifactId>
    <version>1.7.6-cdh5.8.3</version>
</dependency>

And could not find org.apache.avro.hadoop package under the project dependency. Am I missing any dependencies?

Thank you.


问:
Floating DIV giving precedent on resize
I am new to CSS and just graduating from Tables. I am not even sure how to phrase this title. I am struggling with how CSS works and how things are handled. I have made a layout and page that I am currently happy with. Because of the content on the page its likely that the users will resize the page. column left and right are not nearly as important as the middle column. For ease of use its best to be on top.

My page layout at normal size is:

```<code>--------------------
|-------------------|
||    |       |    ||
||    |       |    ||
||Left|  Mid  |Right|
||    |       |    ||
||    |       |    ||
||    |       |    ||
|------------------||
|__________________||
</code>```

When I resize smaller it becomes the layout shifts:

```<code>----------------
|--------------|
||    |       ||
||    |       ||
||Left| Right ||
||    |       ||
||    |       ||
||    |       ||
|--------------|
|     Mid      |
|______________|
</code>```

I would like is middle to always be the top:

```<code>----------------
|--------------|
||            ||
||    Mid     ||
||            ||
||            ||
||            ||
||            ||
|--------------|
| Others       |
|              |
|______________|
</code>```

My CSS:

```<code>#page-wrap {
position: left;
display: inline-block;
}

#left {
width: 239px;
height: 711px;
float: left;
}

#mid {
width: 600px;
height: 600px;
float: left;
margin-left: 5px;
}

#right {
width: fit-content;
height: 300px;
margin-left: 5px;
float: right;
}
</code>```

My webpage is layout:

```<code><div class="container">
    <div id="page-wrap">
        <div id="left"></div>
        <div id="right"></div>
        <div id="mid"></div>
    </div>
</div>
</code>```

How can I get my page to behave properly?

答:
If you can, I would recommend using flexbox instead of floats for layout.

You can read a good introduction to flexbox here.

The snippet below is how you might approach your layout using flexbox. I have changed your HTML so that the mid content appears first. We can use the order property to move the layout around on resize.

You can change the em units to pixels if you need.

jsfiddle

#page-wrap {
  display: flex;
  background: lightblue;
}

#mid {
  flex: 1 1 40em;
}

#left {
  flex: 0 1 15em;
  order: -1;
}

#right {
  flex: 0 1 15em;
}

/* specificy when you want the layout to change */

@media (max-width: 800px) {
  #page-wrap {
    flex-direction: column;
  }
  #left {
    order: 0;
  }
}

/* styling for demo */

#left,
#mid,
#right {
  border: 1px solid white;
  font-family: sans-serif;
  font-size: 2em;
  height: 600px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div id="page-wrap">
    <div id="mid">middle content</div>
    <div id="left">left sidebar</div>
    <div id="right">right sidebar</div>
  </div>
</div></code>```

Title: Floating DIV giving precedent on resize

Body:
I am new to CSS and just graduating from Tables. I am not even sure how to phrase this title. I am struggling with how CSS works and how things are handled. I have made a layout and page that I am currently happy with. Because of the content on the page its likely that the users will resize the page. column left and right are not nearly as important as the middle column. For ease of use its best to be on top.

My page layout at normal size is:

--------------------
|-------------------|
||    |       |    ||
||    |       |    ||
||Left|  Mid  |Right|
||    |       |    ||
||    |       |    ||
||    |       |    ||
|------------------||
|__________________||

When I resize smaller it becomes the layout shifts:

----------------
|--------------|
||    |       ||
||    |       ||
||Left| Right ||
||    |       ||
||    |       ||
||    |       ||
|--------------|
|     Mid      |
|______________|

I would like is middle to always be the top:

----------------
|--------------|
||            ||
||    Mid     ||
||            ||
||            ||
||            ||
||            ||
|--------------|
| Others       |
|              |
|______________|

My CSS:

#page-wrap {
position: left;
display: inline-block;
}

#left {
width: 239px;
height: 711px;
float: left;
}

#mid {
width: 600px;
height: 600px;
float: left;
margin-left: 5px;
}

#right {
width: fit-content;
height: 300px;
margin-left: 5px;
float: right;
}

My webpage is layout:

How can I get my page to behave properly?

Body:
If you can, I would recommend using flexbox instead of floats for layout.

You can read a good introduction to flexbox here.

The snippet below is how you might approach your layout using flexbox. I have changed your HTML so that the mid content appears first. We can use the order property to move the layout around on resize.

You can change the em units to pixels if you need.

jsfiddle

#page-wrap {
  display: flex;
  background: lightblue;
}

#mid {
  flex: 1 1 40em;
}

#left {
  flex: 0 1 15em;
  order: -1;
}

#right {
  flex: 0 1 15em;
}

/* specificy when you want the layout to change */

@media (max-width: 800px) {
  #page-wrap {
    flex-direction: column;
  }
  #left {
    order: 0;
  }
}

/* styling for demo */

#left,
#mid,
#right {
  border: 1px solid white;
  font-family: sans-serif;
  font-size: 2em;
  height: 600px;
}

<div class="container">
  <div id="page-wrap">
    <div id="mid">middle content</div>
    <div id="left">left sidebar</div>
    <div id="right">right sidebar</div>
  </div>
</div>


问:
Fill comboBox with SELECT results
I want to populate a combo box with the results of a SELECT query.

It shows rows in the combobox but all are : System.Data.DataRow

The results of the SELECT is stored in a datatable.

```<code>string ChaineDeSelction = "SELECT fir_mdnt FROM -- WHERE fir_aktiv = 1 AND EXISTS(select firbpv_fir from --)";
        OdbcConnection MyConnec = new OdbcConnection(MyConnString);
        MyConnec.Open();
        OdbcCommand MyComm = new OdbcCommand(ChaineDeSelction, MyConnec);
        DataTable.Load(MyComm.ExecuteReader());

        _cb_Societe.DataSource = DataTable; <--- I tried this way the the foreach .Add way but both return the same.

        foreach(DataRow Ligne in DataTable.Rows)
        {
            _cb_Societe.Items.Add(Ligne);
        }
</code>```

I also have a DataGridView filled with the same

Any suggestions ?

答:
You need to specify which field you want to display using DisplayMember Property and not the whole row as you have done. And you need to save to a DataTable your Reader.

```<code>  DataTable dt = new DataTable();
  dt.Load(MyComm.ExecuteReader());
 _cb_Societe.DataSource = dt;
 _cb_Societe.DisplayMember = "fir_mdnt";
</code>```

Title: Fill comboBox with SELECT results

Body:
I want to populate a combo box with the results of a SELECT query.

It shows rows in the combobox but all are : System.Data.DataRow

The results of the SELECT is stored in a datatable.

string ChaineDeSelction = "SELECT fir_mdnt FROM -- WHERE fir_aktiv = 1 AND EXISTS(select firbpv_fir from --)";
        OdbcConnection MyConnec = new OdbcConnection(MyConnString);
        MyConnec.Open();
        OdbcCommand MyComm = new OdbcCommand(ChaineDeSelction, MyConnec);
        DataTable.Load(MyComm.ExecuteReader());

        _cb_Societe.DataSource = DataTable; <--- I tried this way the the foreach .Add way but both return the same.

        foreach(DataRow Ligne in DataTable.Rows)
        {
            _cb_Societe.Items.Add(Ligne);
        }

I also have a DataGridView filled with the same

Any suggestions ?

Body:
You need to specify which field you want to display using DisplayMember Property and not the whole row as you have done. And you need to save to a DataTable your Reader.

  DataTable dt = new DataTable();
  dt.Load(MyComm.ExecuteReader());
 _cb_Societe.DataSource = dt;
 _cb_Societe.DisplayMember = "fir_mdnt";


问:
Flutter Listview of items as divider with Listview of items Size problems
I have a working page that is a dynamic listview of messages using a Listview.builder. The itembuilder calls a widget that creates the card.  What I am trying to do is change the first list to be a divider that will be a date and then will call a list of items by that date.  All the data calls and lists are being created but keep getting hasSize is not true errors and can not see where the size is a problem, I just used the same layouts that were working.

Not sure what code to show to get some assistance, so let me know if you have ideas and what code you might need to see.

This is the start that worked prior to change:

```<code>var _children = <Widget>[

  new Expanded(
    child: new RefreshIndicator(
      child: new ListView.builder(
        itemBuilder: _divBuilder,
        itemCount: listcount,
      ),
      onRefresh: _onRefresh,
    ),
  ),
  new Stack(
    alignment: Alignment.centerRight,
    children: <Widget>[
      new TextField(
        decoration: const InputDecoration(
          hintText: 'Chat Reply',
          labelText: 'Chat Reply:',
        ),
        autofocus: false,
        focusNode: _focusnode,
        maxLines: 2,
        controller: _newreplycontroller,
        keyboardType: TextInputType.url,
      ),
      new IconButton(
        icon: new Icon(Icons.send),
        onPressed: _sendReply,
        alignment: Alignment.centerRight,
      )
    ],
  ),
];
return new Scaffold(
  appBar: new AppBar(
    title: mytitle,
    actions: getAppBarActions(context),
  ),
  body: new Column(
    mainAxisSize: MainAxisSize.max,
    children: _children,
  ),
);
</code>```

Now I have 2 widgets that are being used.

```<code>    class MyChatWidget extends StatefulWidget {
  MyChatWidget({Key key, this.datediv, this.msgkey}) : super(key: key);

  final DateTime datediv;
  final String msgkey;

  @override
  _MyChatWidgetState createState() => new _MyChatWidgetState();
}

class _MyChatWidgetState extends State<MyChatWidget> {
  List messagelist;
  int messagecount = 0;
  var jsonCodec = const JsonCodec();

  _getMessages() async {
    var _url = 'http://$baseurl/csapi/messages/getbydate';
    DateChatMessage dcm = new DateChatMessage(widget.msgkey, widget.datediv.toString());
    var json = jsonCodec.encode(dcm);
    var http = createHttpClient();
    var response = await http.post(_url, headers: getAuthHeader(), body: json);

    var messages = await jsonCodec.decode(response.body);

    if (mounted) {
      setState(() {
        messagelist = messages.toList();
        messagecount = messagelist.length;
        //replysub = 'Re: ' + chatlist[0]['sub'];
      });
    }
  }

  @override
  void initState() {
    super.initState();
    //controller = new TabController(length: 4, vsync: this);
    _getMessages();
  }

  @override
  Widget build(BuildContext context) {
    var _children = <Widget>[
      new Divider(height: 5.0,color: Colors.red,),
      new Expanded(
        child: new ListView.builder(
          itemBuilder: _itemBuilder,
          itemCount: messagecount,
        ),
      ),

    ];

    return new Column(
        mainAxisSize: MainAxisSize.min,
        children: _children,
      );
  }

  Widget _itemBuilder(BuildContext context, int index) {
    ChatMessage mychat = getChat(index);
    return new ChatWidget(
      mychat: mychat,
    );
  }

  ChatMessage getChat(int index) {
    //prefs.setInt('pid', myReferralList[index]['pid']);
    return new ChatMessage(
      messagelist[index]['msgkey'],
      messagelist[index]['referralname'],
      messagelist[index]['sub'],
      messagelist[index]['oid'],
      messagelist[index]['oname'],
      messagelist[index]['pid'],
      messagelist[index]['pname'],
      messagelist[index]['sender'],
      messagelist[index]['sendname'],
      messagelist[index]['receiver'],
      messagelist[index]['receivename'],
      messagelist[index]['message'],
      messagelist[index]['submitdate'],
      messagelist[index]['pgrpid'],
      messagelist[index]['prid'],
      messagelist[index]['fcmtoken'],
    );
  }
}

class ChatWidget extends StatefulWidget {
  ChatWidget({Key key, this.mychat}) : super(key: key);

  final ChatMessage mychat;

  @override
  _ChatWidgetState createState() => new _ChatWidgetState();
}

class _ChatWidgetState extends State<ChatWidget> {
  @override
  Widget build(BuildContext context) {
    DateTime submitdate = DateTime.parse(widget.mychat.submitdate).toLocal();

    return new Card(
      child: new Container(
        width: 150.0,
        padding: new EdgeInsets.all(10.0),
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            new Row(
              children: <Widget>[
                new Text(
                  widget.mychat.sendname,
                  style: new TextStyle(
                      fontSize: 15.0, fontWeight: FontWeight.bold),
                ),
                new Text(' @ '),
                new Text(new DateFormat.yMd().add_Hm().format(submitdate)),
                //new Text(submitdate.toLocal().toString())
              ],
            ),

            //new Text(widget.mychat.receivename,style: new TextStyle(fontSize: 15.0, fontWeight: FontWeight.bold),),
            //new Text(new DateFormat.yMd().add_Hm().format(submitdate)),
            new Text('${widget.mychat.message}'),
          ],
        ),
      ),
    );
    /*return new ListTile(
      leading: new CircleAvatar(child: new Text(widget.mychat.oname[0])),
      title: new Text(widget.mychat.referralname),
      subtitle: new Text(new DateFormat.yMd().add_Hm().format(submitdate)),
      trailing: new Text(widget.mychat.sendname),
      onTap: _onTap,
    );*/
  }

void _onTap() {
    Route route = new MaterialPageRoute(
      settings: new RouteSettings(name: "/chats/chatconvodetil"),
      builder: (BuildContext context) =>
      new ChatConvoDetail(mychat: widget.mychat),
    );
    Navigator.of(context).push(route);
  }
}
</code>```

Any guidance would be great

Full Error Stack

```<code>══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY

╞═════════════════════════════════════════════════════════
RenderFlex children have non-zero flex but incoming height constraints are unbounded.
When a column is in a parent that does not provide a finite height constraint, for example if it is
in a vertical scrollable, it will try to shrink-wrap its children along the vertical axis. Setting a
space in the vertical direction.
These two directives are mutually exclusive. If a parent is to shrink-wrap its child, the child
cannot simultaneously expand to fit its parent.
Consider setting mainAxisSize to MainAxisSize.min and using FlexFit.loose fits for the flexible
themselves to less than the infinite remaining space they would otherwise be forced to take, and
then will cause the RenderFlex to shrink-wrap the children rather than expanding to fit the maximum
constraints provided by the parent.
The affected RenderFlex is:
RenderFlex#d88d8 relayoutBoundary=up8 NEEDS-LAYOUT NEEDS-PAINT
The creator information is set to:
Column ← MyChatWidget ← RepaintBoundary-[<0>] ← NotificationListener<KeepAliveNotification> ←
KeepAlive ← AutomaticKeepAlive ← SliverList ← ShrinkWrappingViewport ← _ScrollableScope ←
IgnorePointer-[GlobalKey#ac8f6] ← Listener ← _GestureSemantics ← ⋯
See also: https://flutter.io/layout/
https://flutter.io/debugging/#rendering-layer
http://docs.flutter.io/flutter/rendering/debugDumpRenderTree.html
If none of the above helps enough to fix this problem, please don't hesitate to file a bug:
https://github.com/flutter/flutter/issues/new

When the exception was thrown, this was the stack:

The following RenderObject was being processed when the exception was fired:
RenderFlex#d88d8 relayoutBoundary=up8 NEEDS-LAYOUT NEEDS-PAINT
creator: Column ← MyChatWidget ← RepaintBoundary-[<0>] ←
NotificationListener<KeepAliveNotification> ← KeepAlive ← AutomaticKeepAlive ← SliverList ←
ShrinkWrappingViewport ← _ScrollableScope ← IgnorePointer-[GlobalKey#ac8f6] ← Listener ←
_GestureSemantics ← ⋯
size: MISSING
direction: vertical
mainAxisAlignment: start
mainAxisSize: min
crossAxisAlignment: center
verticalDirection: down
RenderConstrainedBox#1d682 relayoutBoundary=up9 NEEDS-PAINT
RenderPositionedBox#d9c42 relayoutBoundary=up10 NEEDS-PAINT
RenderPadding#c357c relayoutBoundary=up11 NEEDS-PAINT
RenderConstrainedBox#3ad51 relayoutBoundary=up12 NEEDS-PAINT
RenderDecoratedBox#e68e0 relayoutBoundary=up13 NEEDS-PAINT
RenderSemanticsGestureHandler#83b48 NEEDS-LAYOUT NEEDS-PAINT
RenderPointerListener#9b129 NEEDS-LAYOUT NEEDS-PAINT
RenderIgnorePointer#aa9c2 NEEDS-LAYOUT NEEDS-PAINT
RenderShrinkWrappingViewport#f658c NEEDS-LAYOUT NEEDS-PAINT
RenderSliverList#7b88e NEEDS-LAYOUT NEEDS-PAINT
════════════════════════════════════════════════════════════════════════════════════════════════════
Another exception was thrown: 'package:flutter/src/rendering/box.dart': Failed assertion: line 1433 pos 12: 'hasSize': is not true.
Another exception was thrown: 'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 455 pos 12: 'child.hasSize': is not true.
</code>```

答: Use Flexible instead of Expanded.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have a working page that is a dynamic listview of messages using a Listview.builder. The itembuilder calls a widget that creates the card.  What I am trying to do is change the first list to be a divider that will be a date and then will call a list of items by that date.  All the data calls and lists are being created but keep getting hasSize is not true errors and can not see where the size is a problem, I just used the same layouts that were working.

Not sure what code to show to get some assistance, so let me know if you have ideas and what code you might need to see.

This is the start that worked prior to change:

var _children = <Widget>[

  new Expanded(
    child: new RefreshIndicator(
      child: new ListView.builder(
        itemBuilder: _divBuilder,
        itemCount: listcount,
      ),
      onRefresh: _onRefresh,
    ),
  ),
  new Stack(
    alignment: Alignment.centerRight,
    children: <Widget>[
      new TextField(
        decoration: const InputDecoration(
          hintText: 'Chat Reply',
          labelText: 'Chat Reply:',
        ),
        autofocus: false,
        focusNode: _focusnode,
        maxLines: 2,
        controller: _newreplycontroller,
        keyboardType: TextInputType.url,
      ),
      new IconButton(
        icon: new Icon(Icons.send),
        onPressed: _sendReply,
        alignment: Alignment.centerRight,
      )
    ],
  ),
];
return new Scaffold(
  appBar: new AppBar(
    title: mytitle,
    actions: getAppBarActions(context),
  ),
  body: new Column(
    mainAxisSize: MainAxisSize.max,
    children: _children,
  ),
);

Now I have 2 widgets that are being used.

    class MyChatWidget extends StatefulWidget {
  MyChatWidget({Key key, this.datediv, this.msgkey}) : super(key: key);

  final DateTime datediv;
  final String msgkey;

  @override
  _MyChatWidgetState createState() => new _MyChatWidgetState();
}

class _MyChatWidgetState extends State<MyChatWidget> {
  List messagelist;
  int messagecount = 0;
  var jsonCodec = const JsonCodec();

  _getMessages() async {
    var _url = 'http://$baseurl/csapi/messages/getbydate';
    DateChatMessage dcm = new DateChatMessage(widget.msgkey, widget.datediv.toString());
    var json = jsonCodec.encode(dcm);
    var http = createHttpClient();
    var response = await http.post(_url, headers: getAuthHeader(), body: json);

    var messages = await jsonCodec.decode(response.body);

    if (mounted) {
      setState(() {
        messagelist = messages.toList();
        messagecount = messagelist.length;
        //replysub = 'Re: ' + chatlist[0]['sub'];
      });
    }
  }

  @override
  void initState() {
    super.initState();
    //controller = new TabController(length: 4, vsync: this);
    _getMessages();
  }

  @override
  Widget build(BuildContext context) {
    var _children = <Widget>[
      new Divider(height: 5.0,color: Colors.red,),
      new Expanded(
        child: new ListView.builder(
          itemBuilder: _itemBuilder,
          itemCount: messagecount,
        ),
      ),

    ];

    return new Column(
        mainAxisSize: MainAxisSize.min,
        children: _children,
      );
  }

  Widget _itemBuilder(BuildContext context, int index) {
    ChatMessage mychat = getChat(index);
    return new ChatWidget(
      mychat: mychat,
    );
  }

  ChatMessage getChat(int index) {
    //prefs.setInt('pid', myReferralList[index]['pid']);
    return new ChatMessage(
      messagelist[index]['msgkey'],
      messagelist[index]['referralname'],
      messagelist[index]['sub'],
      messagelist[index]['oid'],
      messagelist[index]['oname'],
      messagelist[index]['pid'],
      messagelist[index]['pname'],
      messagelist[index]['sender'],
      messagelist[index]['sendname'],
      messagelist[index]['receiver'],
      messagelist[index]['receivename'],
      messagelist[index]['message'],
      messagelist[index]['submitdate'],
      messagelist[index]['pgrpid'],
      messagelist[index]['prid'],
      messagelist[index]['fcmtoken'],
    );
  }
}

class ChatWidget extends StatefulWidget {
  ChatWidget({Key key, this.mychat}) : super(key: key);

  final ChatMessage mychat;

  @override
  _ChatWidgetState createState() => new _ChatWidgetState();
}

class _ChatWidgetState extends State<ChatWidget> {
  @override
  Widget build(BuildContext context) {
    DateTime submitdate = DateTime.parse(widget.mychat.submitdate).toLocal();

    return new Card(
      child: new Container(
        width: 150.0,
        padding: new EdgeInsets.all(10.0),
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            new Row(
              children: <Widget>[
                new Text(
                  widget.mychat.sendname,
                  style: new TextStyle(
                      fontSize: 15.0, fontWeight: FontWeight.bold),
                ),
                new Text(' @ '),
                new Text(new DateFormat.yMd().add_Hm().format(submitdate)),
                //new Text(submitdate.toLocal().toString())
              ],
            ),

            //new Text(widget.mychat.receivename,style: new TextStyle(fontSize: 15.0, fontWeight: FontWeight.bold),),
            //new Text(new DateFormat.yMd().add_Hm().format(submitdate)),
            new Text('${widget.mychat.message}'),
          ],
        ),
      ),
    );
    /*return new ListTile(
      leading: new CircleAvatar(child: new Text(widget.mychat.oname[0])),
      title: new Text(widget.mychat.referralname),
      subtitle: new Text(new DateFormat.yMd().add_Hm().format(submitdate)),
      trailing: new Text(widget.mychat.sendname),
      onTap: _onTap,
    );*/
  }

void _onTap() {
    Route route = new MaterialPageRoute(
      settings: new RouteSettings(name: "/chats/chatconvodetil"),
      builder: (BuildContext context) =>
      new ChatConvoDetail(mychat: widget.mychat),
    );
    Navigator.of(context).push(route);
  }
}

Any guidance would be great

Full Error Stack

══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY

╞═════════════════════════════════════════════════════════
RenderFlex children have non-zero flex but incoming height constraints are unbounded.
When a column is in a parent that does not provide a finite height constraint, for example if it is
in a vertical scrollable, it will try to shrink-wrap its children along the vertical axis. Setting a
space in the vertical direction.
These two directives are mutually exclusive. If a parent is to shrink-wrap its child, the child
cannot simultaneously expand to fit its parent.
Consider setting mainAxisSize to MainAxisSize.min and using FlexFit.loose fits for the flexible
themselves to less than the infinite remaining space they would otherwise be forced to take, and
then will cause the RenderFlex to shrink-wrap the children rather than expanding to fit the maximum
constraints provided by the parent.
The affected RenderFlex is:
RenderFlex#d88d8 relayoutBoundary=up8 NEEDS-LAYOUT NEEDS-PAINT
The creator information is set to:
Column ← MyChatWidget ← RepaintBoundary-[<0>] ← NotificationListener<KeepAliveNotification> ←
KeepAlive ← AutomaticKeepAlive ← SliverList ← ShrinkWrappingViewport ← _ScrollableScope ←
IgnorePointer-[GlobalKey#ac8f6] ← Listener ← _GestureSemantics ← ⋯
See also: https://flutter.io/layout/
https://flutter.io/debugging/#rendering-layer
http://docs.flutter.io/flutter/rendering/debugDumpRenderTree.html
If none of the above helps enough to fix this problem, please don't hesitate to file a bug:
https://github.com/flutter/flutter/issues/new

When the exception was thrown, this was the stack:

The following RenderObject was being processed when the exception was fired:
RenderFlex#d88d8 relayoutBoundary=up8 NEEDS-LAYOUT NEEDS-PAINT
creator: Column ← MyChatWidget ← RepaintBoundary-[<0>] ←
NotificationListener<KeepAliveNotification> ← KeepAlive ← AutomaticKeepAlive ← SliverList ←
ShrinkWrappingViewport ← _ScrollableScope ← IgnorePointer-[GlobalKey#ac8f6] ← Listener ←
_GestureSemantics ← ⋯
size: MISSING
direction: vertical
mainAxisAlignment: start
mainAxisSize: min
crossAxisAlignment: center
verticalDirection: down
RenderConstrainedBox#1d682 relayoutBoundary=up9 NEEDS-PAINT
RenderPositionedBox#d9c42 relayoutBoundary=up10 NEEDS-PAINT
RenderPadding#c357c relayoutBoundary=up11 NEEDS-PAINT
RenderConstrainedBox#3ad51 relayoutBoundary=up12 NEEDS-PAINT
RenderDecoratedBox#e68e0 relayoutBoundary=up13 NEEDS-PAINT
RenderSemanticsGestureHandler#83b48 NEEDS-LAYOUT NEEDS-PAINT
RenderPointerListener#9b129 NEEDS-LAYOUT NEEDS-PAINT
RenderIgnorePointer#aa9c2 NEEDS-LAYOUT NEEDS-PAINT
RenderShrinkWrappingViewport#f658c NEEDS-LAYOUT NEEDS-PAINT
RenderSliverList#7b88e NEEDS-LAYOUT NEEDS-PAINT
════════════════════════════════════════════════════════════════════════════════════════════════════
Another exception was thrown: 'package:flutter/src/rendering/box.dart': Failed assertion: line 1433 pos 12: 'hasSize': is not true.
Another exception was thrown: 'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 455 pos 12: 'child.hasSize': is not true.

Body: Use Flexible instead of Expanded.


问:
cmake - preset settings for entries from ini file
I have a project that uses some third party libraries. So each time I setup this project with CMake, I have to set each entry (path of the third party library) on the GUI of CMake. I improve this by making CMake script guess the path by this script (learn this technique from OGRE):

```<code># Guess the paths.
set( OGRE_SOURCE "${CMAKE_CURRENT_SOURCE_DIR}/Dependencies/Ogre" CACHE STRING "Path to OGRE source code (see http://www.ogre3d.org/tikiwiki/tiki-index.php?page=CMake+Quick+Start+Guide)" )
</code>```

So each time I setup with CMake, it will automatic fill the entry OGRE_SOURCE. But that doesn't enough. If the Ogre source is not in the path

```<code>"${CMAKE_CURRENT_SOURCE_DIR}/Dependencies/Ogre"
</code>```

, then I have to open and edit the CMake script or I have to edit the entry on the GUI of CMake. I find that pretty inconvenient, especially when you link to a lot of third party libraries.

So I want to use another technique: preset settings for entries from file - CMake reads the presets from file PresetEntries.txt (that I make) and apply the these presets on the entries (It's a lot quicker to edit the path in text file than on the GUI of CMake).

Here my idea about this preset file: PresetEntries.txt

```<code>OGRE_SOURCE=E:/Source/ogre
</code>```

I found that CMake can read a text file, but if I use this, I have to do string manipulations.

CMake has the file CMakeCache.txt to save the settings on the CMake GUI, but I want it to be simple: it should only has the preset settings that need to be pre-set.

So I wonder if CMake support this preset settings for entries from file.

Edit:
So I read this question and see that CMake can set config from file, but this require to fire cmake with the -C mysettings.cmake, but I wanna it to be automatically with CMake GUI - just edit the file and hit generate button in CMake GUI. So I wanna make this question more specific:
In my CMakeLists.txt should have script like this:

```<code># Guess the paths.
#I wanna have this function from C++
#https://msdn.microsoft.com/en-us/library/windows/desktop/ms724353%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
GetPrivateProfileString("OGRE",         #lpAppName
                        "OGRE_SOURCE",  #lpKeyName
                        "${CMAKE_CURRENT_SOURCE_DIR}/Dependencies/Ogre", #lpDefault
                        OGRE_SOURCE_VAR,#lpReturnedString
                        MAX_PATH,       #nSize, may be can reduce this variable
                        "LibPath.ini")  #lpFileName

set( OGRE_SOURCE "${OGRE_SOURCE_VAR}" CACHE STRING "Path to OGRE source code" )
</code>```

In the file LibPath.ini

```<code>[OGRE]
OGRE_SOURCE = "E:/Source/ogre"
</code>```

So the user can choose to either use the ini file or not.

I don't know if there any way I can use a function that similar to function GetPrivateProfileString (of C++) in CMake.

Thanks for reading

答:
I can't find the function to read the ini file, so what I can do is create a simple function that read simple txt file for myself.

I declare the function in 1 file for other file use it

"\CMake\Dependencies\CommonFunc.cmake"

```<code>#------------Define function Read file------------
macro( readSettingFile KEY DEFAULT_RESULT STRING_RESULT_OUT)

    unset(STRING_RESULT)
    # Read the file
    file( READ "${CMAKE_SOURCE_DIR}/LibPath.txt" LIB_PATH_STR )

    # Set the variable "Esc" to the ASCII value 27 - basically something
    # which is unlikely to conflict with anything in the file contents.
    string(ASCII 27 Esc)

    # Turn the contents into a list of strings, each ending with an Esc.
    # This allows us to preserve blank lines in the file since CMake
    # automatically prunes empty list items during a foreach loop.
    string(REGEX REPLACE "\n" "${Esc};" LIB_PATH_LINES "${LIB_PATH_STR}")

    foreach(LINE ${LIB_PATH_LINES})
        if("${LINE}" MATCHES "${KEY}")
            #remove the key, leave the content untouch
            string(REPLACE "${KEY}" "" STRING_RESULT ${LINE})
            # Swap the appended Esc character back out in favour of a line feed
            string(REGEX REPLACE "${Esc}" "" STRING_RESULT ${STRING_RESULT})
        endif()
    endforeach()

    if("${STRING_RESULT}" STREQUAL "")
        set( STRING_RESULT ${DEFAULT_RESULT} )
    endif()

    #message( STATIC "---GTA Sa-----" "[${STRING_RESULT}]" )
endmacro()
</code>```

(I need the help from this answer to write this function :p)

Here is how I use

For example: "\CMake\Dependencies\Ogre.cmake"

```<code>#include common functions
include( CMake/Dependencies/CommonFunc.cmake )
#---------------Guess the paths.----------------------
#----Set OGRE_SOURCE
readSettingFile(    "OGRE_SOURCE="
                    "E:/Source/ogre"
                    STRING_RESULT
                )
set( OGRE_SOURCE "${STRING_RESULT}" CACHE STRING "Path to OGRE Source" )
#----Set OGRE_BINARIES
readSettingFile(    "OGRE_BINARIES="
                    "E:/Source/_build/ogre"
                    STRING_RESULT
                )
set( OGRE_BINARIES "${STRING_RESULT}" CACHE STRING "Path to OGRE's build folder generated by CMake" )
</code>```

Here is the setting file

"\LibPath.txt"

```<code>OGRE_SOURCE=E:/Source/ogre
OGRE_BINARIES=E:/Source/_build/ogre
</code>```

Body:
I have a project that uses some third party libraries. So each time I setup this project with CMake, I have to set each entry (path of the third party library) on the GUI of CMake. I improve this by making CMake script guess the path by this script (learn this technique from OGRE):

# Guess the paths.
set( OGRE_SOURCE "${CMAKE_CURRENT_SOURCE_DIR}/Dependencies/Ogre" CACHE STRING "Path to OGRE source code (see http://www.ogre3d.org/tikiwiki/tiki-index.php?page=CMake+Quick+Start+Guide)" )

So each time I setup with CMake, it will automatic fill the entry OGRE_SOURCE. But that doesn't enough. If the Ogre source is not in the path

"${CMAKE_CURRENT_SOURCE_DIR}/Dependencies/Ogre"

, then I have to open and edit the CMake script or I have to edit the entry on the GUI of CMake. I find that pretty inconvenient, especially when you link to a lot of third party libraries.

So I want to use another technique: preset settings for entries from file - CMake reads the presets from file PresetEntries.txt (that I make) and apply the these presets on the entries (It's a lot quicker to edit the path in text file than on the GUI of CMake).

Here my idea about this preset file: PresetEntries.txt

OGRE_SOURCE=E:/Source/ogre

I found that CMake can read a text file, but if I use this, I have to do string manipulations.

CMake has the file CMakeCache.txt to save the settings on the CMake GUI, but I want it to be simple: it should only has the preset settings that need to be pre-set.

So I wonder if CMake support this preset settings for entries from file.

Edit:
So I read this question and see that CMake can set config from file, but this require to fire cmake with the -C mysettings.cmake, but I wanna it to be automatically with CMake GUI - just edit the file and hit generate button in CMake GUI. So I wanna make this question more specific:
In my CMakeLists.txt should have script like this:

# Guess the paths.
#I wanna have this function from C++
#https://msdn.microsoft.com/en-us/library/windows/desktop/ms724353%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
GetPrivateProfileString("OGRE",         #lpAppName
                        "OGRE_SOURCE",  #lpKeyName
                        "${CMAKE_CURRENT_SOURCE_DIR}/Dependencies/Ogre", #lpDefault
                        OGRE_SOURCE_VAR,#lpReturnedString
                        MAX_PATH,       #nSize, may be can reduce this variable
                        "LibPath.ini")  #lpFileName

set( OGRE_SOURCE "${OGRE_SOURCE_VAR}" CACHE STRING "Path to OGRE source code" )

In the file LibPath.ini

[OGRE]
OGRE_SOURCE = "E:/Source/ogre"

So the user can choose to either use the ini file or not.

I don't know if there any way I can use a function that similar to function GetPrivateProfileString (of C++) in CMake.

Thanks for reading

Body:
I can't find the function to read the ini file, so what I can do is create a simple function that read simple txt file for myself.

I declare the function in 1 file for other file use it

"\CMake\Dependencies\CommonFunc.cmake"

#------------Define function Read file------------
macro( readSettingFile KEY DEFAULT_RESULT STRING_RESULT_OUT)

    unset(STRING_RESULT)
    # Read the file
    file( READ "${CMAKE_SOURCE_DIR}/LibPath.txt" LIB_PATH_STR )

    # Set the variable "Esc" to the ASCII value 27 - basically something
    # which is unlikely to conflict with anything in the file contents.
    string(ASCII 27 Esc)

    # Turn the contents into a list of strings, each ending with an Esc.
    # This allows us to preserve blank lines in the file since CMake
    # automatically prunes empty list items during a foreach loop.
    string(REGEX REPLACE "\n" "${Esc};" LIB_PATH_LINES "${LIB_PATH_STR}")

    foreach(LINE ${LIB_PATH_LINES})
        if("${LINE}" MATCHES "${KEY}")
            #remove the key, leave the content untouch
            string(REPLACE "${KEY}" "" STRING_RESULT ${LINE})
            # Swap the appended Esc character back out in favour of a line feed
            string(REGEX REPLACE "${Esc}" "" STRING_RESULT ${STRING_RESULT})
        endif()
    endforeach()

    if("${STRING_RESULT}" STREQUAL "")
        set( STRING_RESULT ${DEFAULT_RESULT} )
    endif()

    #message( STATIC "---GTA Sa-----" "[${STRING_RESULT}]" )
endmacro()

(I need the help from this answer to write this function :p)

Here is how I use

For example: "\CMake\Dependencies\Ogre.cmake"

#include common functions
include( CMake/Dependencies/CommonFunc.cmake )
#---------------Guess the paths.----------------------
#----Set OGRE_SOURCE
readSettingFile(    "OGRE_SOURCE="
                    "E:/Source/ogre"
                    STRING_RESULT
                )
set( OGRE_SOURCE "${STRING_RESULT}" CACHE STRING "Path to OGRE Source" )
#----Set OGRE_BINARIES
readSettingFile(    "OGRE_BINARIES="
                    "E:/Source/_build/ogre"
                    STRING_RESULT
                )
set( OGRE_BINARIES "${STRING_RESULT}" CACHE STRING "Path to OGRE's build folder generated by CMake" )

Here is the setting file

"\LibPath.txt"

OGRE_SOURCE=E:/Source/ogre
OGRE_BINARIES=E:/Source/_build/ogre


问:
JSON encode to table
I want to show JSON array into table,
my db table structure consist: act_id, sales_id, cust_name, act_type, notes, date_add, date_modified, action.

here are the scripts (/api.php):

```<code>public function get_todo($id = null)
{
    $this->_require_login();

    if ($id != null){
        $this->db->where([
            'act_id' => $id,
            'user_id' => $this->session->userdata('user_id')
        ]);
    } else {
        $this->db->where('user_id', $this->session->userdata('user_id'));
    }
    $this->db->where('user_id', $this->session->userdata('user_id'));
    $query = $this->db->get('activity');
    $result = $query->result_array();

    $this->output->set_output(json_encode($result));
}
</code>```

my event.js

```<code>var load_todo = function() {
    $.get('api/get_todo', function(o){

        var output = '';
        for (var i = 0; i < o.length; i++){
            output += Template.todo(o[i]);
        }

        $("#list_todo").html(output);
    }, 'json');
};
</code>```

this is my template.js

```<code>output +='<table style="width:80%;">';
    output +='<thead>';
    output += '<tr>';
    output +='<th>' + "Client Name" + '</th>';
    output +='<th>' + "Activity" + '</th>';
    output +='<th>' + "Notes" + '</th>';
    output +='<th>' + "Start" + '</th>';
    output +='<th>' + "Finish" + '</th>';
    output +='<th>' + "Action" + '</th>';
    output +='</tr>';
    output += '</thead>';

    output +='<tbody>';
    output += '<tr>'
    output +='<td>' + obj.cust_name + '</td>';
    output +='<td>' + obj.act_type + '</td>';
    output +='<td>' + obj.act_notes + '</td>';
    output +='<td>' + obj.date_added +'</td>';
    output +='<td>' + obj.date_modified + '</td>';
output += '<td>' + '<a class="todo_update" data-id="' + obj.act_id + '"data-completed="' + data_completed + '" href="api/update_todo">' + data_completed_text + '</a>' + '</td>';
    output += '</tr>';
    output +='</tbody>'; output +='</table>';
</code>```

however it creates duplicate column name in each rows view

any help would really appreciated. thank you.

答: Keep the header part of the table out of the loop. My advice is to split the program in two halves first, encode the header part, see it's output and then encode the rest of the data and then join as you require.</p>

Title: JSON encode to table

Body:
I want to show JSON array into table,
my db table structure consist: act_id, sales_id, cust_name, act_type, notes, date_add, date_modified, action.

here are the scripts (/api.php):

public function get_todo($id = null)
{
    $this->_require_login();

    if ($id != null){
        $this->db->where([
            'act_id' => $id,
            'user_id' => $this->session->userdata('user_id')
        ]);
    } else {
        $this->db->where('user_id', $this->session->userdata('user_id'));
    }
    $this->db->where('user_id', $this->session->userdata('user_id'));
    $query = $this->db->get('activity');
    $result = $query->result_array();

    $this->output->set_output(json_encode($result));
}

my event.js

var load_todo = function() {
    $.get('api/get_todo', function(o){

        var output = '';
        for (var i = 0; i < o.length; i++){
            output += Template.todo(o[i]);
        }

        $("#list_todo").html(output);
    }, 'json');
};

this is my template.js

output +='
';
    output +='
';
    output += '
';
    output +='' + "Client Name" + '	';
    output +='' + "Activity" + '	';
    output +='' + "Notes" + '	';
    output +='' + "Start" + '	';
    output +='' + "Finish" + '	';
    output +='' + "Action" + '	';
    output +='
';
    output += '
';

    output +='
';
    output += '
'
    output +='' + obj.cust_name + '	';
    output +='' + obj.act_type + '	';
    output +='' + obj.act_notes + '	';
    output +='' + obj.date_added +'	';
    output +='' + obj.date_modified + '	';
output += '' + '' + data_completed_text + '' + '	';
    output += '
';
    output +='
'; output +='
';

however it creates duplicate column name in each rows view

any help would really appreciated. thank you.


问:
Unable to send ajax response to the controller in yii2
I have a view in which I have a detailview and a gridview. In my gridview I have a checkbox. And on clicking on any check box I am able to get the id of the column(s) selected. Below is my view

```<code>//my DetailView
?= GridView::widget([
         'dataProvider' => $dataProvider,
          /*'filterModel' => $searchModel,*/

          'columns' => [

         ['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
             return ['value' => $d['meter_id']];
         }],

         'Meter_Serial_Number',
         'Issued_To',
         'Store',
       ],
]); ?>
<a href="<?= URL::toRoute(['ogpheader/viewsetpdf', 'id'=>$model->id])?>" name="redirect" class="btn btn-primary" id="myid">Set PDF</a>
</code>```

UI

Note:

The detail view is coming from the model and gridview is generated from query to view and then select the data.

Now I have placed an ajax call that will send the data to the controller.

```<code><?php
$url = Url::toRoute(['/ogpheader/viewsetpdf']);
$script = <<< JS
$(document).ready(function () {

$('#myid').click(function() {
 var strValue = "";

    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!="")
        {
        strValue = strValue + " , " + this.value;

        }
    else
        strValue = this.value;

});
$.ajax({
     url: '$url',
     data: {
           data: strValue,
     },
     type: 'post',
     dataType: 'json',
     success: function(data) {
        alert(data);
     },
  });
 })
});

JS;
$this->registerJs($script, static::POS_END);
?>
</code>```

Action Controller

```<code> public function actionViewsetpdf($id)
{
    $model = $this->findModel($id);
    print_r($model);
    $data = "";
    if(isset($_POST['data']))
    {
        $data = json_decode($_POST['data']);
        print_r($data);
    }
    else{
        echo 'no data';
    }
    exit();

}
</code>```

The $id is the id of the model i.e. the id of my detail view. I want to pass both my detail view and grid view selected items to process things forward.

Now when i click on Set PDF button I got the following result

In output image I am getting the details of my model i.e. my detail view items but for my selected grid view items I am getting no data. I have searched for it but unable to find the solution that helps me

Update 1

Changed my JS and ajax call

```<code>$('#myid').on('click',function(e) {
e.preventDefault();
 var strValue = "";
    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!="")
        {
        strValue = strValue + " , " + this.value;

        }
    else
        strValue = this.value;

});
   // alert(strValue);
  $.ajax({
     url: '$url',
     type: 'POST',
     dataType: 'json',
     data: 'data='+ strValue,
     success: function(data) {
        alert(data);
      },
    });
   })
  });
</code>```

The output in my Xhr I am getting is

```<code>common\models\Ogpheader Object( [_attributes:yii\db\BaseActiveRecord:private] => Array ( [id] => 54 [created_by] => 12 [created_at] => 2017-11-13 05:26:04 [updated_at] => [canceled_at] => [store_id] => 10 [status] => Prepared [issuer] => 88 [admin_incharge] => Faisal [project_manager] => Ali ) [_oldAttributes:yii\db\BaseActiveRecord:private] => Array ( [id] => 54 [created_by] => 12 [created_at] => 2017-11-13 05:26:04 [updated_at] => [canceled_at] => [store_id] => 10 [status] => Prepared [issuer] => 88 [admin_incharge] => Faisal [project_manager] => Ali ) [_related:yii\db\BaseActiveRecord:private] => Array ( ) [_errors:yii\base\Model:private] => [_validators:yii\base\Model:private] => [_scenario:yii\base\Model:private] => default [_events:yii\base\Component:private] => Array ( ) [_behaviors:yii\base\Component:private] => Array ( ))array(1) { ["data"]=> string(26) "99 , 100 , 101 , 102 , 103"}
</code>```

But when I remove the e.preventDefault() then the page is redirected to the another view and the response i get is

```<code>common\models\Ogpheader Object( [_attributes:yii\db\BaseActiveRecord:private] => Array ( [id] => 54 [created_by] => 12 [created_at] => 2017-11-13 05:26:04 [updated_at] => [canceled_at] => [store_id] => 10 [status] => Prepared [issuer] => 88 [admin_incharge] => Faisal [project_manager] => Ali ) [_oldAttributes:yii\db\BaseActiveRecord:private] => Array ( [id] => 54 [created_by] => 12 [created_at] => 2017-11-13 05:26:04 [updated_at] => [canceled_at] => [store_id] => 10 [status] => Prepared [issuer] => 88 [admin_incharge] => Faisal [project_manager] => Ali ) [_related:yii\db\BaseActiveRecord:private] => Array ( ) [_errors:yii\base\Model:private] => [_validators:yii\base\Model:private] => [_scenario:yii\base\Model:private] => default [_events:yii\base\Component:private] => Array ( ) [_behaviors:yii\base\Component:private] => Array ( )) no data
</code>```

Any help would be highly appreciated.

答:
you should avoid the quote aroun php var  </p>

```<code>$.ajax({
    url: $url,
    .....
</code>```

Body:
I have a view in which I have a detailview and a gridview. In my gridview I have a checkbox. And on clicking on any check box I am able to get the id of the column(s) selected. Below is my view

//my DetailView
?= GridView::widget([
         'dataProvider' => $dataProvider,
          /*'filterModel' => $searchModel,*/

          'columns' => [

         ['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
             return ['value' => $d['meter_id']];
         }],

         'Meter_Serial_Number',
         'Issued_To',
         'Store',
       ],
]); ?>
<a href="<?= URL::toRoute(['ogpheader/viewsetpdf', 'id'=>$model->id])?>" name="redirect" class="btn btn-primary" id="myid">Set PDF

UI

Note:

The detail view is coming from the model and gridview is generated from query to view and then select the data.

Now I have placed an ajax call that will send the data to the controller.

<?php
$url = Url::toRoute(['/ogpheader/viewsetpdf']);
$script = <<< JS
$(document).ready(function () {

$('#myid').click(function() {
 var strValue = "";

    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!="")
        {
        strValue = strValue + " , " + this.value;

        }
    else
        strValue = this.value;

});
$.ajax({
     url: '$url',
     data: {
           data: strValue,
     },
     type: 'post',
     dataType: 'json',
     success: function(data) {
        alert(data);
     },
  });
 })
});

JS;
$this->registerJs($script, static::POS_END);
?>

Action Controller

 public function actionViewsetpdf($id)
{
    $model = $this->findModel($id);
    print_r($model);
    $data = "";
    if(isset($_POST['data']))
    {
        $data = json_decode($_POST['data']);
        print_r($data);
    }
    else{
        echo 'no data';
    }
    exit();

}

The $id is the id of the model i.e. the id of my detail view. I want to pass both my detail view and grid view selected items to process things forward.

Now when i click on Set PDF button I got the following result

In output image I am getting the details of my model i.e. my detail view items but for my selected grid view items I am getting no data. I have searched for it but unable to find the solution that helps me

Update 1

Changed my JS and ajax call

$('#myid').on('click',function(e) {
e.preventDefault();
 var strValue = "";
    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!="")
        {
        strValue = strValue + " , " + this.value;

        }
    else
        strValue = this.value;

});
   // alert(strValue);
  $.ajax({
     url: '$url',
     type: 'POST',
     dataType: 'json',
     data: 'data='+ strValue,
     success: function(data) {
        alert(data);
      },
    });
   })
  });

The output in my Xhr I am getting is

common\models\Ogpheader Object( [_attributes:yii\db\BaseActiveRecord:private] => Array ( [id] => 54 [created_by] => 12 [created_at] => 2017-11-13 05:26:04 [updated_at] => [canceled_at] => [store_id] => 10 [status] => Prepared [issuer] => 88 [admin_incharge] => Faisal [project_manager] => Ali ) [_oldAttributes:yii\db\BaseActiveRecord:private] => Array ( [id] => 54 [created_by] => 12 [created_at] => 2017-11-13 05:26:04 [updated_at] => [canceled_at] => [store_id] => 10 [status] => Prepared [issuer] => 88 [admin_incharge] => Faisal [project_manager] => Ali ) [_related:yii\db\BaseActiveRecord:private] => Array ( ) [_errors:yii\base\Model:private] => [_validators:yii\base\Model:private] => [_scenario:yii\base\Model:private] => default [_events:yii\base\Component:private] => Array ( ) [_behaviors:yii\base\Component:private] => Array ( ))array(1) { ["data"]=> string(26) "99 , 100 , 101 , 102 , 103"}

But when I remove the e.preventDefault() then the page is redirected to the another view and the response i get is

common\models\Ogpheader Object( [_attributes:yii\db\BaseActiveRecord:private] => Array ( [id] => 54 [created_by] => 12 [created_at] => 2017-11-13 05:26:04 [updated_at] => [canceled_at] => [store_id] => 10 [status] => Prepared [issuer] => 88 [admin_incharge] => Faisal [project_manager] => Ali ) [_oldAttributes:yii\db\BaseActiveRecord:private] => Array ( [id] => 54 [created_by] => 12 [created_at] => 2017-11-13 05:26:04 [updated_at] => [canceled_at] => [store_id] => 10 [status] => Prepared [issuer] => 88 [admin_incharge] => Faisal [project_manager] => Ali ) [_related:yii\db\BaseActiveRecord:private] => Array ( ) [_errors:yii\base\Model:private] => [_validators:yii\base\Model:private] => [_scenario:yii\base\Model:private] => default [_events:yii\base\Component:private] => Array ( ) [_behaviors:yii\base\Component:private] => Array ( )) no data

Any help would be highly appreciated.

Body:
you should avoid the quote aroun php var

$.ajax({
    url: $url,
    .....


问:
Do I need to delete an static std::map?
In some classes I have an static std::map with pointers inside. My question is if I need to delete at the end of the program or this memory is automatically freed. My concern is if the pointers stored inside are correctly deleted through our destructors when std::map is deleted.

Thanks.

答: std::map never calls delete on it's members. Assuming you're working with a relatively recent operating system, the OS will reclaim the memory occupied by the members on process termination, but the destructors will not run.

ContentLicense: CC BY-SA 2.5

Title: Do I need to delete an static std::map?


问:
Node.js and Request.js: Finding the file extension for a download?
I'm trying to download a couple of files using request, but I don't know how to find what their extensions are. Some of them are images, some are sounds, some are videos, but all of them come from a URL with no extension at the end.

```<code>const request = require("request");

request.get({
    url: "http://example.com/unknownextension",
})
.on("error", function(error) {
    console.log(error);
})
.pipe(fs.createWriteStream("files/what.extension"));
</code>```

When you go on this website, it downloads just fine. Think of something like Google Drive links.

I can't open any of these files unless they have a valid extension, so I'd appreciate some help.

答:
The  response from the website should send the type of file through a header , most likely content-disposition or

```<code>content-type

const request = require("request");
request.get({
    url: "http://example.com/unknownextension",
})
.on("error", function(error) {
    console.log(error);
})
.on('response',  function (res) {
  res.pipe(fs.createWriteStream("files/what." + res.headers['content-type'].split('/')[1]));
 // it could also be content-dispostion or any other header, please check the headers first

});
</code>```

Body:
I'm trying to download a couple of files using request, but I don't know how to find what their extensions are. Some of them are images, some are sounds, some are videos, but all of them come from a URL with no extension at the end.

const request = require("request");

request.get({
    url: "http://example.com/unknownextension",
})
.on("error", function(error) {
    console.log(error);
})
.pipe(fs.createWriteStream("files/what.extension"));

When you go on this website, it downloads just fine. Think of something like Google Drive links.

I can't open any of these files unless they have a valid extension, so I'd appreciate some help.

Body:
The  response from the website should send the type of file through a header , most likely content-disposition or

content-type

const request = require("request");
request.get({
    url: "http://example.com/unknownextension",
})
.on("error", function(error) {
    console.log(error);
})
.on('response',  function (res) {
  res.pipe(fs.createWriteStream("files/what." + res.headers['content-type'].split('/')[1]));
 // it could also be content-dispostion or any other header, please check the headers first

});


问:
dataForm jQuery Ajax to PHP
My code does not working correctly, after 3 hours, I don't understand why it isn't working. Can anybody help me out? My goal is to sent over form fields and image to PHP with jQuery. I don't get any respond as XHR. The only thing I see is (Parameters):

```<code>-----------------------------163541139317822
Content-Disposition: form-data; name="staffnumber"

utyu
-----------------------------163541139317822
Content-Disposition: form-data; name="nameperson"

yu
-----------------------------163541139317822
Content-Disposition: form-data; name="fileupload"; filename=""
Content-Type: application/octet-stream

-----------------------------163541139317822--
</code>```

Error in console: SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data.

HTML

```<code><form method="POST" id="formadduser" enctype="multipart/form-data">
    <div id="staffnumber" class="form-group row">
        <label for="staffnumber" class="col-sm-3 col-form-label"><strong>Personeelsnummer</strong> <img src="api/icons/info.svg"></label>
        <div class="col-sm-4">
            <input class="form-control" id="staffnumber" name="staffnumber" value="" type="text">
        </div>
    </div>
    <div id="nameperson" class="form-group row">
        <label for="nameperson" class="col-sm-3 col-form-label"><strong>Naam</strong> <img src="api/icons/info.svg"></label>
        <div class="col-sm-4">
            <input class="form-control" id="nameperson" name="nameperson" value="" type="text">
        </div>
    </div>
    <div id="rowstarttime" class="form-group row">
        <label for="starttime" class="col-sm-3 col-form-label"><strong>Afbeelding</strong></label>
        <div class="col-sm-4">
        <label class="custom-file">
            <input type="file" id="fileupload" class="custom-file-input" name="fileupload">
            <span class="custom-file-control"></span>
        </label>
        </div>
    </div>

  <div class="modal-footer">
  <button id="modaladdusersave" class="btn btn-primary mx-sm-3" type="submit">Opslaan</button>
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Sluiten</button>
</form>
</code>```

jQuery

```<code>$("#formadduser").submit(function(e) {
    e.preventDefault();

    var formData = new FormData(this);
    alert(formData);
    alert('hoi');
    $.ajax({
        ajax_call: "add_user",
        url: '/api/add.php',
        type: 'POST',
        data: formData,
        async: false,
        success: function (data) {
            var data = $.parseJSON( data );
            alert(data)
        },
        cache: false,
        contentType: false,
        processData: false
    });

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

PHP

```<code><?php

require_once('../database.php');

if(isset($_GET['ajax_call']) && $_GET['ajax_call'] == 'add_user') {

$staffnumber = $_GET['staffnumber']; // $_GET['staffnumber'];
$nameperson = $_GET['nameperson']; // $_GET['nameperson'];

$file = $_FILES['fileupload']['tmp_name'];
$targetPath = "upload/".$_FILES['fileupload']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ;    // Moving Uploaded file

// Add record
// $queryNew = 'INSERT INTO Persons (id, name, image) VALUES ("'. $staffnumber .'", "'. $nameperson .'", "test")';
// mysqli_query($conn, $queryNew);

$data = array(
        'staffnumber'   => $staffnumber,
        'nameperson'    => $nameperson,
    );
echo json_encode($data);
exit;

}

?>
</code>```

答:
Use post method instead of get to get record in php file because you are passing data through jquery is in post method,

```<code>if(isset($_GET['ajax_call']) && $_GET['ajax_call'] == 'add_user') {
$staffnumber = $_GET['staffnumber']; // $_GET['staffnumber'];
$nameperson = $_GET['nameperson'];
</code>```

instead of

```<code>if(isset($_POST['ajax_call']) && $_POST['ajax_call'] == 'add_user') {
$staffnumber = $_POST['staffnumber'];
$nameperson = $_POST['nameperson'];
</code>```

And what is move_uploaded_file($sourcePath,$targetPath) source path here??,
you have to pass temp file here move_uploaded_file($_FILES['fileupload']['tmp_name'],$targetPath) ;

Title: dataForm jQuery Ajax to PHP

Body:
My code does not working correctly, after 3 hours, I don't understand why it isn't working. Can anybody help me out? My goal is to sent over form fields and image to PHP with jQuery. I don't get any respond as XHR. The only thing I see is (Parameters):

-----------------------------163541139317822
Content-Disposition: form-data; name="staffnumber"

utyu
-----------------------------163541139317822
Content-Disposition: form-data; name="nameperson"

yu
-----------------------------163541139317822
Content-Disposition: form-data; name="fileupload"; filename=""
Content-Type: application/octet-stream

-----------------------------163541139317822--

Error in console: SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data.

HTML

<form method="POST" id="formadduser" enctype="multipart/form-data">

        Personeelsnummer

            <input class="form-control" id="staffnumber" name="staffnumber" value="" type="text">

        Naam

            <input class="form-control" id="nameperson" name="nameperson" value="" type="text">

        Afbeelding

            <input type="file" id="fileupload" class="custom-file-input" name="fileupload">

  <button id="modaladdusersave" class="btn btn-primary mx-sm-3" type="submit">Opslaan</button>
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Sluiten</button>
</form>

jQuery

$("#formadduser").submit(function(e) {
    e.preventDefault();

    var formData = new FormData(this);
    alert(formData);
    alert('hoi');
    $.ajax({
        ajax_call: "add_user",
        url: '/api/add.php',
        type: 'POST',
        data: formData,
        async: false,
        success: function (data) {
            var data = $.parseJSON( data );
            alert(data)
        },
        cache: false,
        contentType: false,
        processData: false
    });

    return false;
});

PHP

<?php

require_once('../database.php');

if(isset($_GET['ajax_call']) && $_GET['ajax_call'] == 'add_user') {

$staffnumber = $_GET['staffnumber']; // $_GET['staffnumber'];
$nameperson = $_GET['nameperson']; // $_GET['nameperson'];

$file = $_FILES['fileupload']['tmp_name'];
$targetPath = "upload/".$_FILES['fileupload']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ;    // Moving Uploaded file

// Add record
// $queryNew = 'INSERT INTO Persons (id, name, image) VALUES ("'. $staffnumber .'", "'. $nameperson .'", "test")';
// mysqli_query($conn, $queryNew);

$data = array(
        'staffnumber'   => $staffnumber,
        'nameperson'    => $nameperson,
    );
echo json_encode($data);
exit;

}

?>

Body:
Use post method instead of get to get record in php file because you are passing data through jquery is in post method,

if(isset($_GET['ajax_call']) && $_GET['ajax_call'] == 'add_user') {
$staffnumber = $_GET['staffnumber']; // $_GET['staffnumber'];
$nameperson = $_GET['nameperson'];

instead of

if(isset($_POST['ajax_call']) && $_POST['ajax_call'] == 'add_user') {
$staffnumber = $_POST['staffnumber'];
$nameperson = $_POST['nameperson'];

And what is move_uploaded_file($sourcePath,$targetPath) source path here??,
you have to pass temp file here move_uploaded_file($_FILES['fileupload']['tmp_name'],$targetPath) ;


问:
v-model for dynamically generated checkboxes
Here is my fiddle : DEMO

```<code> modules: [{
      moduleName: "Module ABC",
      id: 1,
      actions: [{
        actionName: "addbrand",
        id: 1,
        permissions: [{
          permissionName: "read",
          "id": 1,
          "value": true
        }, {
          permissionName: "write",
          "id": 2,
          "value": true
        }, {
          permissionName: "execute",
          "id": 1,
          "value": false
        }]
}]
</code>```

Checkboxes are dynamically generated iterating over "modules" array in data object. But I am finding it difficult to assign v-model and capture the checked values for the corresponding "action" for its respective "module"'

How do I do this?

```<code><div v-for="module in modules"><b>{{ module.moduleName }}</b>
    <div v-for="action in module.actions">{{ action.actionName }}
      <div v-for="permission in action.permissions">
        <input type="checkbox"> {{ permission.permissionName }}
      </div>
    </div>
    <hr>
  </div>
</code>```

Any help would be much appreciated. Thank you..

答:
I am not sure having nesting more than 2 v-for is a good idea. But you can create an index in v-for as: <p v-for='(foo, index) in array' and use the index to track changes.

In you case you do something like this  https://jsfiddle.net/samayo/az9hge7u/5/

new Vue({
  el: '#app',
  data: {
    modules: [{
      moduleName: "Module ABC",
      id: 1,
      actions: [{
        actionName: "addbrand",
        id: 1,
        permissions: [{
          permissionName: "read",
          "id": 1,
          "value": true
        }, {
          permissionName: "write",
          "id": 2,
          "value": true
        }, {
          permissionName: "execute",
          "id": 1,
          "value": false
        }]
      }, {
        actionName: "addproduct",
        id: 2,
        permissions: [{
          permissionName: "read",
          id: 1,
          value: true
        }, {
          permissionName: "write",
          id: 2,
          value: true
        }, {
          permissionName: "execute",
          id: 1,
          value: false
        }]
      }]
    }, {
      moduleName: "Module PQR",
      id: 2,
      actions: [{
        actionName: "addrules",
        id: 3,
        permissions: [{
          permissionName: "read",
          id: 1,
          value: true
        }, {
          permissionName: "write",
          id: 2,
          value: true
        }, {
          permissionName: "execute",
          id: 1,
          value: false
        }]
      }, {
        actionName: "addactions",
        id: 4,
        permissions: [{
          permissionName: "read",
          id: 1,
          value: true
        }, {
          permissionName: "write",
          id: 2,
          value: true
        }, {
          permissionName: "execute",
          id: 1,
          value: false
        }]
      }]
    }]
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/vue@2.5.3/dist/vue.js"></script>

<div id="app">
  <div v-for="(module, moduleIndex) in modules"><b>{{ module.moduleName }}</b>
    <div v-for="(action, actionIndex) in module.actions">{{ action.actionName }}
      <div v-for="(permission, permIndex) in action.permissions">
        <input type="checkbox" v-model='modules[moduleIndex].actions[actionIndex].permissions[permIndex].value'> {{ permission.permissionName }} - {{modules[moduleIndex].actions[actionIndex].permissions[permIndex].value}}
      </div>
    </div> <hr>
  </div></code>```

Body:
Here is my fiddle : DEMO

 modules: [{
      moduleName: "Module ABC",
      id: 1,
      actions: [{
        actionName: "addbrand",
        id: 1,
        permissions: [{
          permissionName: "read",
          "id": 1,
          "value": true
        }, {
          permissionName: "write",
          "id": 2,
          "value": true
        }, {
          permissionName: "execute",
          "id": 1,
          "value": false
        }]
}]

Checkboxes are dynamically generated iterating over "modules" array in data object. But I am finding it difficult to assign v-model and capture the checked values for the corresponding "action" for its respective "module"'

How do I do this?

{{ module.moduleName }}

{{ action.actionName }}

        <input type="checkbox"> {{ permission.permissionName }}

Any help would be much appreciated. Thank you..

Body:
I am not sure having nesting more than 2 v-for is a good idea. But you can create an index in v-for as: <p v-for='(foo, index) in array' and use the index to track changes.

In you case you do something like this  https://jsfiddle.net/samayo/az9hge7u/5/

new Vue({
  el: '#app',
  data: {
    modules: [{
      moduleName: "Module ABC",
      id: 1,
      actions: [{
        actionName: "addbrand",
        id: 1,
        permissions: [{
          permissionName: "read",
          "id": 1,
          "value": true
        }, {
          permissionName: "write",
          "id": 2,
          "value": true
        }, {
          permissionName: "execute",
          "id": 1,
          "value": false
        }]
      }, {
        actionName: "addproduct",
        id: 2,
        permissions: [{
          permissionName: "read",
          id: 1,
          value: true
        }, {
          permissionName: "write",
          id: 2,
          value: true
        }, {
          permissionName: "execute",
          id: 1,
          value: false
        }]
      }]
    }, {
      moduleName: "Module PQR",
      id: 2,
      actions: [{
        actionName: "addrules",
        id: 3,
        permissions: [{
          permissionName: "read",
          id: 1,
          value: true
        }, {
          permissionName: "write",
          id: 2,
          value: true
        }, {
          permissionName: "execute",
          id: 1,
          value: false
        }]
      }, {
        actionName: "addactions",
        id: 4,
        permissions: [{
          permissionName: "read",
          id: 1,
          value: true
        }, {
          permissionName: "write",
          id: 2,
          value: true
        }, {
          permissionName: "execute",
          id: 1,
          value: false
        }]
      }]
    }]
  }
})

<script src="https://unpkg.com/vue@2.5.3/dist/vue.js"></script>

<div id="app">
  <div v-for="(module, moduleIndex) in modules"><b>{{ module.moduleName }}</b>
    <div v-for="(action, actionIndex) in module.actions">{{ action.actionName }}
      <div v-for="(permission, permIndex) in action.permissions">
        <input type="checkbox" v-model='modules[moduleIndex].actions[actionIndex].permissions[permIndex].value'> {{ permission.permissionName }} - {{modules[moduleIndex].actions[actionIndex].permissions[permIndex].value}}
      </div>
    </div> <hr>
  </div>


问:
Determine major Java version across all Java releases
When determining the major Java version on Java 8 and before it was common to use the system property java.specification.version, drop 1., and parse the second digit:

on Java 8 this would yield "1.8" ~> "8" ~> 8

on Java 9 the same calls leads to NumberFormatException because the system property is "9"

What is a future-proof way to determine the major Java version? The goal is to get an int that can be if-ed or switch-ed over to decide which code path to take (e.g. in a library to activate a feature).

答:
Obviously, nothing can be guaranteed future-proof.  We cannot predict the future with certainty (!)

However, the following would work for previous versions of Java and versions that conform with JEP 233:

If version string starts with "1.[0-4]" use as is.

If version string starts with "1.[5-8]" remove the "1."

Otherwise, use the number before the first "."

But there is also the issue of which version of the numbering you use.  For example, "Java 5" and "Java 1.5" mean the same thing.  Which you use depends on who you are trying to satisfy with your naming scheme.

A good (but not definitive) reference on what the "official" Java version names is:

Java version history (Wikipedia)

Note that your original scheme breaks for early Java versions like "1.2.1" and "1.3.1" where the final number is significant.  And you don't want to start labeling Java 1.0 as "Java 0".  Finally, Java 1.0 and Java 1.1 are very different and should not be confused.  (Java 1.0 doesn't have nested / inner classes, for a start.)

I would only do this for the purpose of making a "manager friendly" name.  I would not reduce the version to a single number for "decision making purposes".  You are liable to find that differences between minor versions are significant.


问:
IFile to IResource
How can I get an IResource from an IFile or from an absolute path?

I tried with:

```<code>IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
resource = root.findMember(file.getAbsolutePath());
</code>```

But I get a null value.

答:
IFile extends IResource so if you have an IFile you have an IResource.

findMember treats the path it is given as relative to the container (the workspace root in this case). So you can't use it to find a file given an absolute file path - you must use the findFilesForLocation APIs for that.

Title: IFile to IResource

Body:
How can I get an IResource from an IFile or from an absolute path?

I tried with:

IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
resource = root.findMember(file.getAbsolutePath());

But I get a null value.


问:
serial aplication writtes "0D" as "0A"
I have a serial app on C that receives data and writes it onto a binary file. The problem is that all the data is the same but when i have 0A on sending side, i have 0D on receiving side. I have set the serial port on raw mode and opened the file with wb option. Any clue how to avoid this? If some code is needed, i'll post it.

thanks

EDIT--------------------------
File opening:

```<code> FILE *fout;
    fout = fopen(file,"wb");
</code>```

Serial options:

```<code>    options.c_cflag |= (CLOCAL | CREAD);

    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;

    /* To disable software flow control simply mask those bits: */
    options.c_iflag &= ~(IXON | IXOFF | IXANY);
    options.c_lflag &= ~(ICANON|ECHO|ECHOE|ISIG);

    tcsetattr(fd, TCSANOW, &options);

    success = 1;

    return success;
</code>```

Writting on the file:

```<code>fwrite(buffer,1,n,fout);
</code>```

----------FIX----------------------

Setting this option fixes the problem :
options.c_oflag &= ~OPOST;

答: You need to mask off the ICRNL mode which translates the enter (carriage return) key to the newline character. This is on the receiving end, not in your program. There's also a corresponding output mode that might be set on your end, but less likely.

Title: serial aplication writtes "0D" as "0A"

Body:
I have a serial app on C that receives data and writes it onto a binary file. The problem is that all the data is the same but when i have 0A on sending side, i have 0D on receiving side. I have set the serial port on raw mode and opened the file with wb option. Any clue how to avoid this? If some code is needed, i'll post it.

thanks

EDIT--------------------------
File opening:

 FILE *fout;
    fout = fopen(file,"wb");

Serial options:

    options.c_cflag |= (CLOCAL | CREAD);

    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;

    /* To disable software flow control simply mask those bits: */
    options.c_iflag &= ~(IXON | IXOFF | IXANY);
    options.c_lflag &= ~(ICANON|ECHO|ECHOE|ISIG);

    tcsetattr(fd, TCSANOW, &options);

    success = 1;

    return success;

Writting on the file:

fwrite(buffer,1,n,fout);

----------FIX----------------------

Setting this option fixes the problem :
options.c_oflag &= ~OPOST;


问:
Java Socket Programming
I am building a simple client/server application using java sockets and experimenting with the ObjectOutputStream etc.

I have been following the tutorial at this url http://java.sun.com/developer/technicalArticles/ALT/sockets starting half way down when it talks about transporting objects over sockets.

See my code for the client http://pastebin.com/m37e4c577 However this doesn't seem to work and i cannot figure out what's not working. The code commented out at the bottom is directly copied out of the tutorial - and this works when i just use that instead of creating the client object.

Can anyone see anything i am doing wrong?

答:
Just a reminder.

When you use ObjectOutputStream keep in mind that it keeps a reference cache. If you write an object, change the object contents, and then send the same object again, you will get duplicate data. For example:

```<code>List list = new ArrayList();
list.add("value1");
out.writeObject(list);
list.clear();
list.add("value2");
out.writeObject(list);
</code>```

Will produce in the client side two lists with the string "value1".

To avoid this, the reset method must be invoked to reset the stream cache when writing the same object reference multiple times:

```<code>List list = new ArrayList();
list.add("value1");
out.writeObject(list);
out.reset();
list.clear();
list.add("value2");
out.writeObject(list);
</code>```

OwnerDisplayName: Malachi

Title: Java Socket Programming

Body:
Just a reminder.

When you use ObjectOutputStream keep in mind that it keeps a reference cache. If you write an object, change the object contents, and then send the same object again, you will get duplicate data. For example:

List list = new ArrayList();
list.add("value1");
out.writeObject(list);
list.clear();
list.add("value2");
out.writeObject(list);

Will produce in the client side two lists with the string "value1".

To avoid this, the reset method must be invoked to reset the stream cache when writing the same object reference multiple times:

List list = new ArrayList();
list.add("value1");
out.writeObject(list);
out.reset();
list.clear();
list.add("value2");
out.writeObject(list);

OwnerDisplayName: jassuncao