问:
TypeError: Impossible to find getCell function in the Sheet object
I'm trying to get some data from a Google Sheet to insert in two arrays with a for loop but I think I'm using the wrong methods.

This is the code:

```<code>function regValori() {
    var datAgg = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("datiaggiornati");
    var f5 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Foglio5");
    var CValue = new Array();
    var CName = new Array();

    CValue.lenght = datAgg.getRange("B1").getValue();
    CName.lenght = CValue.lenght;

    for (var i = 0; i <= CValue.lenght; i++)
    {
        CValue[i] = datAgg.getCell(i, 16).getValue();
        CName[i] = datAgg.getCell(i+2, 1).getValue();
    }
    var riga = f5.getRange("B2").getValue();
      for (x = 3; x <= numCrypto; x++);
        for (i=0;i<numCrypto;i++);
          {
            f5.getRange(riga, x).setValue(valCrypto[r+i]);
            f5.getRange(2,numCrypto).setValue(nomiCrypto[r+i]);
          }
        }
</code>```

The error:

TypeError: Impossible to find getCell function in the Sheet object

Thanks for your help!

答:
this is the solution:

```<code>function regValori() {
    var datAgg = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("datiaggiornati");
    var f5 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Foglio5");

    var riga = f5.getRange(2, 2).getValue();
    for (var i = 2; i <= 6; ++i) {
        f5.getRange(riga, i + 1).setValue(datAgg.getRange("P" + i).getValue());
        f5.getRange(2, i + 1).setValue(datAgg.getRange("A" + i).getValue());
    }
}
</code>```

i posted another question here for the same problem and I get a perfect answer how to use for loop to drastically reduce code lenght.
the only part I changed is this one: (var i = 2; i <= 6; ++i) with this one: (var i = 2; i <= n+1; ++i), so it can work perfectly with any variable n to get with command "var numCrypto = datAgg.getRange(1,2).getValue();"

Body:
I'm trying to get some data from a Google Sheet to insert in two arrays with a for loop but I think I'm using the wrong methods.

This is the code:

function regValori() {
    var datAgg = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("datiaggiornati");
    var f5 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Foglio5");
    var CValue = new Array();
    var CName = new Array();

    CValue.lenght = datAgg.getRange("B1").getValue();
    CName.lenght = CValue.lenght;

    for (var i = 0; i <= CValue.lenght; i++)
    {
        CValue[i] = datAgg.getCell(i, 16).getValue();
        CName[i] = datAgg.getCell(i+2, 1).getValue();
    }
    var riga = f5.getRange("B2").getValue();
      for (x = 3; x <= numCrypto; x++);
        for (i=0;i<numCrypto;i++);
          {
            f5.getRange(riga, x).setValue(valCrypto[r+i]);
            f5.getRange(2,numCrypto).setValue(nomiCrypto[r+i]);
          }
        }

The error:

TypeError: Impossible to find getCell function in the Sheet object

Thanks for your help!

Body:
this is the solution:

function regValori() {
    var datAgg = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("datiaggiornati");
    var f5 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Foglio5");

    var riga = f5.getRange(2, 2).getValue();
    for (var i = 2; i <= 6; ++i) {
        f5.getRange(riga, i + 1).setValue(datAgg.getRange("P" + i).getValue());
        f5.getRange(2, i + 1).setValue(datAgg.getRange("A" + i).getValue());
    }
}

i posted another question here for the same problem and I get a perfect answer how to use for loop to drastically reduce code lenght.
the only part I changed is this one: (var i = 2; i <= 6; ++i) with this one: (var i = 2; i <= n+1; ++i), so it can work perfectly with any variable n to get with command "var numCrypto = datAgg.getRange(1,2).getValue();"


来源: stackexchange

问:
Deleting objects in a specific folder using sweep policy
I have several folders inside my object store, and i want to implement a sweep policy for housekeeping. The idea is that any files/subfolders/documents inside one of my several "main" folders needs to be deleted if they are more than one month old.

I understand that i can do this by using sweep policy, but i have no idea about how to do it.

Probably something to mention, all subfolders in my object store have their own class, but the main folders share one class, "Folder".
Can anyone help with a guide or something about this? I've been to the IBM site and it's not helping much.
Thanks.

答:
I figured it out, with @fnt 's help:

Object deletion automated by using disposal policy, not the standard sweep. Disposal policy deletes things in the object store based on the object class.
Since the target of my disposal already has a class, i can just use that as the base.

The Filter expression is an SQL WHERE query, this is what i put in it:

```<code>DateCreated < Now() - Timespan (30, 'Days') AND PathName LIKE '%Application%'
</code>```

Both INFOLDER and CONTAINS did not work. While i still cannot figure out why INFOLDER doesn't work, CONTAINS apparently requires both the object store and object class of your disposal to be CBR-enabled, which i don't have.

ContentLicense: CC BY-SA 3.0

Body:
I figured it out, with @fnt 's help:

Object deletion automated by using disposal policy, not the standard sweep. Disposal policy deletes things in the object store based on the object class.
Since the target of my disposal already has a class, i can just use that as the base.

The Filter expression is an SQL WHERE query, this is what i put in it:

DateCreated < Now() - Timespan (30, 'Days') AND PathName LIKE '%Application%'

Both INFOLDER and CONTAINS did not work. While i still cannot figure out why INFOLDER doesn't work, CONTAINS apparently requires both the object store and object class of your disposal to be CBR-enabled, which i don't have.


问:
How to hide textarea if input is empty
How do I use jQuery to hide textarea if input text is empty?

My attempt:

```<code>jQuery(document).chnage(function($) {
    var value=$.trim($('input').val());

    if (value.length < 0) {
        $('textarea[name="your-message"]').hide();
    }
});
</code>```

答:
Try this might help you

$('#txtID').on('input', function() {
if(this.value.trim() !== ''){
$('#txtID').show();

}else{
$('#txtID').hide();

}

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<textarea rows="4" cols="50" id="txtID"></textarea></code>```

Title: How to hide textarea if input is empty

Body:
How do I use jQuery to hide textarea if input text is empty?

My attempt:

jQuery(document).chnage(function($) {
    var value=$.trim($('input').val());

    if (value.length < 0) {
        $('textarea[name="your-message"]').hide();
    }
});

Body:
Try this might help you

$('#txtID').on('input', function() {
if(this.value.trim() !== ''){
$('#txtID').show();

}else{
$('#txtID').hide();

}

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<textarea rows="4" cols="50" id="txtID"></textarea>


问:
How to display property in my reactjs component?
In my component I have :

```<code>function Message(msg) {
        //console.log('msg=', msg);
        return (
                <div>
                    {
                        msg ?
                                <div>{msg}</div> :
                                <div>Nothing</div>
                    }
                </div>
        )
    }
</code>```

When I try to render this component in my IDE I get this chromeconsole-error:

Uncaught Error: Objects are not valid as a React child (found: object
  with keys {msg}). If you meant to render a collection of children, use
  an array instead.

How can I display the msg value ie 'hi' in my component?
fiddle

答:
Issue is, in function argument you will get the props object so msg (just the argument name) will have the values of props, because syntax is:

```<code>function Name (props){
    ...
}
</code>```

And in props you are passing msg that's why it is throwing the error:

found: object with keys {msg})

So either use {msg.msg} like this:

```<code>function Message(msg) {
    return (
        <div>
            {
                msg.msg ?
                    <div>{msg.msg}</div> :
                    <div>Nothing</div>
            }
        </div>
    )
}
</code>```

Or use destructuring and write it like this:

```<code>function Message({ msg }) {
   ...
}
</code>```

Body:
In my component I have :

function Message(msg) {
        //console.log('msg=', msg);
        return (

                    {
                        msg ?

{msg}
 :

Nothing

                    }

        )
    }

When I try to render this component in my IDE I get this chromeconsole-error:

Uncaught Error: Objects are not valid as a React child (found: object
  with keys {msg}). If you meant to render a collection of children, use
  an array instead.

How can I display the msg value ie 'hi' in my component?
fiddle

Body:
Issue is, in function argument you will get the props object so msg (just the argument name) will have the values of props, because syntax is:

function Name (props){
    ...
}

And in props you are passing msg that's why it is throwing the error:

found: object with keys {msg})

So either use {msg.msg} like this:

function Message(msg) {
    return (
        <div>
            {
                msg.msg ?
                    <div>{msg.msg}</div> :
                    <div>Nothing</div>
            }
        </div>
    )
}

Or use destructuring and write it like this:

function Message({ msg }) {
   ...
}


问:
How to save user input to local storage
I am creating a score keeping app and need to save the name of the players and the game name in local storage, have no idea how to apply it to the code I have

$(document).ready(function() {
  $("#add-playername").click(function(e) {
    e.preventDefault();
    var numberOfPlayernames = $("#form1").find("input[name^='data[playername]']").length;
    var label = 'Playername ' + (numberOfPlayernames + 1) + ' ';
    var input = '<input type="text" name="data[playername][' + numberOfPlayernames + ']" id="data[playername][' + numberOfPlayernames + ']" />';
    var removeButton = '<button class="remove-playername">Remove</button>';
    var html = "
" + label + input + removeButton + "
";
    $("#form1").find("#add-playername").before(html);
  });
});

$(document).on("click", ".remove-playername", function(e) {
  e.preventDefault();
  $(this).parents(".playername").remove(); //remove playername is connected to this

  $("#form1").find("label[for^='data[playername]']").each(function() {
    $(this).html("Playername " + ($(this).parents('.playername').index() + 1));
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form2" method="post">
  <div class="gamename">
    <label><b>Enter Game Name</b></label>
    <input type="text" name="game name" placeholder="Game Name" id="user_input">
  </div>
</form>
<form id="form1" method="post">
  <div class="playername">
    <label for="data[playername][0]">Add Player Name</label>
    <input type="text" name="data[playername][0]" placeholder="Enter player's name" id="data[playername][0]" />
  </div>
  <button id="add-playername">Add Player</button>
  <br>
  <br>
  <input type="submit" value="Submit" />
</form></code>```

答:
late to answer but something like this</p>

```<code><input type="submit" value="Submit" id="btn_submit" />

<script type="text/javascript">
 $(document).ready(function(){

    $("#btn_submit").click(function(e){
        e.preventDefault();
        var jsonObj = [];
        players = {}
        count = 0;

        $('input[type=text]').each(function(){
            if($.trim($(this).val()) && ($(this).attr('name').indexOf("playername") >= 0)){
                players[count++] = $(this).val()
            }
        });

        players['game_name'] = $("#user_input").val();

        jsonObj.push(players);
        console.log(jsonObj);

       var jsonString= JSON.stringify(jsonObj);
       localStorage.setItem("jsonString", jsonString);

       /* remove localstorage */
       // localStorage.removeItem("jsonString");

       /* get localstorage */
       // console.log(localStorage.getItem("jsonString"));
    });
</script>
</code>```

Title: How to save user input to local storage

Body:
I am creating a score keeping app and need to save the name of the players and the game name in local storage, have no idea how to apply it to the code I have

$(document).ready(function() {
  $("#add-playername").click(function(e) {
    e.preventDefault();
    var numberOfPlayernames = $("#form1").find("input[name^='data[playername]']").length;
    var label = 'Playername ' + (numberOfPlayernames + 1) + ' ';
    var input = '<input type="text" name="data[playername][' + numberOfPlayernames + ']" id="data[playername][' + numberOfPlayernames + ']" />';
    var removeButton = '<button class="remove-playername">Remove</button>';
    var html = "
" + label + input + removeButton + "
";
    $("#form1").find("#add-playername").before(html);
  });
});

$(document).on("click", ".remove-playername", function(e) {
  e.preventDefault();
  $(this).parents(".playername").remove(); //remove playername is connected to this

  $("#form1").find("label[for^='data[playername]']").each(function() {
    $(this).html("Playername " + ($(this).parents('.playername').index() + 1));
  });
});

<form id="form2" method="post">

    Enter Game Name
    <input type="text" name="game name" placeholder="Game Name" id="user_input">

</form>
<form id="form1" method="post">

    Add Player Name
    <input type="text" name="data[playername][0]" placeholder="Enter player's name" id="data[playername][0]" />

  <button id="add-playername">Add Player</button>

  <input type="submit" value="Submit" />
</form>

Body:
late to answer but something like this

<input type="submit" value="Submit" id="btn_submit" />

<script type="text/javascript">
 $(document).ready(function(){

    $("#btn_submit").click(function(e){
        e.preventDefault();
        var jsonObj = [];
        players = {}
        count = 0;

        $('input[type=text]').each(function(){
            if($.trim($(this).val()) && ($(this).attr('name').indexOf("playername") >= 0)){
                players[count++] = $(this).val()
            }
        });

        players['game_name'] = $("#user_input").val();

        jsonObj.push(players);
        console.log(jsonObj);

       var jsonString= JSON.stringify(jsonObj);
       localStorage.setItem("jsonString", jsonString);

       /* remove localstorage */
       // localStorage.removeItem("jsonString");

       /* get localstorage */
       // console.log(localStorage.getItem("jsonString"));
    });
</script>


问:
Error: Database schema comparison using schema project with Azure database
I'm using database project for maintaining database schemas. Schema comparison works perfectly with local databases. But when I connect to Azure database and compare with the schema project, it throws following error.

Unexpected exception caught during population of target model: Value cannot be null.
  Parameter name: catalogStamp

I have tried cleaning up all the saved connections via HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\14.0\SSDT\ConnectionMruList

Any help would be appreciated. Thanks!

答:
Try this</p>

```<code>ALTER DATABASE [Database_Name] SET COMPATIBILITY_LEVEL = 120
</code>```

Body:
Try this

ALTER DATABASE [Database_Name] SET COMPATIBILITY_LEVEL = 120


问:
How do I download zip file in C#?
I use HTTP GET that downloads a zip file in a browser, something like  https://example.com/up/DBID/a/rRID/eFID/vVID (not the exact url)

Now, when I try to do the same download in C# code(same GET method as above) for a desktop application, the zip file downloaded is not a valid archive file. When I opened this file in notepad, it was some HTML page.

I think I'm not setting some header correctly. I looked around for examples. I'd found several wrt uploads, but did not see anything for downloads.

Code:

```<code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/zip";
try
{
    HttpWebResponse res = (HttpWebResponse)request.GetResponse();
    using (StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default))
    {
        StreamWriter oWriter = new StreamWriter(@"D:\Downloads\1.zip");
        oWriter.Write(sr.ReadToEnd());
        oWriter.Close();
    }
    res.Close();
}
catch (Exception ex)
{
}
</code>```

答:
You could just use WebClient for a 2-liner:

```<code>using(WebClient wc = new WebClient())
{
   wc.DownloadFile(url, @"D:\Downloads\1.zip");
}
</code>```

Title: How do I download zip file in C#?

Body:
I use HTTP GET that downloads a zip file in a browser, something like  https://example.com/up/DBID/a/rRID/eFID/vVID (not the exact url)

Now, when I try to do the same download in C# code(same GET method as above) for a desktop application, the zip file downloaded is not a valid archive file. When I opened this file in notepad, it was some HTML page.

I think I'm not setting some header correctly. I looked around for examples. I'd found several wrt uploads, but did not see anything for downloads.

Code:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/zip";
try
{
    HttpWebResponse res = (HttpWebResponse)request.GetResponse();
    using (StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default))
    {
        StreamWriter oWriter = new StreamWriter(@"D:\Downloads\1.zip");
        oWriter.Write(sr.ReadToEnd());
        oWriter.Close();
    }
    res.Close();
}
catch (Exception ex)
{
}

Body:
You could just use WebClient for a 2-liner:

using(WebClient wc = new WebClient())
{
   wc.DownloadFile(url, @"D:\Downloads\1.zip");
}


问:
parts and products relational schema
I have a requirement for inventory management where we need to track parts and products (Finish goods) for which I think of tables as given below,

```<code>Part_Category {id, code, name}
Parts {id, code, name, description, part_cat_id, manufacturer_id, is_salable}
FG_Category {id, code, name}
Finish_Good {id, code, name, fg_cat_id, is_part_also}
</code>```

The is_salable flag is used to say that this part can be sold to customer directly and is_part_also indicates that it is a sub-assembly (used as part in some another FG)

The use cases are,

Parts (raw materials) are issued for production

if FG is a sub-assembly (is_part_also), then that can be issued for production

some parts are directly sold to customers (like FG sold earlier requires a servicing and the firm should be able to sell a part required for this)

FGs are anyway sold directly to customers

The problem I have (using relational based schema) are -

is this the best way to store and track part inventory that are salable as well as are used for production

what is the best way to store and track FG inventory if it is a semi-finished good that can be sold as well as can be issued for production

Assuming that I need to issue all parts from Parts table and all items are sold from Finish_Good table, I have following problems,

managing quantities

since parts are issued from Parts table, not able to issue semi-finished goods from Finish_Good table for production

since salable parts are also in Parts table, they can not be sold

the inventory value be accounted in one place only (if a part is salable, its value is shown under FG stock and the semi-finished product value under Parts stock)

For now, I'm thinking of copying over the semi-finished FGs to Parts table in the application internally when they are produced and salable parts to the Finish_Good table (when they are received) so that they are all available at the right places. But these operations are atomic and appears error prone! But the quantities should also be shown under one accordingly (either Parts or in Finish_Good)

Is there a better design for this?

答:
Managed the above use case by simplifying the overall table structure and by defining a process around the sales & raw material (RM) issue for production.

Storing the available quantity of RMs only in Parts & FGs in
Finish_Good table

Transactions such as parts issue will only deal
with Parts table

Sales will only deal with Finish_Good table

Transactions need not decrement/ increment quantity from multiple tables

Defined a process where required quantity of the saleable RM should be
moved to Finish_Good before a sale and required quantity of semi-finished good to be moved to Part table for use in production

This has simplified the table structure as well as helped in maintaining correct inventory information across the system. This also helped in audit reconciliation where the inventory quantity may be corrected at one place.

Title: parts and products relational schema

Body:
I have a requirement for inventory management where we need to track parts and products (Finish goods) for which I think of tables as given below,

Part_Category {id, code, name}
Parts {id, code, name, description, part_cat_id, manufacturer_id, is_salable}
FG_Category {id, code, name}
Finish_Good {id, code, name, fg_cat_id, is_part_also}

The is_salable flag is used to say that this part can be sold to customer directly and is_part_also indicates that it is a sub-assembly (used as part in some another FG)

The use cases are,

Parts (raw materials) are issued for production

if FG is a sub-assembly (is_part_also), then that can be issued for production

some parts are directly sold to customers (like FG sold earlier requires a servicing and the firm should be able to sell a part required for this)

FGs are anyway sold directly to customers

The problem I have (using relational based schema) are -

is this the best way to store and track part inventory that are salable as well as are used for production

what is the best way to store and track FG inventory if it is a semi-finished good that can be sold as well as can be issued for production

Assuming that I need to issue all parts from Parts table and all items are sold from Finish_Good table, I have following problems,

managing quantities

since parts are issued from Parts table, not able to issue semi-finished goods from Finish_Good table for production

since salable parts are also in Parts table, they can not be sold

the inventory value be accounted in one place only (if a part is salable, its value is shown under FG stock and the semi-finished product value under Parts stock)

For now, I'm thinking of copying over the semi-finished FGs to Parts table in the application internally when they are produced and salable parts to the Finish_Good table (when they are received) so that they are all available at the right places. But these operations are atomic and appears error prone! But the quantities should also be shown under one accordingly (either Parts or in Finish_Good)

Is there a better design for this?


问:
MPAndroid Group bar chart is not showing
Here is the code i used for group bar_chart using MPAndroid library version 3. I've tried group bar chart in lower version and it works fine but the BarData constructor is changed in latest version. And this code doesn't works. There is no crashes and error logs, still graph is loading and no data shows in it. Help me to find ma flaws

```<code>        List<BarEntry> entriesGroup1 = new ArrayList<>();
        List<BarEntry> entriesGroup2 = new ArrayList<>();
        List<BarEntry> entriesGroup3 = new ArrayList<>();

        entriesGroup1.add(new BarEntry(0, 8f));
        entriesGroup1.add(new BarEntry(1, 2f));
        entriesGroup1.add(new BarEntry(2, 5f));
        entriesGroup1.add(new BarEntry(3, 20f));
        entriesGroup1.add(new BarEntry(4, 15f));
        entriesGroup1.add(new BarEntry(5, 19f));

        entriesGroup2.add(new BarEntry(0, 6f));
        entriesGroup2.add(new BarEntry(1, 10f));
        entriesGroup2.add(new BarEntry(2, 5f));
        entriesGroup2.add(new BarEntry(3, 25f));
        entriesGroup2.add(new BarEntry(4, 4f));
        entriesGroup2.add(new BarEntry(5, 17f));

        entriesGroup3.add(new BarEntry(0, 9f));
        entriesGroup3.add(new BarEntry(1, 1f));
        entriesGroup3.add(new BarEntry(2, 15f));
        entriesGroup3.add(new BarEntry(3, 13f));
        entriesGroup3.add(new BarEntry(4, 40f));
        entriesGroup3.add(new BarEntry(5, 25f));

        BarDataSet set1 = new BarDataSet(entriesGroup1, "Group 1");
        BarDataSet set2 = new BarDataSet(entriesGroup2, "Group 2");
        BarDataSet set3 = new BarDataSet(entriesGroup3, "Group 3");

        final ArrayList<String> labels = new ArrayList<String>();
        labels.add("2016");
        labels.add("2015");
        labels.add("2014");
        labels.add("2013");
        labels.add("2012");
        labels.add("2011");
        IAxisValueFormatter formatter = new IAxisValueFormatter() {

            @Override
            public String getFormattedValue(float value, AxisBase axis) {

                if((int) value < 0 || (int) value >= labels.size()){
                    return "";
                }else{
                    return labels.get((int) value);
                }
            }

            // we don't draw numbers, so no decimal digits needed
            @Override
            public int getDecimalDigits() {  return 0; }
        };

        set1.setColor(Color.parseColor("#cd5080"));
        set2.setColor(Color.parseColor("#0d5080"));
        set3.setColor(Color.parseColor("#fc5080"));;

        float groupSpace = 0.06f;
        float barSpace = 0.02f; // x2 dataset
        float barWidth = 0.45f; // x2 dataset
// (0.02 + 0.45) * 2 + 0.06 = 1.00 -> interval per "group"

        XAxis xAxis = barChart.getXAxis();
        xAxis.setCenterAxisLabels(true);
        xAxis.setGranularity(1f); // minimum axis-step (interval) is 1
        xAxis.setValueFormatter(formatter);

        BarData data = new BarData(set1, set2, set3);
        data.setBarWidth(barWidth); // set the width of each bar
        barChart.setData(data);
        barChart.groupBars(2016, groupSpace, barSpace);
        barChart.invalidate(); // refresh

        barChart.animateY(5000);
</code>```

Nb: I'm edited my current question since i'm banned to ask new questions. But its important for me. Thanks everyone.

答: You can use the activity hasWindowFocus() boolean method. Then if it has focus you display a pop-up from the activity, if not, you just display the notification.

Body:
Here is the code i used for group bar_chart using MPAndroid library version 3. I've tried group bar chart in lower version and it works fine but the BarData constructor is changed in latest version. And this code doesn't works. There is no crashes and error logs, still graph is loading and no data shows in it. Help me to find ma flaws

        List<BarEntry> entriesGroup1 = new ArrayList<>();
        List<BarEntry> entriesGroup2 = new ArrayList<>();
        List<BarEntry> entriesGroup3 = new ArrayList<>();

        entriesGroup1.add(new BarEntry(0, 8f));
        entriesGroup1.add(new BarEntry(1, 2f));
        entriesGroup1.add(new BarEntry(2, 5f));
        entriesGroup1.add(new BarEntry(3, 20f));
        entriesGroup1.add(new BarEntry(4, 15f));
        entriesGroup1.add(new BarEntry(5, 19f));

        entriesGroup2.add(new BarEntry(0, 6f));
        entriesGroup2.add(new BarEntry(1, 10f));
        entriesGroup2.add(new BarEntry(2, 5f));
        entriesGroup2.add(new BarEntry(3, 25f));
        entriesGroup2.add(new BarEntry(4, 4f));
        entriesGroup2.add(new BarEntry(5, 17f));

        entriesGroup3.add(new BarEntry(0, 9f));
        entriesGroup3.add(new BarEntry(1, 1f));
        entriesGroup3.add(new BarEntry(2, 15f));
        entriesGroup3.add(new BarEntry(3, 13f));
        entriesGroup3.add(new BarEntry(4, 40f));
        entriesGroup3.add(new BarEntry(5, 25f));

        BarDataSet set1 = new BarDataSet(entriesGroup1, "Group 1");
        BarDataSet set2 = new BarDataSet(entriesGroup2, "Group 2");
        BarDataSet set3 = new BarDataSet(entriesGroup3, "Group 3");

        final ArrayList<String> labels = new ArrayList<String>();
        labels.add("2016");
        labels.add("2015");
        labels.add("2014");
        labels.add("2013");
        labels.add("2012");
        labels.add("2011");
        IAxisValueFormatter formatter = new IAxisValueFormatter() {

            @Override
            public String getFormattedValue(float value, AxisBase axis) {

                if((int) value < 0 || (int) value >= labels.size()){
                    return "";
                }else{
                    return labels.get((int) value);
                }
            }

            // we don't draw numbers, so no decimal digits needed
            @Override
            public int getDecimalDigits() {  return 0; }
        };

        set1.setColor(Color.parseColor("#cd5080"));
        set2.setColor(Color.parseColor("#0d5080"));
        set3.setColor(Color.parseColor("#fc5080"));;

        float groupSpace = 0.06f;
        float barSpace = 0.02f; // x2 dataset
        float barWidth = 0.45f; // x2 dataset
// (0.02 + 0.45) * 2 + 0.06 = 1.00 -> interval per "group"

        XAxis xAxis = barChart.getXAxis();
        xAxis.setCenterAxisLabels(true);
        xAxis.setGranularity(1f); // minimum axis-step (interval) is 1
        xAxis.setValueFormatter(formatter);

        BarData data = new BarData(set1, set2, set3);
        data.setBarWidth(barWidth); // set the width of each bar
        barChart.setData(data);
        barChart.groupBars(2016, groupSpace, barSpace);
        barChart.invalidate(); // refresh

        barChart.animateY(5000);

Nb: I'm edited my current question since i'm banned to ask new questions. But its important for me. Thanks everyone.


问:
How is it possible to do UI operations outside the UI thread?
I tried to set a text inside a normal thread outside of the UI thread and it worked fine.

```<code>    private TextView mTextView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView) findViewById(R.id.my_text);
        Log.d("**** ONCREATE****", Thread.currentThread().getId()+"");
        new BackgroundTestThread().start();
    }

    class BackgroundTestThread extends Thread{
    @Override
    public void run() {
         Log.d("**** THREAD****", Thread.currentThread().getId()+"");
         mTextView.setText("Text was set successfully", TextView.BufferType.EDITABLE);
         }
    }
</code>```

I was pretty much surprised to see this happen. I thought a worker thread can never update main thread because only main thread can render the UI elements (TextView, EditText etc.) and if we try to update, for sure we are going to get an exception.

Why did this happen?

答:
Another way to do UI operations safety outside main UI thread.</p>

```<code>    runOnUiThread(new Runnable() {
        @Override
        public void run() {
           mTextView.setText("Text was set successfully", TextView.BufferType.EDITABLE);
        }
    });
</code>```

Body:
I tried to set a text inside a normal thread outside of the UI thread and it worked fine.

    private TextView mTextView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView) findViewById(R.id.my_text);
        Log.d("**** ONCREATE****", Thread.currentThread().getId()+"");
        new BackgroundTestThread().start();
    }

    class BackgroundTestThread extends Thread{
    @Override
    public void run() {
         Log.d("**** THREAD****", Thread.currentThread().getId()+"");
         mTextView.setText("Text was set successfully", TextView.BufferType.EDITABLE);
         }
    }

I was pretty much surprised to see this happen. I thought a worker thread can never update main thread because only main thread can render the UI elements (TextView, EditText etc.) and if we try to update, for sure we are going to get an exception.

Why did this happen?

Body:
Another way to do UI operations safety outside main UI thread.

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
           mTextView.setText("Text was set successfully", TextView.BufferType.EDITABLE);
        }
    });


问:
Render time increasing with time
Given this code

```<code>import tkinter

canvas = tkinter.Canvas()
canvas.pack()

i = 0
k = 1

while True:
    canvas.create_text(100, 0+i, text="Python 3.6!", fill="red")
    canvas.update()
    canvas.create_rectangle(0, 0, canvas["width"], canvas["height"], fill=canvas["background"])
    canvas.after(3)
    i = i + k

    if i==-1 or i==265:
        k = -k
</code>```

we can see that with each cycle of while loop the movement of the text slows down.

Now, since we are re-rendering the whole canvas multiple times a second, no wonder that it is slow. However, why is it slowing down with time? Is it due to the great amount of objects text and rectangle objects piling up? Can this be avoided?

答:
Instead of moving the text, at each iteration you create a new text item and a rectangle to hide the previous one, so the canvas gets crowded and the program slows down.

There are several ways to avoid that:

1) Delete the text instead of hiding it behind a rectangle:

```<code>   text = canvas.create_text(100, i, text="Python 3.6!", fill="red")
   ...
   canvas.delete(text)
</code>```

2) Change the coordinates of the existing item with coords:

```<code>import tkinter

canvas = tkinter.Canvas()
canvas.pack()

i = 0
k = 1
text = canvas.create_text(100, i, text="Python 3.6!", fill="red")

while True:
    canvas.coords(text, 100, i)  # change coordinates of the text
    canvas.update()
    canvas.after(3)
    i = i + k
    if i==-1 or i==265:
        k = -k
</code>```

3) Move the existing item with move:

```<code>import tkinter

canvas = tkinter.Canvas()
canvas.pack()

i = 0
k = 1
text = canvas.create_text(100, i, text="Python 3.6!", fill="red")

while True:
    canvas.move(text, 0, k)  # increment by k the y coordinate of the text
    canvas.update()
    canvas.after(3)
    i = i + k
    if i==-1 or i==265:
        k = -k
</code>```

Finally, instead of a while loop, you can also use the after method to make the animation. Something like:

```<code>import tkinter

root = tkinter.Tk()
canvas = tkinter.Canvas(root)
canvas.pack()

def motion(i, k):
    canvas.coords(text, 100, i)
    i = i + k
    if i==-1 or i==265:
        k = -k
    canvas.after(3, motion, i, k)

i = 0
k = 1
text = canvas.create_text(100, 0, text="Python 3.6!", fill="red")

motion(i, k)

root.mainloop()
</code>```

Title: Render time increasing with time

Body:
Given this code

import tkinter

canvas = tkinter.Canvas()
canvas.pack()

i = 0
k = 1

while True:
    canvas.create_text(100, 0+i, text="Python 3.6!", fill="red")
    canvas.update()
    canvas.create_rectangle(0, 0, canvas["width"], canvas["height"], fill=canvas["background"])
    canvas.after(3)
    i = i + k

    if i==-1 or i==265:
        k = -k

we can see that with each cycle of while loop the movement of the text slows down.

Now, since we are re-rendering the whole canvas multiple times a second, no wonder that it is slow. However, why is it slowing down with time? Is it due to the great amount of objects text and rectangle objects piling up? Can this be avoided?

Body:
Instead of moving the text, at each iteration you create a new text item and a rectangle to hide the previous one, so the canvas gets crowded and the program slows down.

There are several ways to avoid that:

1) Delete the text instead of hiding it behind a rectangle:

   text = canvas.create_text(100, i, text="Python 3.6!", fill="red")
   ...
   canvas.delete(text)

2) Change the coordinates of the existing item with coords:

import tkinter

canvas = tkinter.Canvas()
canvas.pack()

i = 0
k = 1
text = canvas.create_text(100, i, text="Python 3.6!", fill="red")

while True:
    canvas.coords(text, 100, i)  # change coordinates of the text
    canvas.update()
    canvas.after(3)
    i = i + k
    if i==-1 or i==265:
        k = -k

3) Move the existing item with move:

import tkinter

canvas = tkinter.Canvas()
canvas.pack()

i = 0
k = 1
text = canvas.create_text(100, i, text="Python 3.6!", fill="red")

while True:
    canvas.move(text, 0, k)  # increment by k the y coordinate of the text
    canvas.update()
    canvas.after(3)
    i = i + k
    if i==-1 or i==265:
        k = -k

Finally, instead of a while loop, you can also use the after method to make the animation. Something like:

import tkinter

root = tkinter.Tk()
canvas = tkinter.Canvas(root)
canvas.pack()

def motion(i, k):
    canvas.coords(text, 100, i)
    i = i + k
    if i==-1 or i==265:
        k = -k
    canvas.after(3, motion, i, k)

i = 0
k = 1
text = canvas.create_text(100, 0, text="Python 3.6!", fill="red")

motion(i, k)

root.mainloop()


答:
You need to change to:

```<code> function Message({msg}) {
</code>```

Because that function receives an object 'props' with msg key.

Other ways:

```<code> function Message(props)
  ... {props.msg}
</code>```

Title: How to display property in my reactjs component?

Body:
You need to change to:

 function Message({msg}) {

Because that function receives an object 'props' with msg key.

Other ways:

 function Message(props)
  ... {props.msg}


问:
jQuery autocomplete - how to prevent auto focus when minLength is zero

 var availableTags = [
    "ActionScript",
    "AppleScript",
    "Asp",
    "BASIC",
    "C",
    "C++",
    "Clojure",
    "COBOL",
    "ColdFusion",
    "Erlang",
    "Fortran",
    "Groovy",
    "Haskell",
    "Java",
    "JavaScript",
    "Lisp",
    "Perl",
    "PHP",
    "Python",
    "Ruby",
    "Scala",
    "Scheme"];

    $("#test").autocomplete({
        minLength: 0,
        source: availableTags,
        autoFocus: true,
        select: function (event, ui) {
            if (ui.item) {
                event.preventDefault();
                $(this).val(ui.item.label);
            }
        },
        open: function (event, ui) {
            var menu = $(this).data("uiAutocomplete").menu;
            var items = $('li', menu.element);

            for (var i = 0; i < items.length; i++) {
                if (items.eq(i).text().startsWith($(this).val())) {
                    menu.focus(null, items.eq(i));
                    break;
                }
            }
        },
        focus: function (event, ui) {
            event.preventDefault();
            if ($(this).val() == "" && !event.keyCode) {
                //debugger;
                $('.ui-menu-item a').removeClass('ui-state-focus');
            }
            else {
                //$(this).data("uiAutocomplete").menu.element.children().first().focus();
            }
        }
    }).on("focus", function () {
        $(this).autocomplete("search", "");
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
    <label for="test" class="col-md-3 col-lg-3 control-label"></label>
    <div class="col-md-9 col-lg-7">
        <input id="test" type="text" class="form-control" />
    </div>
</div></code>```

While tabbing through the page, inputs with autocomplete are filling out by default with the first option in dropdown. If I set minLength = 1, problem solved. However, I have to keep minLength = 0 in order to pop up the dropdown when the input is focused.

One thought is that removing the focus class when first popping up the dropdown. But the problem is when I press the arrowdown, the second option is focused instead of the first one.

I cannot find any solution to manually focus the first option. Please help.

Any other solutions are more than welcome. Thanks in advance.

答:
You Need to change .autocomplete to .availableTags in last part of your js.I hope this will help you

$( function() {
var availableTags = [
    "ActionScript",
    "AppleScript",
    "Asp",
    "BASIC",
    "C",
    "C++",
    "Clojure",
    "COBOL",
    "ColdFusion",
    "Erlang",
    "Fortran",
    "Groovy",
    "Haskell",
    "Java",
    "JavaScript",
    "Lisp",
    "Perl",
    "PHP",
    "Python",
    "Ruby",
    "Scala",
    "Scheme"];

    $("#test").autocomplete({
        minLength: 0,
        source: availableTags,
        autoFocus: true,
        select: function (event, ui) {
            if (ui.item) {
                event.preventDefault();
                $(this).val(ui.item.label);
            }
        },
        open: function (event, ui) {
            var menu = $(this).data("uiAutocomplete").menu;
            var items = $('li', menu.element);

            for (var i = 0; i < items.length; i++) {
                if (items.eq(i).text().startsWith($(this).val())) {
                    menu.focus(null, items.eq(i));
                    break;
                }
            }
        },
        focus: function (event, ui) {
            event.preventDefault();
            if ($(this).val() == "" && !event.keyCode) {
                //debugger;
                $('.ui-menu-item a').removeClass('ui-state-focus');
            }
            else {
                //$(this).data("uiAutocomplete").menu.element.children().first().focus();
            }
        }
    }).on("focus", function () {
        $(this).availableTags("search", "");
    });
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
   <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

<div class="form-group">
    <label for="test" class="col-md-3 col-lg-3 control-label"></label>
    <div class="col-md-9 col-lg-7">
        <input id="test" type="text" class="form-control" />
    </div>
</div></code>```

Body:
 var availableTags = [
    "ActionScript",
    "AppleScript",
    "Asp",
    "BASIC",
    "C",
    "C++",
    "Clojure",
    "COBOL",
    "ColdFusion",
    "Erlang",
    "Fortran",
    "Groovy",
    "Haskell",
    "Java",
    "JavaScript",
    "Lisp",
    "Perl",
    "PHP",
    "Python",
    "Ruby",
    "Scala",
    "Scheme"];

    $("#test").autocomplete({
        minLength: 0,
        source: availableTags,
        autoFocus: true,
        select: function (event, ui) {
            if (ui.item) {
                event.preventDefault();
                $(this).val(ui.item.label);
            }
        },
        open: function (event, ui) {
            var menu = $(this).data("uiAutocomplete").menu;
            var items = $('li', menu.element);

            for (var i = 0; i < items.length; i++) {
                if (items.eq(i).text().startsWith($(this).val())) {
                    menu.focus(null, items.eq(i));
                    break;
                }
            }
        },
        focus: function (event, ui) {
            event.preventDefault();
            if ($(this).val() == "" && !event.keyCode) {
                //debugger;
                $('.ui-menu-item a').removeClass('ui-state-focus');
            }
            else {
                //$(this).data("uiAutocomplete").menu.element.children().first().focus();
            }
        }
    }).on("focus", function () {
        $(this).autocomplete("search", "");
    });

        <input id="test" type="text" class="form-control" />

While tabbing through the page, inputs with autocomplete are filling out by default with the first option in dropdown. If I set minLength = 1, problem solved. However, I have to keep minLength = 0 in order to pop up the dropdown when the input is focused.

One thought is that removing the focus class when first popping up the dropdown. But the problem is when I press the arrowdown, the second option is focused instead of the first one.

I cannot find any solution to manually focus the first option. Please help.

Any other solutions are more than welcome. Thanks in advance.

Body:
You Need to change .autocomplete to .availableTags in last part of your js.I hope this will help you

$( function() {
var availableTags = [
    "ActionScript",
    "AppleScript",
    "Asp",
    "BASIC",
    "C",
    "C++",
    "Clojure",
    "COBOL",
    "ColdFusion",
    "Erlang",
    "Fortran",
    "Groovy",
    "Haskell",
    "Java",
    "JavaScript",
    "Lisp",
    "Perl",
    "PHP",
    "Python",
    "Ruby",
    "Scala",
    "Scheme"];

    $("#test").autocomplete({
        minLength: 0,
        source: availableTags,
        autoFocus: true,
        select: function (event, ui) {
            if (ui.item) {
                event.preventDefault();
                $(this).val(ui.item.label);
            }
        },
        open: function (event, ui) {
            var menu = $(this).data("uiAutocomplete").menu;
            var items = $('li', menu.element);

            for (var i = 0; i < items.length; i++) {
                if (items.eq(i).text().startsWith($(this).val())) {
                    menu.focus(null, items.eq(i));
                    break;
                }
            }
        },
        focus: function (event, ui) {
            event.preventDefault();
            if ($(this).val() == "" && !event.keyCode) {
                //debugger;
                $('.ui-menu-item a').removeClass('ui-state-focus');
            }
            else {
                //$(this).data("uiAutocomplete").menu.element.children().first().focus();
            }
        }
    }).on("focus", function () {
        $(this).availableTags("search", "");
    });
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
   <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

<div class="form-group">
    <label for="test" class="col-md-3 col-lg-3 control-label"></label>
    <div class="col-md-9 col-lg-7">
        <input id="test" type="text" class="form-control" />
    </div>
</div>


问:
How can I input values from a list or dataframe into each cell in existing excel file?
So basically, I want to update a worksheet with new data, overwriting existing cells in excel. Both files have the same column names (I do not want to create a new workbook nor add a new column).

Here I am retreiving the data that I want:

```<code>import pandas as pd
df1 = pd.read_csv
print(df1)
</code>```

Ouput (I just copy and pasted the first 5 rows, there are about 500 rows total):

```<code>          Index  Type  Stage  CDID  Period  Index Value
0     812008000     6      2  JTV9  201706      121.570
1     812008000     6      2  JTV9  201707      121.913
2     812008000     6      2  JTV9  201708      121.686
3     812008000     6      2  JTV9  201709      119.809
4     812008000     6      2  JTV9  201710      119.841
5     812128000     6      1  K2VA  201706      122.030
</code>```

The existing excel file has the same columns (and row total) as df1, but I just want to have the 'Index' column repopulated with the new values. Let's just say it looks like this (i.e. so I want the previous values for Index to go into the corresponding column):

```<code>          Index  Type  Stage  CDID  Period  Index Value
0     512901100     6      2  JTV9  201706      121.570
1     412602034     6      2  JTV9  201707      121.913
2     612307802     6      2  JTV9  201708      121.686
3     112808360     6      2  JTV9  201709      119.809
4     912233066     6      2  JTV9  201710      119.841
5     312128003     6      1  K2VA  201706      122.030
</code>```

Here I am retrieving the excel file, and attempting to overwrite it:

```<code>from win32com.client import Dispatch
import os

xl = Dispatch("Excel.Application")
xl.Visible = True

wbs_path = ('folder path')

for wbname in os.listdir(wbs_path):
    if not wbname.endswith("file name.xlsx"):
        continue
    wb = xl.Workbooks.Open(wbs_path + '\\' + wbname)
    sh = wb.Worksheets("sheet name")
    sh.Range("A1:A456").Value = df1[["Index"]]
    wb.Save()
    wb.Close()
xl.Quit()
</code>```

But this doesn't do anything.
If I type in strings, such as:

```<code>h.Range("A1:A456").Value = 'o', 'x', 'c'
</code>```

This repeats o in cells through A1 through to A456 (it updates the spreadsheet), but ignores x and c. I have tried converting df1 into a list and numpy array, but this doesn't work.

Does anyone know a solution or alternative workaround?

答:
If the index of the dataframe is the same you can update columns by using update(). It could work like this:

```<code>df1.update(df2['Index'].to_frame())
</code>```

Note: the to frame() is probably not needed

EDIT:

Since you try to update a excel-file and not a dataframe, my answer is probably not enough.
For this part I would suggest to load the file into a dataframe, update the data and save it.

```<code>df1 = pd.read_excel('file.xlsx', sheet_name='sheet_name')

# do the update

writer = pd.ExcelWriter('file.xlsx')
df1.to_excel(writer,sheet_name='sheet_name', engine='xlsxwriter')
writer.save()
</code>```

Body:
So basically, I want to update a worksheet with new data, overwriting existing cells in excel. Both files have the same column names (I do not want to create a new workbook nor add a new column).

Here I am retreiving the data that I want:

import pandas as pd
df1 = pd.read_csv
print(df1)

Ouput (I just copy and pasted the first 5 rows, there are about 500 rows total):

          Index  Type  Stage  CDID  Period  Index Value
0     812008000     6      2  JTV9  201706      121.570
1     812008000     6      2  JTV9  201707      121.913
2     812008000     6      2  JTV9  201708      121.686
3     812008000     6      2  JTV9  201709      119.809
4     812008000     6      2  JTV9  201710      119.841
5     812128000     6      1  K2VA  201706      122.030

The existing excel file has the same columns (and row total) as df1, but I just want to have the 'Index' column repopulated with the new values. Let's just say it looks like this (i.e. so I want the previous values for Index to go into the corresponding column):

          Index  Type  Stage  CDID  Period  Index Value
0     512901100     6      2  JTV9  201706      121.570
1     412602034     6      2  JTV9  201707      121.913
2     612307802     6      2  JTV9  201708      121.686
3     112808360     6      2  JTV9  201709      119.809
4     912233066     6      2  JTV9  201710      119.841
5     312128003     6      1  K2VA  201706      122.030

Here I am retrieving the excel file, and attempting to overwrite it:

from win32com.client import Dispatch
import os

xl = Dispatch("Excel.Application")
xl.Visible = True

wbs_path = ('folder path')

for wbname in os.listdir(wbs_path):
    if not wbname.endswith("file name.xlsx"):
        continue
    wb = xl.Workbooks.Open(wbs_path + '\\' + wbname)
    sh = wb.Worksheets("sheet name")
    sh.Range("A1:A456").Value = df1[["Index"]]
    wb.Save()
    wb.Close()
xl.Quit()

But this doesn't do anything.
If I type in strings, such as:

h.Range("A1:A456").Value = 'o', 'x', 'c'

This repeats o in cells through A1 through to A456 (it updates the spreadsheet), but ignores x and c. I have tried converting df1 into a list and numpy array, but this doesn't work.

Does anyone know a solution or alternative workaround?

Body:
If the index of the dataframe is the same you can update columns by using update(). It could work like this:

df1.update(df2['Index'].to_frame())

Note: the to frame() is probably not needed

EDIT:

Since you try to update a excel-file and not a dataframe, my answer is probably not enough.
For this part I would suggest to load the file into a dataframe, update the data and save it.

df1 = pd.read_excel('file.xlsx', sheet_name='sheet_name')

# do the update

writer = pd.ExcelWriter('file.xlsx')
df1.to_excel(writer,sheet_name='sheet_name', engine='xlsxwriter')
writer.save()


答:
From the code you've shared, the 'msg' variable is an object
{msg: 'hi'}, so you've to access the property to display the string.

```<code>                {
                    msg ?
                            <div>{msg.msg}</div> :
                            <div>Nothing</div>
                }
</code>```

Cleaner way would be to use ES6 destructuring.

```<code>function Message({msg}) {
.
.
{
    msg ?
        <div>{msg}</div> :
        <div>Nothing</div>
}
.
.
</code>```

Body:
In my component I have :

function Message(msg) {
        //console.log('msg=', msg);
        return (

                    {
                        msg ?

{msg}
 :

Nothing

                    }

        )
    }

When I try to render this component in my IDE I get this chromeconsole-error:

Uncaught Error: Objects are not valid as a React child (found: object
  with keys {msg}). If you meant to render a collection of children, use
  an array instead.

How can I display the msg value ie 'hi' in my component?
fiddle

Body:
From the code you've shared, the 'msg' variable is an object
{msg: 'hi'}, so you've to access the property to display the string.

                {
                    msg ?
                            <div>{msg.msg}</div> :
                            <div>Nothing</div>
                }

Cleaner way would be to use ES6 destructuring.

function Message({msg}) {
.
.
{
    msg ?
        <div>{msg}</div> :
        <div>Nothing</div>
}
.
.


问:
Making a Minute Rate Metric in Netflix Servo
I want to convert the StepCounter from doing the rates based on seconds to rate per minute (we have a monitor that runs every minute).

When I try to switch them polling from 1 per second to once every 60 seconds, it will, instead, take the increment value and divide it by 60 and create an rate per second.

Anyone have an idea of how to expose a JMX value via Netflix Servo package to do a 60s metric instead? There's CounterToRateMetricTransform but there are no examples on how to convert a Counter metric to a Rate.

答:
StepCounter is an individual metric, but CounterToRateMetricTransform is applied to a MetricObserver, and returns a new observer that observes all counters transformed as rates

e.g. to create an observer that observes counters as rates and add it to a pollrunnable task

```<code>MetricObserver observer = new CloudWatchMetricObserver(...) // existing observer
MetricObserver transformedObserver = new CounterToRateMetricTransform(observer, 60, TimeUnit.SECONDS);
PollRunnable task = new PollRunnable(..., Immutable.listOf(transformedObserver));
</code>```

Unfortunately this transform also returns a rate per second (see CounterToRateMetricTransform.computeRate)

There's no way to get a per minute rate through the existing library as far as I can see, you'd need to either implement your own metric (like StepCounter) or your own transform on an observer (like CounterToRateMetricTransform) depending on your use case.

The best approach is probably just to take the per second rate and multiply it by 60 in your monitoring system rather than changing the reporting

Body:
StepCounter is an individual metric, but CounterToRateMetricTransform is applied to a MetricObserver, and returns a new observer that observes all counters transformed as rates

e.g. to create an observer that observes counters as rates and add it to a pollrunnable task

MetricObserver observer = new CloudWatchMetricObserver(...) // existing observer
MetricObserver transformedObserver = new CounterToRateMetricTransform(observer, 60, TimeUnit.SECONDS);
PollRunnable task = new PollRunnable(..., Immutable.listOf(transformedObserver));

Unfortunately this transform also returns a rate per second (see CounterToRateMetricTransform.computeRate)

There's no way to get a per minute rate through the existing library as far as I can see, you'd need to either implement your own metric (like StepCounter) or your own transform on an observer (like CounterToRateMetricTransform) depending on your use case.

The best approach is probably just to take the per second rate and multiply it by 60 in your monitoring system rather than changing the reporting


问:
Replace static JSON data with $HTTP request in AngularJS factory
Have some troubles with replacing static JSON data in AngularJS factory, here is example with static data:

```<code>    angular.module('starter.services', [])
    .factory('catgs', function($http) {
      var catgs = [{
        id: 19,
        name: 'CATG20'
},{
        id: 20,
        name: 'CATG21'
      }];
      return {
        all: function() {
          return catgs;
        },
        remove: function(catg) {
          catgs.splice(catgs.indexOf(catg), 1);
        },
        get: function(catgId) {
          for (var i = 0; i < catgs.length; i++) {
            if (catgs[i].id === parseInt(catgId)) {
              return catgs[i];
            }
          }
          return null;
        }
      };
    });
</code>```

Need replace static var catgs with $http.get from json data url. I'm new in Angular and need help with this issue.

答:
you are looking for something like this</p>

```<code>function getStuff() {

        return $http({
            method: 'POST',
            url: '/yourresturl'
        }).then(function successCallback(response) {

            return response;
        }, function errorCallback(response) {
            return ;
           //do something
        });

    }
</code>```

Body:
Have some troubles with replacing static JSON data in AngularJS factory, here is example with static data:

    angular.module('starter.services', [])
    .factory('catgs', function($http) {
      var catgs = [{
        id: 19,
        name: 'CATG20'
},{
        id: 20,
        name: 'CATG21'
      }];
      return {
        all: function() {
          return catgs;
        },
        remove: function(catg) {
          catgs.splice(catgs.indexOf(catg), 1);
        },
        get: function(catgId) {
          for (var i = 0; i < catgs.length; i++) {
            if (catgs[i].id === parseInt(catgId)) {
              return catgs[i];
            }
          }
          return null;
        }
      };
    });

Need replace static var catgs with $http.get from json data url. I'm new in Angular and need help with this issue.

Body:
you are looking for something like this

function getStuff() {

        return $http({
            method: 'POST',
            url: '/yourresturl'
        }).then(function successCallback(response) {

            return response;
        }, function errorCallback(response) {
            return ;
           //do something
        });

    }


问:
How can I sum strings in one column into one row in Microsoft SQL? Group by does not work since it is MSSQL
for example we have table with three columns

```<code>Column A |  Column B | Column C
-------------------------------
P1       |    10     |    A
P1       |    20     |    B
P1       |    30     |    C
P2       |    30     |    D
P2       |    40     |    E
</code>```

How do I have to write SELECT query in Microsoft SQL to have this kind of result

```<code>Column A |     Column B      |   Column C
------------------------------------------
P1       |    10, 20, 30     |    A, B, C
P2       |    30, 40         |    D, E
</code>```

答:
try this

```<code>CREATE TABLE #temp(ColumnA VARCHAR(10),ColumnB INT ,ColumnC VARCHAR(10))
--insert rows

SELECT t.[ColumnA] ,
         [ColumnB] = STUFF((SELECT  ','+cast([ColumnB] AS VARCHAR ) FROM  #Temp WHERE  [ColumnA]  = t.[ColumnA]  FOR XML PATH('')),1,1,''),
         [ColumnC] = STUFF((SELECT  ','+[ColumnC] FROM #Temp WHERE [ColumnA] = t.[ColumnA] FOR XML PATH('')),1,1,'')
FROM #Temp t
GROUP BY t.[ColumnA]
</code>```

i test it

Body:
for example we have table with three columns

Column A |  Column B | Column C
-------------------------------
P1       |    10     |    A
P1       |    20     |    B
P1       |    30     |    C
P2       |    30     |    D
P2       |    40     |    E

How do I have to write SELECT query in Microsoft SQL to have this kind of result

Column A |     Column B      |   Column C
------------------------------------------
P1       |    10, 20, 30     |    A, B, C
P2       |    30, 40         |    D, E

Body:
try this

CREATE TABLE #temp(ColumnA VARCHAR(10),ColumnB INT ,ColumnC VARCHAR(10))
--insert rows

SELECT t.[ColumnA] ,
         [ColumnB] = STUFF((SELECT  ','+cast([ColumnB] AS VARCHAR ) FROM  #Temp WHERE  [ColumnA]  = t.[ColumnA]  FOR XML PATH('')),1,1,''),
         [ColumnC] = STUFF((SELECT  ','+[ColumnC] FROM #Temp WHERE [ColumnA] = t.[ColumnA] FOR XML PATH('')),1,1,'')
FROM #Temp t
GROUP BY t.[ColumnA]

i test it


答:
Trivia

Your suspicion was correct. Redraw/Render time increases because you leak memory by stacking objects (they're don't disappear on each iteration, they're kept in memory) and because tkinter redraws them all at the same time. From that point I think that the solution is clear.

Answer

Sure it can be avoided.

There's two options:

If all you need is just to animate one object - you can simply move one (and redraw one) object at the time.

Consider this example:

```<code>import tkinter as tk

class App(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.canvas = tk.Canvas()
        self.canvas.pack()
        self.canvas.create_rectangle(0, 0, self.canvas["width"], self.canvas["height"], fill=self.canvas["background"])
        self.text = self.canvas.create_text(100, 1, text="Python 3.6!", fill="red")
        self.step = 3
        self.simulate_things()

    def simulate_things(self):
        if 0 <= self.canvas.coords(self.text)[1] + self.step <= self.canvas.winfo_height():
            # no need to change direction - still inside canvas
            pass
        else:
            # switch direction
            self.step *= -1

        # you can use coords method as alternative
        self.canvas.move(self.text, 0, self.step)

        # scheduling next move
        self.after(41, self.simulate_things)

if __name__ == '__main__':
    app = App()
    app.mainloop()
</code>```

If there's any idea behind of multiple objects - you can switch their state to hidden/disabled (it's also more optimal way than deleting of the object, because we reduce id/item managing to a minimum). That option will tell tkinter not to redraw them.
However, you need to track objects, which are already created to prevent a memory leak!

Consider this example:

```<code>import tkinter as tk

class App(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.canvas = tk.Canvas()
        self.canvas.pack()
        self.canvas.create_rectangle(0, 0, self.canvas["width"], self.canvas["height"], fill=self.canvas["background"])
        self.texts = {}
        self.i = 1
        self.step = 3
        self.simulate_things()

    def simulate_things(self):
        if self.i in self.texts:
            # hide previous object (if exists)
            self.canvas.itemconfigure(self.texts[self.i], state='hidden')

        if 0 <= self.i + self.step <= self.canvas.winfo_height():
            # no need to change direction - still inside canvas
            pass
        else:
            # switch direction
            self.step *= -1

        self.i += self.step

        if self.i in self.texts:
            # show hidden object for a step (if exists)
            self.canvas.itemconfigure(self.texts[self.i], state='normal')
        else:
            # or create a new one
            self.texts[self.i] = self.canvas.create_text(100, self.i, text="Python 3.6!", fill="red")

        # scheduling next move
        self.after(41, self.simulate_things)

if __name__ == '__main__':
    app = App()
    app.mainloop()
</code>```

As you can see - your main goal in managing perfomance is to decrease the amount of redrawings (and to keep the amount of objects at minimum).

Links

Canvas
widget

Methods on Canvas widgets

Tk Canvas documentation

Tk Perfomance

Title: Render time increasing with time

Body:
Trivia

Your suspicion was correct. Redraw/Render time increases because you leak memory by stacking objects (they're don't disappear on each iteration, they're kept in memory) and because tkinter redraws them all at the same time. From that point I think that the solution is clear.

Answer

Sure it can be avoided.

There's two options:

If all you need is just to animate one object - you can simply move one (and redraw one) object at the time.

Consider this example:

import tkinter as tk

class App(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.canvas = tk.Canvas()
        self.canvas.pack()
        self.canvas.create_rectangle(0, 0, self.canvas["width"], self.canvas["height"], fill=self.canvas["background"])
        self.text = self.canvas.create_text(100, 1, text="Python 3.6!", fill="red")
        self.step = 3
        self.simulate_things()

    def simulate_things(self):
        if 0 <= self.canvas.coords(self.text)[1] + self.step <= self.canvas.winfo_height():
            # no need to change direction - still inside canvas
            pass
        else:
            # switch direction
            self.step *= -1

        # you can use coords method as alternative
        self.canvas.move(self.text, 0, self.step)

        # scheduling next move
        self.after(41, self.simulate_things)

if __name__ == '__main__':
    app = App()
    app.mainloop()

If there's any idea behind of multiple objects - you can switch their state to hidden/disabled (it's also more optimal way than deleting of the object, because we reduce id/item managing to a minimum). That option will tell tkinter not to redraw them.
However, you need to track objects, which are already created to prevent a memory leak!

Consider this example:

import tkinter as tk

class App(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.canvas = tk.Canvas()
        self.canvas.pack()
        self.canvas.create_rectangle(0, 0, self.canvas["width"], self.canvas["height"], fill=self.canvas["background"])
        self.texts = {}
        self.i = 1
        self.step = 3
        self.simulate_things()

    def simulate_things(self):
        if self.i in self.texts:
            # hide previous object (if exists)
            self.canvas.itemconfigure(self.texts[self.i], state='hidden')

        if 0 <= self.i + self.step <= self.canvas.winfo_height():
            # no need to change direction - still inside canvas
            pass
        else:
            # switch direction
            self.step *= -1

        self.i += self.step

        if self.i in self.texts:
            # show hidden object for a step (if exists)
            self.canvas.itemconfigure(self.texts[self.i], state='normal')
        else:
            # or create a new one
            self.texts[self.i] = self.canvas.create_text(100, self.i, text="Python 3.6!", fill="red")

        # scheduling next move
        self.after(41, self.simulate_things)

if __name__ == '__main__':
    app = App()
    app.mainloop()

As you can see - your main goal in managing perfomance is to decrease the amount of redrawings (and to keep the amount of objects at minimum).

Links

Canvas
widget

Methods on Canvas widgets

Tk Canvas documentation

Tk Perfomance

ContentLicense: CC BY-SA 4.0


问:
filtering in an ng-repeat from JSON response
I've got a question about filtering within a ng-repeat. But this isn't a simple question since I'm not really having a problem that needs a solution. In this case, I'm looking for the best possible answer that doesn't require a lot of code but still does the trick as to how I want it to. It will become more clear in my description.

a short introduction:

So I'm currently working on a shopping application. The shopping application has a connection with an existing PrestaShop webshop through the web service API. A rest API for PrestaShop. So after creating a customer section, products section, and a cart system, I would like to be able to update the "stock amount" of each product within the application. Many people would tell me: Well that's easy, just create a form with ng-repeat response data from the database and the possibility of updating the stock on let's say a button ng-click event.

Well I've done that but now the tricky part, and to explain I will provide some less important examples to make it more clear of what I'm asking:

The prestashop database

The prestashop database is a database that exists of over 250 tables. Among those tables are various connections through id's and attribute id's. Some simple examples are:

The customer table has an id_address row which connects to the address table. Within this table, all the 'customersaddress info is placed. So far, let's say updating a customer I've created a combination of update thecustomertable with thecustomer_idbut also update theaddresstable where theaddress_idis equal to theid_addressfrom the selectedcustomerwithin thecustomer` table.

Products also have some linked tables. Think about prices, taxes, sizes, and colors. The id_product_attribute is an attribute_id that could correspond to a color or size.

As explained above the prestashop database structure is very detailed which confines to using various filters for showing the wanted data.

Using the webservice

So for using the webservice I'm using a combination of angularJS, javascript, php, and JSON. The JSON is the actual data. by using $http.get(url, options) I'm able to get the data from the database. Then for showing the data I'm using response. A example is shown below:

```<code>$http.get('config/get/getCustomers.php', { cache: true }).then(function (response) {
    $scope.customers = response.data.customers.customer
});
</code>```

using $scope.customers = response.data.customers.customer gives me the option to show the customer data by using, for example, a ng-repeat as in the example below

    $http.get('config/get/getCustomers.php', { cache: true }).then(function (response) {
        $scope.customers = response.data.customers.customer
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="row listrow" ng-repeat="customer in customers | orderBy: customer.id">
        <div class="col-lg-8">
            <p class="customer" ng-bind="customer.id + ' ' + customer.firstname + ' ' + customer.lastname">
      </p>
        </div>
</div></code>```

In this case, the response would be empty since there is no database connection. To create a full example for testing here is some JSON data you could use from the customers table.

```<code>{"customers":{"customer":[{"id":"1","id_default_group":"0","id_lang":"0","newsletter_date_add":"0000-00-00 00:00:00","ip_registration_newsletter":{},"last_passwd_gen":"2017-10-30 09:27:03","secure_key":{},"deleted":"0","passwd":"$2y$10$eZvPTD9bkxwSfWN7qovrmee\/Den2TqZ5a6YjcGC\/lha3oU59MCjOO","lastname":"TestStefans","firstname":"John","email":"pub@prestashop.com","id_gender":"0","birthday":"0000-00-00","newsletter":"0","optin":"0","website":{},"company":{},"siret":{},"ape":{},"outstanding_allow_amount":"0.000000","show_public_prices":"0","id_risk":"0","max_payment_days":"0","active":"1","note":{},"is_guest":"0","id_shop":"1","id_shop_group":"1","date_add":"2017-04-26 14:01:31","date_upd":"2017-10-27 15:56:54","reset_password_token":{},"reset_password_validity":"0000-00-00 00:00:00","associations":{"groups":{"@attributes":{"nodeType":"group","api":"groups"},"group":{"id":"3"}}}},{"id":"2","id_default_group":"0","id_lang":"1","newsletter_date_add":"0000-00-00 00:00:00","ip_registration_newsletter":{},"last_passwd_gen":"2017-10-27 15:56:55","secure_key":{},"deleted":"0","passwd":"$2y$10$C8M6TIuzmZjP9kh06Hai8.XyuNG9WcSi9L34oXqAuidsJkoYog4WW","lastname":"Demoers","firstname":"Demoers","email":"demo@sdwebdesign.nl","id_gender":"0","birthday":"0000-00-00","newsletter":"0","optin":"0","website":{},"company":{},"siret":{},"ape":{},"outstanding_allow_amount":"0.000000","show_public_prices":"0","id_risk":"0","max_payment_days":"0","active":"1","note":{},"is_guest":"0","id_shop":"1","id_shop_group":"1","date_add":"2017-04-26 14:01:33","date_upd":"2017-10-27 15:56:55","reset_password_token":{},"reset_password_validity":"0000-00-00 00:00:00","associations":{"groups":{"@attributes":{"nodeType":"group","api":"groups"},"group":{"id":"3"}}}}]}}
</code>```

So with this information here is my question:

While working on the application the following data is given within the stock_availables table.

So while using the $http.get() and the response functions I was able to create a form for updating the stock. But now take a look at the id_product_attribute. This row corresponds to a product_attribute. In this case a size or color. Now I would like to filter these results. In this case by using for example ng-if="id_product_attribute == 0" I'm able to filter in a way that only all with this id_attribute are shown. But I would like to show all of them. So also with id="1", id="2", etc. But there is where I'm wondering, is there a way to do this in a sufficient way that wouldn't require a ng-if for each id? Since there are around 50 different id_attribute's which each corresponds to a color or size. So is there a function that could get each different id and filter that in a sufficient way than using many ng-if clauses. Look at the following full code as an example.

myApp.controller('ProductsController', function($scope, $http){

    $http.get('config/get/getProducts.php', {cache: true}).then(function(response){
        $scope.products = response.data.products.product
    });
    // Stock check + view
    $http.get('config/get/getStock.php', {cache: true}).then(function (response) {
        $scope.stock_availables = response.data.stock_availables.stock_available
    });

// Update Stock
    $scope.updateStock = function(stock_available) {

        var stock_id = stock_available.id;
        var product_id = stock_available.id_product;
        var stock_quantity = stock_available.quantity;

        console.log(stock_id + product_id + stock_quantity);

        // Post to the database //

    };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="row listrow">
        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <ng-form name="stock">
                <div ng-repeat="stock_available in stock_availables">
                    <div class="row full-width padding-tb-15" ng-if="stock_available.id_product == product.id  && stock_available.id_product_attribute == 0" ng-repeat="product in products">
                        <div class="col-lg-12 form-stock-group hidden">
                            <input title="id" type="text" name="stockId" class="form-control" aria-describedby="" ng-value="stock_available.id">
                        </div>
                        <div class="col-lg-4">
                            <h5 ng-bind="product.name.language"></h5>
                        </div>
                        <div class="col-lg-3">
                            <h5 ng-bind="product.ean13"></h5>
                        </div>
                        <div class="col-lg-2">
                            <h5 ng-bind="product.reference"></h5>
                        </div>
                        <div ng-if="stock_available.id_product == product.id && stock_available.id_product_attribute == 0" ng-repeat="stock_available in stock_availables" class="col-lg-1 text-center">
                            <input title="stock_id" type="text" name="stock_id" class="form-control hidden" aria-describedby=""  ng-model="stock_available.id" ng-value="stock_available.id">
                            <input title="stock_id_product" type="text" name="stock_id_product" class="form-control hidden" aria-describedby="" ng-model="stock_available.id_product" ng-value="stock_available.id_product">
                            <h5 title="quantity" name="stockQuantity" aria-describedby="" ng-model="stock_available.quantity" ng-bind="stock_available.quantity"></h5>
                        </div>
                        <div ng-if="stock_available.id_product == product.id && stock_available.id_product_attribute == 0" ng-repeat="stock_available in stock_availables" class="col-lg-1 text-center">
                            <input title="updateStockAmount" class="form-control form-control-stock" type="number">
                        </div>
                        <div class="col-lg-1 text-center">

                                <i class="fa fa-print" aria-hidden="true"></i>

                        </div>
                    </div>
                </div>
            </ng-form>
        </div>
    </div></code>```

I trying to create the following view:

Product-id 1: then all sizes, colors, etc.

Product-id 2: then all sizes, colors, etc.

Yes it is possible with writing 50 different ng-if statements but I'm asking if there is a better, easier and more sufficient way to do this?

A simple build of the dummy code can be found here

As always,

Thanks in advance!

答:
Maybe you should ask yourself what part of your application have the responsibility of sorting those attributes. This could lead to a more obvious solution for you.
If the responsibility goes to the API, then either your request or your API should return a ready-to-use JSON for your WebApp.
If the responsibility goes to the front WebApp, either do it in the js code or in the template.

My guess is that your API should do that, in which case i may not be the most advisor.
But if you decide to do this in the WebApp, I definitely think that you should not use ngIf to do that, but instead build Pure Functions in your JS to build one or several array that you will be able to use with not too much of functionnaly code in your template.

For example you could .map() your response and return a well iterable object, and/or chained it with a .concat() or whatever. If you need ideas to build such functions check those example http://reactivex.io/learnrx/

Body:
I've got a question about filtering within a ng-repeat. But this isn't a simple question since I'm not really having a problem that needs a solution. In this case, I'm looking for the best possible answer that doesn't require a lot of code but still does the trick as to how I want it to. It will become more clear in my description.

a short introduction:

So I'm currently working on a shopping application. The shopping application has a connection with an existing PrestaShop webshop through the web service API. A rest API for PrestaShop. So after creating a customer section, products section, and a cart system, I would like to be able to update the "stock amount" of each product within the application. Many people would tell me: Well that's easy, just create a form with ng-repeat response data from the database and the possibility of updating the stock on let's say a button ng-click event.

Well I've done that but now the tricky part, and to explain I will provide some less important examples to make it more clear of what I'm asking:

The prestashop database

The prestashop database is a database that exists of over 250 tables. Among those tables are various connections through id's and attribute id's. Some simple examples are:

The customer table has an id_address row which connects to the address table. Within this table, all the 'customersaddress info is placed. So far, let's say updating a customer I've created a combination of update thecustomertable with thecustomer_idbut also update theaddresstable where theaddress_idis equal to theid_addressfrom the selectedcustomerwithin thecustomer` table.

Products also have some linked tables. Think about prices, taxes, sizes, and colors. The id_product_attribute is an attribute_id that could correspond to a color or size.

As explained above the prestashop database structure is very detailed which confines to using various filters for showing the wanted data.

Using the webservice

So for using the webservice I'm using a combination of angularJS, javascript, php, and JSON. The JSON is the actual data. by using $http.get(url, options) I'm able to get the data from the database. Then for showing the data I'm using response. A example is shown below:

$http.get('config/get/getCustomers.php', { cache: true }).then(function (response) {
    $scope.customers = response.data.customers.customer
});

using $scope.customers = response.data.customers.customer gives me the option to show the customer data by using, for example, a ng-repeat as in the example below

    $http.get('config/get/getCustomers.php', { cache: true }).then(function (response) {
        $scope.customers = response.data.customers.customer
    });

In this case, the response would be empty since there is no database connection. To create a full example for testing here is some JSON data you could use from the customers table.

{"customers":{"customer":[{"id":"1","id_default_group":"0","id_lang":"0","newsletter_date_add":"0000-00-00 00:00:00","ip_registration_newsletter":{},"last_passwd_gen":"2017-10-30 09:27:03","secure_key":{},"deleted":"0","passwd":"$2y$10$eZvPTD9bkxwSfWN7qovrmee\/Den2TqZ5a6YjcGC\/lha3oU59MCjOO","lastname":"TestStefans","firstname":"John","email":"pub@prestashop.com","id_gender":"0","birthday":"0000-00-00","newsletter":"0","optin":"0","website":{},"company":{},"siret":{},"ape":{},"outstanding_allow_amount":"0.000000","show_public_prices":"0","id_risk":"0","max_payment_days":"0","active":"1","note":{},"is_guest":"0","id_shop":"1","id_shop_group":"1","date_add":"2017-04-26 14:01:31","date_upd":"2017-10-27 15:56:54","reset_password_token":{},"reset_password_validity":"0000-00-00 00:00:00","associations":{"groups":{"@attributes":{"nodeType":"group","api":"groups"},"group":{"id":"3"}}}},{"id":"2","id_default_group":"0","id_lang":"1","newsletter_date_add":"0000-00-00 00:00:00","ip_registration_newsletter":{},"last_passwd_gen":"2017-10-27 15:56:55","secure_key":{},"deleted":"0","passwd":"$2y$10$C8M6TIuzmZjP9kh06Hai8.XyuNG9WcSi9L34oXqAuidsJkoYog4WW","lastname":"Demoers","firstname":"Demoers","email":"demo@sdwebdesign.nl","id_gender":"0","birthday":"0000-00-00","newsletter":"0","optin":"0","website":{},"company":{},"siret":{},"ape":{},"outstanding_allow_amount":"0.000000","show_public_prices":"0","id_risk":"0","max_payment_days":"0","active":"1","note":{},"is_guest":"0","id_shop":"1","id_shop_group":"1","date_add":"2017-04-26 14:01:33","date_upd":"2017-10-27 15:56:55","reset_password_token":{},"reset_password_validity":"0000-00-00 00:00:00","associations":{"groups":{"@attributes":{"nodeType":"group","api":"groups"},"group":{"id":"3"}}}}]}}

So with this information here is my question:

While working on the application the following data is given within the stock_availables table.

So while using the $http.get() and the response functions I was able to create a form for updating the stock. But now take a look at the id_product_attribute. This row corresponds to a product_attribute. In this case a size or color. Now I would like to filter these results. In this case by using for example ng-if="id_product_attribute == 0" I'm able to filter in a way that only all with this id_attribute are shown. But I would like to show all of them. So also with id="1", id="2", etc. But there is where I'm wondering, is there a way to do this in a sufficient way that wouldn't require a ng-if for each id? Since there are around 50 different id_attribute's which each corresponds to a color or size. So is there a function that could get each different id and filter that in a sufficient way than using many ng-if clauses. Look at the following full code as an example.

myApp.controller('ProductsController', function($scope, $http){

    $http.get('config/get/getProducts.php', {cache: true}).then(function(response){
        $scope.products = response.data.products.product
    });
    // Stock check + view
    $http.get('config/get/getStock.php', {cache: true}).then(function (response) {
        $scope.stock_availables = response.data.stock_availables.stock_available
    });

// Update Stock
    $scope.updateStock = function(stock_available) {

        var stock_id = stock_available.id;
        var product_id = stock_available.id_product;
        var stock_quantity = stock_available.quantity;

        console.log(stock_id + product_id + stock_quantity);

        // Post to the database //

    };
});

            <ng-form name="stock">

                            <input title="id" type="text" name="stockId" class="form-control" aria-describedby="" ng-value="stock_available.id">

                            <input title="stock_id" type="text" name="stock_id" class="form-control hidden" aria-describedby=""  ng-model="stock_available.id" ng-value="stock_available.id">
                            <input title="stock_id_product" type="text" name="stock_id_product" class="form-control hidden" aria-describedby="" ng-model="stock_available.id_product" ng-value="stock_available.id_product">

                            <input title="updateStockAmount" class="form-control form-control-stock" type="number">

            </ng-form>

I trying to create the following view:

Product-id 1: then all sizes, colors, etc.

Product-id 2: then all sizes, colors, etc.

Yes it is possible with writing 50 different ng-if statements but I'm asking if there is a better, easier and more sufficient way to do this?

A simple build of the dummy code can be found here

As always,

Thanks in advance!


问:
Trigger jenkins from JIRA-workflow
we have jenkins CICD automated pipelines working great. we also trigger it via REST API with build Parameters.

Now, we have JIRA dashboard having custom workflow created where developers moves or changes queue of issues/stories to "ReadyForDeployment" once development is completed.

Now here, once developer moves queue to "ReadyForDeployment" :-

JIRA should prompt for 3 fields (ENV, PACKAGE_NAME_APP and
PACKAGE_NAME_DB) those will be placed in jenkins URL like
blahblahblah/buildWithParameters?ENV=${ENV}&  PACKAGE_NAME_APP=${PACKAGE_NAME_APP}&PACKAGE_NAME_DB=${PACKAGE_NAME_DB}

Basically upon queue change,webhook should be triggered whcih
will take input/parameters from JIRA itself.

Please let me know your thoughts on this.

答:
It depends on your requirement whether its correct or not. But it can be possible to trigger jenkins from Jira useing Jira-weebhook and passing the parameters.

https://developer.atlassian.com/jiradev/jira-apis/webhooks

Title: Trigger jenkins from JIRA-workflow


问:
How to make font bold in java dialogue box?
I have this:

```<code>JOptionPane.showMessageDialog(null, " " + company1 +
            " Has Higher A Market Value\nThan " + company2,
                "Information", JOptionPane.INFORMATION_MESSAGE);
</code>```

I want to make company1 and company2 appear bold in the dialogue box. I tried using html formatting but (I suppose) obviously that did not work.

Any clues or hints?

TIA!

答:
Use HTML

```<code>JOptionPane.showMessageDialog(null, "<html> <b> Has </b>Higher A Market Value</html> ");
</code>```

If your default font doesn't support it then you can specify it like

```<code> String msg = "<html>This is how to get:<ul><li><i>italics</i> and "
        + "<li><b>bold</b> and "
        + "<li><u>underlined</u>...</ul></html>";
        JLabel label = new JLabel(msg);
        label.setFont(new Font("serif", Font.PLAIN, 14));
        JOptionPane.showConfirmDialog(null, label);
</code>```

Output:

ContentLicense: CC BY-SA 2.5

Body:
I have this:

JOptionPane.showMessageDialog(null, " " + company1 +
            " Has Higher A Market Value\nThan " + company2,
                "Information", JOptionPane.INFORMATION_MESSAGE);

I want to make company1 and company2 appear bold in the dialogue box. I tried using html formatting but (I suppose) obviously that did not work.

Any clues or hints?

TIA!

Body:
Use HTML

JOptionPane.showMessageDialog(null, "<html> <b> Has </b>Higher A Market Value</html> ");

If your default font doesn't support it then you can specify it like

 String msg = "<html>This is how to get:<ul><li><i>italics</i> and "
        + "<li><b>bold</b> and "
        + "<li><u>underlined</u>...</ul></html>";
        JLabel label = new JLabel(msg);
        label.setFont(new Font("serif", Font.PLAIN, 14));
        JOptionPane.showConfirmDialog(null, label);

Output:


问:
Error while requesting a transaction
When I requesting a CXTansaction in CXStratCallAction it showing the error message as  "Error Domain=com.apple.CallKit.error.requesttransaction Code=1 "(null)" ". Can anyone explain this Error message.

答:
From the header <CallKit/CXError.h>:

```<code>typedef NS_ERROR_ENUM(CXErrorDomainRequestTransaction, CXErrorCodeRequestTransactionError) {
    ...
    CXErrorCodeRequestTransactionErrorUnentitled = 1,
    ...
} API_AVAILABLE(ios(10.0));
</code>```

So error code 1 corresponds to CXErrorCodeRequestTransactionErrorUnentitled.

This error is usually returned when an app lacks the voip iOS App Background Mode. To fix this, open Xcode's Capabilities tab for the app target and enable the "VoIP" background mode, or add 'voip' to the UIBackgroundModes array within the app's Info.plist.

(I have filed a request in Apple's bug tracker to mention this in the documentation, Radar 35903988.)

Title: Error while requesting a transaction

Body:
From the header <CallKit/CXError.h>:

typedef NS_ERROR_ENUM(CXErrorDomainRequestTransaction, CXErrorCodeRequestTransactionError) {
    ...
    CXErrorCodeRequestTransactionErrorUnentitled = 1,
    ...
} API_AVAILABLE(ios(10.0));

So error code 1 corresponds to CXErrorCodeRequestTransactionErrorUnentitled.

This error is usually returned when an app lacks the voip iOS App Background Mode. To fix this, open Xcode's Capabilities tab for the app target and enable the "VoIP" background mode, or add 'voip' to the UIBackgroundModes array within the app's Info.plist.

(I have filed a request in Apple's bug tracker to mention this in the documentation, Radar 35903988.)


问:
Regex to match words or phrases in string but NOT match if part of a URL or inside   tags. (php)
I am aware that regex is not ideal for use with HTML strings and I have looked at the PHP Simple HTML DOM Parser but still believe this is the way to go. All the HTML tags will be generated by my forum software so they will be consistent and valid HTML.

What I am trying to do is make a plugin that will find a list of keywords (or phrases) in a string of HTML and replace them with a link I specify. For example if someone types:

```<code>I use Amazon for that.
</code>```

it would replace it with:

```<code>I use <a href="http://www.amazon.com">Amazon</a> for that.
</code>```

The problem is of course is that if "amazon" is in the URL it would also get replaced. I solved that issue with a callback function found on this site, slightly modified.

But now I still have an issue, it still replaces words between opening and closing  tags.

```<code><a href="http://www.amazon.com">My Amazon Link</a>
</code>```

It will match the "Amazon" in "My Amazon Link"

What I really need is a regex to match say "amazon" anywhere except between  and

Any ideas?

答:
Improvisation. It should link only if it is a whole word "Amazon" and not words like AmazonWorld.  </p>

```<code>$result = preg_replace('%\bAmazon(?![^<]*</a>)\b%i', '<a href="http://www.amazon.com">Amazon</a>', $subject);
</code>```

Title: Regex to match words or phrases in string but NOT match if part of a URL or inside <a> </a> tags. (php)

Body:
I am aware that regex is not ideal for use with HTML strings and I have looked at the PHP Simple HTML DOM Parser but still believe this is the way to go. All the HTML tags will be generated by my forum software so they will be consistent and valid HTML.

What I am trying to do is make a plugin that will find a list of keywords (or phrases) in a string of HTML and replace them with a link I specify. For example if someone types:

I use Amazon for that.

it would replace it with:

I use Amazon for that.

The problem is of course is that if "amazon" is in the URL it would also get replaced. I solved that issue with a callback function found on this site, slightly modified.

But now I still have an issue, it still replaces words between opening and closing  tags.

My Amazon Link

It will match the "Amazon" in "My Amazon Link"

What I really need is a regex to match say "amazon" anywhere except between <a href and

Any ideas?

Body:
Improvisation. It should link only if it is a whole word "Amazon" and not words like AmazonWorld.

$result = preg_replace('%\bAmazon(?![^<]*</a>)\b%i', '<a href="http://www.amazon.com">Amazon</a>', $subject);


问:
AND/OR operator between numbers in Python
How do and/or operators work between numbers (or even strings)?

```<code>5 and 7  # this returns 7
7 and 5  # this returns 5
21 and 4 # this returns 4
4 and 21 # this returns 21
</code>```

How does the and operator work in such cases?

答:
Let's disassemble!

```<code>>>> import dis
>>> def check_and(a, b):
...   return a and b
...
>>> dis.dis(check_and)
  2           0 LOAD_FAST                0 (a)
              3 JUMP_IF_FALSE_OR_POP     9
              6 LOAD_FAST                1 (b)
        >>    9 RETURN_VALUE
</code>```

Now it's pretty straightforward.
1. Load a to stack (It becomes TOS - Top of stack value.
2. JUMP_IF_FALSE_OR_POP tries to evaluate boolean value of TOS (Top Of Stack). If it's true, remove this value from stack, if it's not, set bytecode counter (in our case it would junmp to line 9.
3. Push b to stack.
4. Return.

I can't really tell why the evaluation order is different in the other case but as you can see the second evaluated value will be returned if first one is True.

Same happens to or and other operators. try to disassemble them yourself.

This comes handy if you want to make a quick check. Instead of writing:

```<code>def check(value)
  if value:
    return value
  else:
    return "No value"
</code>```

You can write:

```<code>def check(value):
  return value or "No value"
</code>```

Body:
How do and/or operators work between numbers (or even strings)?

5 and 7  # this returns 7
7 and 5  # this returns 5
21 and 4 # this returns 4
4 and 21 # this returns 21

How does the and operator work in such cases?

Body:
Let's disassemble!

>>> import dis
>>> def check_and(a, b):
...   return a and b
...
>>> dis.dis(check_and)
  2           0 LOAD_FAST                0 (a)
              3 JUMP_IF_FALSE_OR_POP     9
              6 LOAD_FAST                1 (b)
        >>    9 RETURN_VALUE

Now it's pretty straightforward.
1. Load a to stack (It becomes TOS - Top of stack value.
2. JUMP_IF_FALSE_OR_POP tries to evaluate boolean value of TOS (Top Of Stack). If it's true, remove this value from stack, if it's not, set bytecode counter (in our case it would junmp to line 9.
3. Push b to stack.
4. Return.

I can't really tell why the evaluation order is different in the other case but as you can see the second evaluated value will be returned if first one is True.

Same happens to or and other operators. try to disassemble them yourself.

This comes handy if you want to make a quick check. Instead of writing:

def check(value)
  if value:
    return value
  else:
    return "No value"

You can write:

def check(value):
  return value or "No value"


问:
Stop tooltip span from wrapping at each word in CSS
I have created tooltips that appear when certain links have hovered over. The tooltips are spans with the class tooltiptext, and the links use the id gloss.

The problem is that the tooltips end up being the width of the longest word inside them. I've tried setting a minimum width, but it's impractical because some of the tooltips are only a few words, whilst others are whole paragraphs. I don't want all of the text to be on the same line if there's a paragraph of text, so white-space: nowrap is impractical too.

Any ideas?

#gloss {
  border-bottom: solid 1pt blue;
  position: relative;
  display: inline-block;
  text-decoration: none;
}

#gloss:hover {
  text-decoration: none;
}

.tooltiptext {
  visibility: hidden;
  text-align:center; background-color:#8899ff;
  color: #000;
  border-radius: 6px;
  box-shadow: 2px 2px 1px #aaa;
  border: 1px solid #000;
  padding: 5px;
  position: absolute;
  z-index: 1;
  bottom: 125%;
  left: 50%;
  margin-left: -60px;
  opacity: 0;
  transition: all 0.15s ease;
  pointer-events: none;
}

#gloss:hover .tooltiptext {
  visibility: visible;
  opacity: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><br><br><br><br><br>
<!--<br>s to move the paragraph down-->
<p>This is some text, with a link<span class="tooltiptext">Here is some information about the link.</span>. And the text continues.</p></code>```

答:
add style="width: auto;" in to your span tag it will work

```<code><br><br><br><br><br>
<!--<br>s to move the paragraph down-->
<p>This is some text, with a <a href="#" id="gloss">link<span style="width: auto;" class="tooltiptext">Here is some information about the link</span></a>. And the text continues.</p>
</code>```

Body:
I have created tooltips that appear when certain links have hovered over. The tooltips are spans with the class tooltiptext, and the links use the id gloss.

The problem is that the tooltips end up being the width of the longest word inside them. I've tried setting a minimum width, but it's impractical because some of the tooltips are only a few words, whilst others are whole paragraphs. I don't want all of the text to be on the same line if there's a paragraph of text, so white-space: nowrap is impractical too.

Any ideas?

#gloss {
  border-bottom: solid 1pt blue;
  position: relative;
  display: inline-block;
  text-decoration: none;
}

#gloss:hover {
  text-decoration: none;
}

.tooltiptext {
  visibility: hidden;
  text-align:center; background-color:#8899ff;
  color: #000;
  border-radius: 6px;
  box-shadow: 2px 2px 1px #aaa;
  border: 1px solid #000;
  padding: 5px;
  position: absolute;
  z-index: 1;
  bottom: 125%;
  left: 50%;
  margin-left: -60px;
  opacity: 0;
  transition: all 0.15s ease;
  pointer-events: none;
}

#gloss:hover .tooltiptext {
  visibility: visible;
  opacity: 1;
}

This is some text, with a linkHere is some information about the link.. And the text continues.

Body:
add style="width: auto;" in to your span tag it will work

<br><br><br><br><br>
<!--<br>s to move the paragraph down-->
<p>This is some text, with a <a href="#" id="gloss">link<span style="width: auto;" class="tooltiptext">Here is some information about the link</span></a>. And the text continues.</p>