问:
how to get average of certain column values in table
I'm a beginner so I'm not sure whats wrong here. What im trying to achieve is to check if certain cells in a table (column) has numerical values in them and if they do include them in calculating the average value upon losing focus (blur) so that it would kind of be real time.

I'm not sure if calculation function is wrong itself, or if I'm addressing wrong column maybe or trying to insert calculated value in the wrong way. help would be appreciated.

Here is JSfiddle and the code excerpts:
https://jsfiddle.net/NulisDefo/03rn7ew1/5/

table

```<code><table id="myTable" class="table table-inverse">
    <thead id = "headings" class = "thead-default">
      <tr>
        <th>Tabelio Nr.</th>
        <th>Vardas</th>
        <th>Pavardė</th>
        <th>Pareigos</th>
        <th>Bazinė alga, €</th>
        <th>Valandinis atlyginimas, €</th>
        <th>Veiksmai</th>
      </tr>
    </thead>
    <tfoot class = "thead-default">
      <tr>
        <td colspan = "4">Vidurkis</td>
        <!-- <td></td>
        <td></td>
        <td></td> -->
        <td id = "alga">0</td>
        <td id = "valandinis" colspan = "2">0</td>
        <!-- <td></td> -->
      </tr>
    </tfoot>
    <tbody>
      <tr>
        <td>1</td>
        <td>Mark</td>
        <td>Otto</td>
        <td>@mdo</td>
        <td>1000</td>
        <td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
        <td>
          <p class = "btn editbtn"><span class = "fa fa-edit"></span></p>
          <p class = "btn" onclick="deleteRow(this)"><span class = "fa fa-trash"></span></p>
        </td>
      </tr>
      <tr>
        <td>2</td>
        <td>Jacob</td>
        <td>Thornton</td>
        <td>@fat</td>
        <td>2000</td>
        <td>blum</td>
        <td>
          <p class = "btn editbtn"><span class = "fa fa-edit"></span></p>
          <p class = "btn" onclick="deleteRow(this)"><span class = "fa fa-trash"></span></p>
        </td>
      </tr>
      <tr class = "testas">
        <td>3</td>
        <td>Larry</td>
        <td>the Bird</td>
        <td>@twitter</td>
        <td>5000</td>
        <td>blum</td>
        <td>
          <p class = "btn editbtn"><span class = "fa fa-edit"></span></p>
          <p class = "btn" onclick="deleteRow(this)"><span class = "fa fa-trash"></span></p>
        </td>
      </tr>
    </tbody>
  </table>
</code>```

script for calculating and trigger

```<code>$("table").on("blur", "td", function(){
calculate();
} );

function calculate() {
  var sum = 0;
  var counter = 0 //daliklis
  $('#myTable tbody tr td:nth-child(5)').each(function() {
  // $("table tbody tr td:eq(4)").each(function(){
    if (!isNaN(this.value))
    {
      sum += parseFloat($(this).text());
      counter += 1;
    }
    });
    $("#alga").textContent(sum/counter);
};
</code>```

I should probably mention, that prior existing entries can be edited only after pressing edit button.

EDIT: Ok, so apparently all of the solutions work, but the problem is, that if cell is empty, instead of excluding that part from calculation the returned result is NaN

答:
function deleteRow(r) {
    var i = r.parentNode.parentNode.rowIndex;
    document.getElementById("myTable").deleteRow(i);
    };

$("#pridet").on("click", function() {
  $("

").prependTo("table tbody");
  $("table tbody tr td").last().clone().appendTo("table tbody tr:first");
});

$(".editbtn").click(function () {
          var currentTD = $(this).parents("tr").find("td");

              $.each(currentTD, function () {
                  $(this).prop("contenteditable", true)
              });
      });

$("table").on("blur", "td", function(){
  calculate();
} );

function calculate() {
  var sum = 0;
  var counter = 0 //daliklis
  $('#myTable tbody tr td:nth-child(5)').each(function() {
  // $("table tbody tr td:eq(4)").each(function(){
    if (!isNaN($(this).text()))
    {
      sum += parseFloat($(this).text());
      counter += 1;
    }
    });
    $("#alga").text(sum/counter);
}
calculate();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.btn {
  width:10%;
  padding-bottom:0;
  margin-bottom:0;
  border-bottom:0
}</code>```

      <button id = "pridet">add</button>

            Tabelio Nr.
            Vardas
            Pavardė
            Pareigos
            Bazinė alga, €
            Valandinis atlyginimas, €
            Veiksmai

            Average

            0
            0

            1
            Mark
            Otto
            @mdo
            1000
            15.3

            2
            Jacob
            Thornton
            @fat
            2000
            16.8

            3
            Larry
            the Bird
            @twitter
            5000
            10.2

      ```

$("#alga").text(sum/counter); instead of $("#alga").textContent(sum/counter);

textContent is not a function. Use $.fn.text instead.

Plus you use this.value. Which should be $(this).text() and you should initially call the calculate()  function once:

Body:
I'm a beginner so I'm not sure whats wrong here. What im trying to achieve is to check if certain cells in a table (column) has numerical values in them and if they do include them in calculating the average value upon losing focus (blur) so that it would kind of be real time.

I'm not sure if calculation function is wrong itself, or if I'm addressing wrong column maybe or trying to insert calculated value in the wrong way. help would be appreciated.

Here is JSfiddle and the code excerpts:
https://jsfiddle.net/NulisDefo/03rn7ew1/5/

table

        Tabelio Nr.
        Vardas
        Pavardė
        Pareigos
        Bazinė alga, €
        Valandinis atlyginimas, €
        Veiksmai

        Vidurkis

        0
        0

        1
        Mark
        Otto
        @mdo
        1000
        <input type="button" value="Delete" onclick="deleteRow(this)">

        2
        Jacob
        Thornton
        @fat
        2000
        blum

        3
        Larry
        the Bird
        @twitter
        5000
        blum

script for calculating and trigger

$("table").on("blur", "td", function(){
calculate();
} );

function calculate() {
  var sum = 0;
  var counter = 0 //daliklis
  $('#myTable tbody tr td:nth-child(5)').each(function() {
  // $("table tbody tr td:eq(4)").each(function(){
    if (!isNaN(this.value))
    {
      sum += parseFloat($(this).text());
      counter += 1;
    }
    });
    $("#alga").textContent(sum/counter);
};

I should probably mention, that prior existing entries can be edited only after pressing edit button.

EDIT: Ok, so apparently all of the solutions work, but the problem is, that if cell is empty, instead of excluding that part from calculation the returned result is NaN

Body:
function deleteRow(r) {
    var i = r.parentNode.parentNode.rowIndex;
    document.getElementById("myTable").deleteRow(i);
    };

$("#pridet").on("click", function() {
  $("<tr contenteditable><td></td><td></td><td></td><td></td><td></td><td></td></tr>").prependTo("table tbody");
  $("table tbody tr td").last().clone().appendTo("table tbody tr:first");
});

$(".editbtn").click(function () {
          var currentTD = $(this).parents("tr").find("td");

              $.each(currentTD, function () {
                  $(this).prop("contenteditable", true)
              });
      });

$("table").on("blur", "td", function(){
  calculate();
} );

function calculate() {
  var sum = 0;
  var counter = 0 //daliklis
  $('#myTable tbody tr td:nth-child(5)').each(function() {
  // $("table tbody tr td:eq(4)").each(function(){
    if (!isNaN($(this).text()))
    {
      sum += parseFloat($(this).text());
      counter += 1;
    }
    });
    $("#alga").text(sum/counter);
}
calculate();

.btn {
  width:10%;
  padding-bottom:0;
  margin-bottom:0;
  border-bottom:0
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <div class="container">
      <button id = "pridet">add</button>
      <table id="myTable" class="table table-inverse">
        <thead id = "headings" class = "thead-default">
          <tr>
            <th>Tabelio Nr.</th>
            <th>Vardas</th>
            <th>Pavardė</th>
            <th>Pareigos</th>
            <th>Bazinė alga, €</th>
            <th>Valandinis atlyginimas, €</th>
            <th>Veiksmai</th>
          </tr>
        </thead>
        <tfoot class = "thead-default">
          <tr>
            <td colspan = "4">Average</td>
            <!-- <td></td>
            <td></td>
            <td></td> -->
            <td id = "alga">0</td>
            <td id = "valandinis" colspan = "2">0</td>
            <!-- <td></td> -->
          </tr>
        </tfoot>
        <tbody>
          <tr>
            <td>1</td>
            <td>Mark</td>
            <td>Otto</td>
            <td>@mdo</td>
            <td>1000</td>
            <td>15.3</td>
            <td>
              <p class = "btn editbtn"><span class = "fa fa-edit"></span></p>
              <p class = "btn" onclick="deleteRow(this)"><span class = "fa fa-trash"></span></p>
            </td>
          </tr>
          <tr>
            <td>2</td>
            <td>Jacob</td>
            <td>Thornton</td>
            <td>@fat</td>
            <td>2000</td>
            <td>16.8</td>
            <td>
              <p class = "btn editbtn"><span class = "fa fa-edit"></span></p>
              <p class = "btn" onclick="deleteRow(this)"><span class = "fa fa-trash"></span></p>
            </td>
          </tr>
          <tr class = "testas">
            <td>3</td>
            <td>Larry</td>
            <td>the Bird</td>
            <td>@twitter</td>
            <td>5000</td>
            <td>10.2</td>
            <td>
              <p class = "btn editbtn"><span class = "fa fa-edit"></span></p>
              <p class = "btn" onclick="deleteRow(this)"><span class = "fa fa-trash"></span></p>
            </td>
          </tr>
        </tbody>
      </table>
      </div>
      </body>

$("#alga").text(sum/counter); instead of $("#alga").textContent(sum/counter);

textContent is not a function. Use $.fn.text instead.

Plus you use this.value. Which should be $(this).text() and you should initially call the calculate()  function once:


来源: stackexchange

问:
Populate a subreport from muti-valued combo box.
I'm working on a simple database to organize some information for me.
I have a table named "Units" which has a multivalue combobox for which weapons said unit can take. I am trying to populate a subreport on the report that displays the table for each item (weapon) that the unit can take.

Example

Unit 1

Weapons: Weapon1/Weapon2/Weapon3

Subreport:

Weapon 1 table entries

Weapon 2 table entries

Weapon 3 table entries

I'm getting some minor success, my report is showing a separate entry for that unit and each weapon. Such as:

Unit 1

Subreport:

Weapon 1

Unit 1

Subreport:

Weapon 2

etc.

答: Not sure if I understand correctly. Are you trying to group the entries? https://support.office.com/en-us/article/Create-a-grouped-or-summary-report-6a58e9ab-9f74-4689-83b6-c63cddb2c7f9</p>

ContentLicense: CC BY-SA 3.0


问:
If-else statement giving error
normal if else statement is working but optimized if else not working

calVal == "0" ? "1" : employee.TotalLeaveDays.TotalCorrectValue.ToString();

答:
calVal = ( expression to evaluate ) ? output if true : output if false

I'm not sure what you are trying to do there.

Title: If-else statement giving error


问:
Factoring out skeleton processing (C#)
Is there a language construct in C# that allows the abstraction of loop (or other) "outer" processing?

I have a fairly straight forward nested structure (lists of lists of ints say) and the code to "spin" through each of the lowest level ints. The code isn't complicated (nor particularly long) but I have multiple functions thats need to "interact" with the lowest level independently and have been just copying the loop skeleton to do so. Seems like a waste to me.

```<code>foreach (list in outerlists)
    ... a few random lines of structure traversing
    foreach (int in list)
        do something simple to int
</code>```

This is obviously a scaled down example but my real world is similar - I end up copying the outer processing repeatedly to change out relatively few inner lines of work.

My tentative solution is to make a "processing" method that contains the loops and takes an enumeration (or something) parameter to tell it which inner function to call. Then put a switch statement at the "do something" level which calls the correct sub function.

Am I on the right track or is there an easier way? I could get rid of the switch statement with a concept of function pointers (just pass a function pointer into the processing loop and call it at the do something level) but don't know if that is possible in C#?

答: You can pass in an Action delegate - this will be the function doing the actual operation within the outer loop.

ContentLicense: CC BY-SA 2.5

Title: Factoring out skeleton processing (C#)

Body:
Is there a language construct in C# that allows the abstraction of loop (or other) "outer" processing?

I have a fairly straight forward nested structure (lists of lists of ints say) and the code to "spin" through each of the lowest level ints. The code isn't complicated (nor particularly long) but I have multiple functions thats need to "interact" with the lowest level independently and have been just copying the loop skeleton to do so. Seems like a waste to me.

foreach (list in outerlists)
    ... a few random lines of structure traversing
    foreach (int in list)
        do something simple to int

This is obviously a scaled down example but my real world is similar - I end up copying the outer processing repeatedly to change out relatively few inner lines of work.

My tentative solution is to make a "processing" method that contains the loops and takes an enumeration (or something) parameter to tell it which inner function to call. Then put a switch statement at the "do something" level which calls the correct sub function.

Am I on the right track or is there an easier way? I could get rid of the switch statement with a concept of function pointers (just pass a function pointer into the processing loop and call it at the do something level) but don't know if that is possible in C#?


问:
inserting variable in mysql using c++
```<code>while(true)
{
    mysql_query(conn, " select close, id from fivemin order by id DESC LIMIT 5 ");

    result = mysql_store_result(conn);
    num_fields = mysql_num_fields(result);
    float sum = 0;
    while((row=mysql_fetch_row(result)))
        {
                 sum += atof(row[0]);
                 last_id = atoi(row[1]);

        }
    float ma;
    ma=sum/5.0;
    if(previous_last_id != last_id)
        {
        cout << "Simple moving Average: " << ma << endl;
        previous_last_id = last_id;
        }

     mysql_query(conn,"insert into sma values("+ma+")");
}
</code>```

i want to store float ma in my db table but error: invalid operands of types 'const char[24]' and 'float' to binary 'operator+'

答:
"insert into sma values("+ma+")" this doesn't work in C.
Maybe use sprintf("insert into sma values(%f)", ma);

Also, do you really want the infinite loop? Where do you exit it?

Title: inserting variable in mysql using c++

Body:
while(true)
{
    mysql_query(conn, " select close, id from fivemin order by id DESC LIMIT 5 ");

    result = mysql_store_result(conn);
    num_fields = mysql_num_fields(result);
    float sum = 0;
    while((row=mysql_fetch_row(result)))
        {
                 sum += atof(row[0]);
                 last_id = atoi(row[1]);

        }
    float ma;
    ma=sum/5.0;
    if(previous_last_id != last_id)
        {
        cout << "Simple moving Average: " << ma << endl;
        previous_last_id = last_id;
        }

     mysql_query(conn,"insert into sma values("+ma+")");
}

i want to store float ma in my db table but error: invalid operands of types 'const char[24]' and 'float' to binary 'operator+'


问:
node.js check if a remote URL exists
How do I check to see if a URL exists without pulling it down? I use the following code, but it downloads the whole file. I just need to check that it exists.

```<code>app.get('/api/v1/urlCheck/', function (req,res) {
    var url=req.query['url'];
    var request = require('request');
    request.get(url, {timeout: 30000, json:false}, function (error, result) {
        res.send(result.body);

    });

});
</code>```

Appreciate any help!

答:
Simply use url-exists npm package to test if url exists or not</p>

```<code>var urlExists = require('url-exists');

urlExists('https://www.google.com', function(err, exists) {
  console.log(exists); // true
});

urlExists('https://www.fakeurl.notreal', function(err, exists) {
  console.log(exists); // false
});
</code>```

Title: node.js check if a remote URL exists

Body:
How do I check to see if a URL exists without pulling it down? I use the following code, but it downloads the whole file. I just need to check that it exists.

app.get('/api/v1/urlCheck/', function (req,res) {
    var url=req.query['url'];
    var request = require('request');
    request.get(url, {timeout: 30000, json:false}, function (error, result) {
        res.send(result.body);

    });

});

Appreciate any help!

Body:
Simply use url-exists npm package to test if url exists or not

var urlExists = require('url-exists');

urlExists('https://www.google.com', function(err, exists) {
  console.log(exists); // true
});

urlExists('https://www.fakeurl.notreal', function(err, exists) {
  console.log(exists); // false
});


问:
Laravel 5 Sort data in Alphabetical Order
What is the best approach to display data in Alphabetical order using Laravel. what is the best way to querying for data for this type of task?

This is the example what i wanted!

is it good to use Laravel Collections or is there any best way to do this?

答:
Ok Found an answer!!</p>

```<code>$collection = App\User::orderBy('name')->get();

$grouped = $collection->groupBy(function ($item, $key) {
    return substr($item->name, 0, 1);
});
</code>```

Body:
Ok Found an answer!!

$collection = App\User::orderBy('name')->get();

$grouped = $collection->groupBy(function ($item, $key) {
    return substr($item->name, 0, 1);
});


问:
Execute Command SwitchCell OnChanged in a ListView
I'm fairly new to Xamarin.Forms and tried googling my question.
I have a ListView of SwitchCells, the ItemsSource is a Collection of a simple Data-Class.

Now when I change the Switch's state in the SwitchCell I want to have a Method being called...that should not be the problem, but I can't figure out how I know which SwitchCell, or in other words which Instance of the DataClass, which Item was switched.

I expect it to be something like the code I commented, but am really not sure...also I think that I'm mixing up Commands and Methods here....

My XAML:

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="slwAppTutorial.InterestsList">
  <StackLayout>
    <ListView x:Name="interestList">
      <ListView.ItemTemplate>
        <DataTemplate>
          <SwitchCell Text="{Binding Text}" On="false" > <!--OnChanged="{Binding something}" -->
          </SwitchCell>
        </DataTemplate>
      </ListView.ItemTemplate>
    </ListView>
    <Button x:Name="submit" Text="Bestätigen"></Button>
  </StackLayout>
</ContentPage>
</code>```

My CodeBehind file:

```<code>namespace slwAppTutorial
{
public partial class InterestsList : ContentPage
{
    //InterestListManager manager;
    List<InterestsItem> myList = new List<InterestsItem>();

    public InterestsList()
    {

        InitializeComponent();

        InterestsItem myInterest = new InterestsItem() { Id = "1234", Text = "Volleyball", Kind = "Sport" };
        for (int i=0; i < 25; i++) { myList.Add(myInterest); }
        //manager = InterestListManager.DefaultManager;

// My Expected Command
// someSwitch.OnChanged+= (sender, args) =>
//            {
//                var selectedItem = args.Item as InterestsItem;
//
//                Do something with my InterestsItem
//
//                DisplayAlert(title: selectedItem.Text, message: selectedItem.Kind, cancel: "OK");
//                if (selectedItem == null) return;
//            };

    protected override async void OnAppearing()
    {
        base.OnAppearing();
        interestList.ItemsSource = myList;
        //await RefreshItems(true, syncItems: false);
    }

    private async Task RefreshItems(bool showActivityIndicator, bool syncItems)
    {
        interestList.ItemsSource = myList; //await manager.GetInterestItemsAsync(syncItems);
    }

}
}
</code>```

答:
I think you should use Switch not SwitchCell

Switch has a IsToggledProperty

or a Toggled event

ContentLicense: CC BY-SA 4.0

Body:
I'm fairly new to Xamarin.Forms and tried googling my question.
I have a ListView of SwitchCells, the ItemsSource is a Collection of a simple Data-Class.

Now when I change the Switch's state in the SwitchCell I want to have a Method being called...that should not be the problem, but I can't figure out how I know which SwitchCell, or in other words which Instance of the DataClass, which Item was switched.

I expect it to be something like the code I commented, but am really not sure...also I think that I'm mixing up Commands and Methods here....

My XAML:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="slwAppTutorial.InterestsList">
  <StackLayout>
    <ListView x:Name="interestList">
      <ListView.ItemTemplate>
        <DataTemplate>
          <SwitchCell Text="{Binding Text}" On="false" >
          </SwitchCell>
        </DataTemplate>
      </ListView.ItemTemplate>
    </ListView>
    <Button x:Name="submit" Text="Bestätigen"></Button>
  </StackLayout>
</ContentPage>

My CodeBehind file:

namespace slwAppTutorial
{
public partial class InterestsList : ContentPage
{
    //InterestListManager manager;
    List<InterestsItem> myList = new List<InterestsItem>();

    public InterestsList()
    {

        InitializeComponent();

        InterestsItem myInterest = new InterestsItem() { Id = "1234", Text = "Volleyball", Kind = "Sport" };
        for (int i=0; i < 25; i++) { myList.Add(myInterest); }
        //manager = InterestListManager.DefaultManager;

// My Expected Command
// someSwitch.OnChanged+= (sender, args) =>
//            {
//                var selectedItem = args.Item as InterestsItem;
//
//                Do something with my InterestsItem
//
//                DisplayAlert(title: selectedItem.Text, message: selectedItem.Kind, cancel: "OK");
//                if (selectedItem == null) return;
//            };

    protected override async void OnAppearing()
    {
        base.OnAppearing();
        interestList.ItemsSource = myList;
        //await RefreshItems(true, syncItems: false);
    }

    private async Task RefreshItems(bool showActivityIndicator, bool syncItems)
    {
        interestList.ItemsSource = myList; //await manager.GetInterestItemsAsync(syncItems);
    }

}
}


问:
Bitbucket fails to authenticate on git pull
I use BitBucket and had to change my password because it was compromised.

```<code>git pull
</code>```

remote: Invalid username or password. If you log in via a third party service you must ensure you have an account password set in your account profile.

  fatal: Authentication failed for 'https://bitbucket.org/myusername/myproject.git/'

How can I change my password using command line?

答:
You can update your Bitbucket credentials from the OSX Keychain.

Updating your cached credentials via the command line:

```<code>$ git credential-osxkeychain erase
host=bitbucket.org
protocol=https
[press return]
</code>```

If it's successful, nothing will print out. To test that it works, try and clone a repository from Bitbucket. If you are prompted for a password, the keychain entry was deleted.

Body:
I use BitBucket and had to change my password because it was compromised.

git pull

remote: Invalid username or password. If you log in via a third party service you must ensure you have an account password set in your account profile.

  fatal: Authentication failed for 'https://bitbucket.org/myusername/myproject.git/'

How can I change my password using command line?

Body:
You can update your Bitbucket credentials from the OSX Keychain.

Updating your cached credentials via the command line:

$ git credential-osxkeychain erase
host=bitbucket.org
protocol=https
[press return]

If it's successful, nothing will print out. To test that it works, try and clone a repository from Bitbucket. If you are prompted for a password, the keychain entry was deleted.


问:
Client-Side templating with nodejs and pug
I have a web app that I'm building that has dynamic widgets being constructed on the client-side. Currently I am using nodejs and pug as my server side templating library, and I like the simplicity of pug.

I would like to have a series of small pug files on the server that the client side can use as building blocks to construct the user desired widget.

I tried using a previous solution found here:
client side server side templating nodejs

However, that solution looks like overkill for what I want. Moreover, it looks like the ezel project is no longer maintained, it hasn't been updated in 2 years and it still uses jade (which npm gives me a lot of errors).

I just want to be able to construct my dynamic widgets in pug in the browser. This page seems to have exactly what I want:
https://pugjs.org/api/reference.html
Specifically the pug.renderFile('path/to/file.pug', options); function seems like exactly what I want to use to dynamically build my widgets (the user has all the controls on how the widgets are constructed/displayed, so the browser needs to dynamically construct the html views)

My issue is the dependence on:
https://pugjs.org/js/pug.js
And the need to do require('pug') in the browser. I already have pug installed as part of my package.json. Is there a more robust way of getting pug.js directly? I am still new to web development, my background is in C++/Java, so I'm not entirely sure if using pug.js in the browser directly is the best solution or if there are better standard solution. The stackoverflow question I posted is the only post I came across that is remotely similar.

答:
If you use webpack:

https://github.com/pugjs/pug-loader and
https://github.com/willyelm/pug-html-loader serve well.

In case of rollup:

https://www.npmjs.com/package/rollup-plugin-pug + https://www.npmjs.com/package/rollup-plugin-pug-html seem to be good solution (currently testing how it works, we are now experimenting with native es6 modules and backuping bundles with rollup)

In case of browserify:

https://www.npmjs.com/package/jadeify (never have tried)

Also pug-cli have got -c key, so you can just run any watcher and generate js files as mentioned above, but it seems to be bit too straightforward since we've got variety of bundling tools now in 2017.


问:
To fault or not to fault
I'm having a discussion with a colleague about when to throw faults and when not to throw faults in a WCF service.

One opinion is, that we only throw faults when the service operation could not do its work due to some error; and something may be in an invalid state because of it. So, some examples:

ValidateMember(string name, string password, string country)
-> would throw a fault if the mandatory parameters are not passed, because the validation itself could not be executed;
-> would throw fault if some internal error occured, like database was down
-> would return a status contract in all other cases, that specifies the result of the validation (MemberValidated, WrongPassword, MemberNotKnown,...)

GetMember(int memberId)
-> would only throw fault if something is down, in all other cases it would return the member or null if not found

The other opinion is that we should also throw faults when GetMember does not find the member, or in the case of ValidateMember the password is wrong.

What do you think?

答:
It it is a common, routine failure, then throwing a fault is a mistake.  The software should be written to handle routine items, like entering the wrong password.  Fault processing is for exceptional failure which are not considered part of the program's normal design.

For example, if your program was written with the idea that it always has access to a database, and the database is not accessible, that's an issue where the "fix" is well outside of the limits of your software.  A fault should be thrown.

Fault processing uses different logical flows through the structure of the programming language, and by using it only when you've "left" the normal processing of the programming problem, you will make your solution leverage the feature of the programming language in a way that seems more natural.

Title: To fault or not to fault


问:
How to update the form's value with Struts 2
I'm trying to pass the value from JSP page to my Action class when pressing the Update button.

In this case, I create in action class a list of Strings named value with getter and setter.

My problem is that, when trying to modify the input field in JSP and then pressing Update, value remains the same (with its initial value) in the action class.

For example:

```<code>v[0] = "zero"
v[1] = "something"
v[2] = "true"
</code>```

In my form I've changed the v[2] input text in "false" and then pressed Update; when printed in execute(), v[2] remains "true".

UPDATE: I rewrite the JSP code, using Struts 2 tag instead of scriptlet

<form name="propertiesForm" method="post" action="<s:url value='/update.action'/>" >

            Property
            Value

          <s:iterator value="%{propertiesForm.properties}" status="rowStatus">

        <s:property value="%{properties[#rowStatus.index].name}"/>
        <s:textfield name="value[%{#rowStatus.index}]" value="%{propertiesForm.getValue(#rowStatus.index)}"/>

         </s:iterator>

           <input class="buttons" type="submit" value="Update" />

</form>
```

答:
Form fields are bound by their name attribute. It should be a proper OGNL expression, which is evaluated by params interceptor against the valueStack. The action bean should be on top of the valueStack when parameters are populated, if your action is not model driven, then the action bean will be populated if it has corresponding property accessors.

The problem is in your code as you use scriptlets (that are highly discouraged, see How to avoid Java code in JSP files?) and has a bug in the code name="<%="value[" + i + "]"%>.

Looking on the code you have update recently in your question

```<code><s:textfield name="value[%{#rowStatus.index}]" value="%{propertiesForm.getValue(#rowStatus.index)}"/>
</code>```

I see that the value comes from propertiesForm property, but the form field is bound to action property. It might not have corresponding setter to fill the property value when the form is submitted. I recommend to bind the value to the propertiesForm, so you even don't need the value pre-populated, since the value evaluated by the name attribute.

```<code><s:textfield name="propertiesForm.value[%{#rowStatus.index}]" />
</code>```

Body:
I'm trying to pass the value from JSP page to my Action class when pressing the Update button.

In this case, I create in action class a list of Strings named value with getter and setter.

My problem is that, when trying to modify the input field in JSP and then pressing Update, value remains the same (with its initial value) in the action class.

For example:

v[0] = "zero"
v[1] = "something"
v[2] = "true"

In my form I've changed the v[2] input text in "false" and then pressed Update; when printed in execute(), v[2] remains "true".

UPDATE: I rewrite the JSP code, using Struts 2 tag instead of scriptlet

<form name="propertiesForm" method="post" action="<s:url value='/update.action'/>" >

            Property
            Value

          <s:iterator value="%{propertiesForm.properties}" status="rowStatus">

        <s:property value="%{properties[#rowStatus.index].name}"/>
        <s:textfield name="value[%{#rowStatus.index}]" value="%{propertiesForm.getValue(#rowStatus.index)}"/>

         </s:iterator>

           <input class="buttons" type="submit" value="Update" />

</form>

Body:
Form fields are bound by their name attribute. It should be a proper OGNL expression, which is evaluated by params interceptor against the valueStack. The action bean should be on top of the valueStack when parameters are populated, if your action is not model driven, then the action bean will be populated if it has corresponding property accessors.

The problem is in your code as you use scriptlets (that are highly discouraged, see How to avoid Java code in JSP files?) and has a bug in the code name="<%="value[" + i + "]"%>.

Looking on the code you have update recently in your question

<s:textfield name="value[%{#rowStatus.index}]" value="%{propertiesForm.getValue(#rowStatus.index)}"/>

I see that the value comes from propertiesForm property, but the form field is bound to action property. It might not have corresponding setter to fill the property value when the form is submitted. I recommend to bind the value to the propertiesForm, so you even don't need the value pre-populated, since the value evaluated by the name attribute.

<s:textfield name="propertiesForm.value[%{#rowStatus.index}]" />


问:
Error code 403 in Google+ api
I got "error": {
  "errors": [
   {
    "domain": "usageLimits",
    "reason": "dailyLimitExceededUnreg",
    "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
    "extendedHelp": "https://code.google.com/apis/console"
   }
  ],
  "code": 403,
  "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
 }
When i try to fetch User Profile in Google+ api by https://www.googleapis.com/plus/v1/people/me URL String.If anyone have any suggestion then please tell me as soon as possible.Thanks in advance for your time.

答: I got the same error and after much hunting I found that, in my case, the Authorization header with the access token was not set. Set Authorization: "Bearer <YOUR_ACCESS_TOKEN>" in the header of the request of EVERY Google API call.

Title: Error code 403 in Google+ api


问:
className applied when using "addItem"
I am using addItem to add a value to a list from another component

I am adding it to this.state.movies. It appears, however it has the inactive/noresults className applied to it.

How do I determine which styling is applied to an item that has not appeared yet (ie using addItem)? Thanks

Full example on Codesandbox is here. Add an movie to the list and you will see it gets the stying applied: https://codesandbox.io/s/3OGK2pP9

Parent component where I add the item

```<code><CreateNew addItem={item => this.setState({ movies: [{ name: item.value.name, genres: item.genres }].concat( movies, ), })} />
</code>```

Child component that creates the item

```<code>class CreateNew extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: '',
      genres: '',
    };
  }
  handleSubmit1 = (e, value) => {
    e.preventDefault();
    this.props.addItem(this.state);
  };
  onChange = e => {
    this.setState({
      value: { name: e.target.value },
      genres: [{ name: 'Test', type: 1 }, { name: 'Foo', type: 10 }],
    });
  };
  render() {
    const { value, genres } = this.props;
    return (
      <form onSubmit={this.handleSubmit1}>
        Add a new movie
        <input onChange={this.onChange} value={value} type="text" />
        <button type="submit">Add</button>
      </form>
    );
  }
}
</code>```

答:
Was related to filtering on my const x instead of my state this.state.movies.

I changed it from const filteredResults = andFilter({x}, Object.keys(selectedFilters)); to `const filteredResults = andFilter({this.state.movies}, Object.keys(selectedFilters));

Title: className applied when using "addItem"

Body:
I am using addItem to add a value to a list from another component

I am adding it to this.state.movies. It appears, however it has the inactive/noresults className applied to it.

How do I determine which styling is applied to an item that has not appeared yet (ie using addItem)? Thanks

Full example on Codesandbox is here. Add an movie to the list and you will see it gets the stying applied: https://codesandbox.io/s/3OGK2pP9

Parent component where I add the item

<CreateNew addItem={item => this.setState({ movies: [{ name: item.value.name, genres: item.genres }].concat( movies, ), })} />

Child component that creates the item

class CreateNew extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: '',
      genres: '',
    };
  }
  handleSubmit1 = (e, value) => {
    e.preventDefault();
    this.props.addItem(this.state);
  };
  onChange = e => {
    this.setState({
      value: { name: e.target.value },
      genres: [{ name: 'Test', type: 1 }, { name: 'Foo', type: 10 }],
    });
  };
  render() {
    const { value, genres } = this.props;
    return (
      <form onSubmit={this.handleSubmit1}>
        Add a new movie
        <input onChange={this.onChange} value={value} type="text" />
        <button type="submit">Add</button>
      </form>
    );
  }
}


问:
Breaking bash script execution if passed file is of wrong extension
I have a small bash file that I used to compress PDFs and undertake some other file manipulations. I would like to break execution of this bash script if the passed file name does not have .pdf or .PDF extension.

Current approach:

```<code># Take file name
fle_nme=$1

# Check if passed PDF file
# -ne - not equal
if ["${fle_nme: -4}" -ne ".pdf"] ||  ["${fle_nme: -4}" -ne ".PDF"]; then
        echo "Incorrect file."
        exit
fi
</code>```

Current output

The script fails but without the desired message:

```<code>[me@onthebox bashStuff ERR]$ compressPDF ~/bashFun/failWithThisExtension.bad
compressPDF.sh: line 16: [.bad: command not found
compressPDF.sh: line 16: [.bad: command not found
</code>```

Desired results

Execution of the script should finish

Message Incorrect file should be printed to console

答:
Fix the if-conditional in bash, put spaces around [, ] and always remember to quote your variables and remember -ne is for integer comparisons and not for string comparison.

```<code>fle_nme="$1"
if [ "${fle_nme: -4}" != ".pdf" ] ||  [ "${fle_nme: -4}" != ".PDF" ]; then
</code>```

(or) you have a relatively recent version of bash you can set the nocasematch option available which will work for both .pdf and .PDF

```<code>shopt -s nocasematch
if [[ "${fle_nme: -4}" != ".pdf" ]]; then
..

shopt -u nocasematch
</code>```

Also worth adding that, the shell option you are setting needs to be disabled soon after the comparison is done. If not the option will be propagated to the rest of the script which might affect your other string comparisons.

As a side note, the best way to extract the extension from the filename would be to use parameter expansion syntax like below, this way you need not worry about the number of characters comprising of the file extension

```<code>shopt -s nocasematch
if [[ "${fle_nme##*.}" != "pdf" ]]; then
</code>```

Body:
I have a small bash file that I used to compress PDFs and undertake some other file manipulations. I would like to break execution of this bash script if the passed file name does not have .pdf or .PDF extension.

Current approach:

# Take file name
fle_nme=$1

# Check if passed PDF file
# -ne - not equal
if ["${fle_nme: -4}" -ne ".pdf"] ||  ["${fle_nme: -4}" -ne ".PDF"]; then
        echo "Incorrect file."
        exit
fi

Current output

The script fails but without the desired message:

[me@onthebox bashStuff ERR]$ compressPDF ~/bashFun/failWithThisExtension.bad
compressPDF.sh: line 16: [.bad: command not found
compressPDF.sh: line 16: [.bad: command not found

Desired results

Execution of the script should finish

Message Incorrect file should be printed to console

Body:
Fix the if-conditional in bash, put spaces around [, ] and always remember to quote your variables and remember -ne is for integer comparisons and not for string comparison.

fle_nme="$1"
if [ "${fle_nme: -4}" != ".pdf" ] ||  [ "${fle_nme: -4}" != ".PDF" ]; then

(or) you have a relatively recent version of bash you can set the nocasematch option available which will work for both .pdf and .PDF

shopt -s nocasematch
if [[ "${fle_nme: -4}" != ".pdf" ]]; then
..

shopt -u nocasematch

Also worth adding that, the shell option you are setting needs to be disabled soon after the comparison is done. If not the option will be propagated to the rest of the script which might affect your other string comparisons.

As a side note, the best way to extract the extension from the filename would be to use parameter expansion syntax like below, this way you need not worry about the number of characters comprising of the file extension

shopt -s nocasematch
if [[ "${fle_nme##*.}" != "pdf" ]]; then


问:
I am getting error while executing below query in SQL SERVER 2008 R2
```<code>SP_ADDTYPE 'SWORKSTATIONID_TYPE_TEMP', 'VARCHAR(256)', NULL
</code>```

答:
First, to run a stored procedure, use exec:

```<code>EXEC SP_ADDTYPE 'SWORKSTATIONID_TYPE_TEMP', 'VARCHAR(256)', NULL ;
</code>```

Second, this is deprecated.  Use CREATE TYPE instead (see here).

Body:
First, to run a stored procedure, use exec:

EXEC SP_ADDTYPE 'SWORKSTATIONID_TYPE_TEMP', 'VARCHAR(256)', NULL ;

Second, this is deprecated.  Use CREATE TYPE instead (see here).


问:
How to pass a String variable to javascript onClick Function in a JSP
In my jsp, I have something like this

```<code><%
String isMultipleOfficesExists = (String)request.getAttribute("MultipleOfficesExists");
        String isMultipleOfficeSecurity = (String)request.getAttribute("MultipleOfficeSecurityExists");
String envParm = "default";
if("true".equals(isMultipleOfficesExists)){
    envParm = "multipleOffice";
}else if("true".equals(isMultipleOfficeSecurity)){
    envParm = "multipleOfficeSecurity";
}
%>
</code>```

At the bottom of my form, in my submit button, I am calling a JavaScript On-click function.

```<code><input class="white_button_extra_large" type="button" value="<%=goBtn%>" onclick="javascript:selectEnvironment(envParm);">
</code>```

And my script section is :

```<code>function selectEnvironment(envParm)
{
    resetToken();
    logoutFlag = false;
    document.forms[0].action = contextURL+'/login/selectEnvironment?envParam=' +envParm;
    document.forms[0].submit();
}
</code>```

But I am getting Uncaught ReferenceError: envParam is not defined

How can I solve this?

答:
Make your envParm variable global in JSP. And your on click event should be like follows

```<code><input class="white_button_extra_large" type="button" value="<%=goBtn%>" onclick="javascript:selectEnvironment('<%=envParm%>')">
</code>```

You should pass the value from javascript function. The parameter should have value. Refer this linkPassing arguments

Body:
In my jsp, I have something like this

<%
String isMultipleOfficesExists = (String)request.getAttribute("MultipleOfficesExists");
        String isMultipleOfficeSecurity = (String)request.getAttribute("MultipleOfficeSecurityExists");
String envParm = "default";
if("true".equals(isMultipleOfficesExists)){
    envParm = "multipleOffice";
}else if("true".equals(isMultipleOfficeSecurity)){
    envParm = "multipleOfficeSecurity";
}
%>

At the bottom of my form, in my submit button, I am calling a JavaScript On-click function.

<input class="white_button_extra_large" type="button" value="<%=goBtn%>" onclick="javascript:selectEnvironment(envParm);">

And my script section is :

function selectEnvironment(envParm)
{
    resetToken();
    logoutFlag = false;
    document.forms[0].action = contextURL+'/login/selectEnvironment?envParam=' +envParm;
    document.forms[0].submit();
}

But I am getting Uncaught ReferenceError: envParam is not defined

How can I solve this?

Body:
Make your envParm variable global in JSP. And your on click event should be like follows

<input class="white_button_extra_large" type="button" value="<%=goBtn%>" onclick="javascript:selectEnvironment('<%=envParm%>')">

You should pass the value from javascript function. The parameter should have value. Refer this linkPassing arguments


问:
How does a web server know what linked to it?
I use photobucket to post images to various user forums.  The forums I post to allow the embedding of a direct link to the image.

One of the services photobucket provides is a view history which includes not only number of hits but also information on which sites viewed the page.  I can't figure out how they do that -- can anyone fill me in on the details?

I would like to add that ability to my own server, but isn't this a security hole in the HTTP protocol of sorts?

答: When you request an image from that web service (lets say it's a PHP page), the image is served, but first PHP takes a look at the $_SERVER['HTTP_REFERER'] variable to see what URL the request is coming from


问:
(C#) Web Service doesn't recognize Oracle Library
I'm currently creating a Web Service to call on my ASP/C# application, which has a basic SQL SELECT query from an Oracle Database.

The problem is that the Web Service file itself doesn't recognize the Oracle libraries, so I can't use any commands like OracleConnection and such, as they asked me to do so for work.

The commands itself work perfectly on C# pages, and have no issue at all. The Web Service can read SQL Commands like SqlConnect, but not OracleConnect.

Any way to fix it? Thanks.

答:
I was also facing all same issue
so i upload the all assemble to server it resolve my problem also please check the all the references

then clean the solution and rebuild solution.

Please check the oracle version and reference dll version


问:
MongoDB query returns 3 dots instead of answer
I am following an online course on a website and when I am trying to submit a query on my local MongoDB, it returns ... instead of the answer.

The query I submit is

db.scores.find( { "type" : "essay", "score" : 50 }, { student : true, _id : false ).pretty()

答: When I had this same error, its was the result of a string value being terminated prematurely due to a ' or " in the string. Look for any extraneous quotation marks or apostrophes in the values you're adding which may interfere with the declaration.</p>


问:
How to prevent Soft Keyboard hiding button in custom dialog?
I have a custom dialog like following

When soft keyboard comes it hides the Button like below.

my code

https://mcaf.ee/9qhnef

How to avoid Submit button being hide?  i have added autoresize and auto pan but no luck so far.

答: Add your whole attribute in one Linear Layout  and put in Scroll View. i hope this help you. </p>


问:
rails respond_to in controller rescue block
respond_to not working inside controller rescue block:

```<code>def create
  respond_to do | format |
    format.json { render json: SomeManager.new(some_params).json }
    format.html do
      SomeManager.new(some_params)
      render :new, notice: 'it worked'
    end
  end
rescue => e
  respond_to do | format |
    format.json { render json: {error: 'did not work because reasons'}.to_json, status: :forbidden }
    format.html { render :new, alert: 'did not work because reasons' }
  end
end
</code>```

^ Controller for API which can respond to API json uploads, or manual uploads using UI.

答:
The rescue block isn't to blame. This would happen if your routes.rb is specified with an option like so:

```<code>resources :widgets, defaults: {format: :the_spanish_inquisition}
</code>```

Body:
respond_to not working inside controller rescue block:

def create
  respond_to do | format |
    format.json { render json: SomeManager.new(some_params).json }
    format.html do
      SomeManager.new(some_params)
      render :new, notice: 'it worked'
    end
  end
rescue => e
  respond_to do | format |
    format.json { render json: {error: 'did not work because reasons'}.to_json, status: :forbidden }
    format.html { render :new, alert: 'did not work because reasons' }
  end
end

^ Controller for API which can respond to API json uploads, or manual uploads using UI.

Body:
The rescue block isn't to blame. This would happen if your routes.rb is specified with an option like so:

resources :widgets, defaults: {format: :the_spanish_inquisition}


问:
Filter in pandas using operators
I have Three variables as

```<code>a='col1'
b='=='
c=2
</code>```

I have Pandas dataframe as

```<code>df = pd.DataFrame({'col1': [0, 1, 2], 'col2': [10, 11, 12]},dtype=object)
</code>```

And I wanted to filter for col1=2, So I wrote

```<code>df.query("@a @b @c")
</code>```

Which is throwing below error

```<code>File "<unknown>", line 1
    __pd_eval_local_a __pd_eval_local_b __pd_eval_local_c
                                      ^
SyntaxError: invalid syntax
</code>```

Can some one help me how to achieve this using these three variables?

Thanks,

答:
You can do it without the use of query if that's not a requierement, using eval : </p>

```<code>a='col1'
b='=='
c='2'

instruction ="df[\"" + a + "\"]" + b  + c
>>>> 'df["col1"]==2'
df[eval(instruction)]
>>>>
    col1    col2
  2  2      12
</code>```

Title: Filter in pandas using operators

Body:
I have Three variables as

a='col1'
b='=='
c=2

I have Pandas dataframe as

df = pd.DataFrame({'col1': [0, 1, 2], 'col2': [10, 11, 12]},dtype=object)

And I wanted to filter for col1=2, So I wrote

df.query("@a @b @c")

Which is throwing below error

File "<unknown>", line 1
    __pd_eval_local_a __pd_eval_local_b __pd_eval_local_c
                                      ^
SyntaxError: invalid syntax

Can some one help me how to achieve this using these three variables?

Thanks,

Body:
You can do it without the use of query if that's not a requierement, using eval :

a='col1'
b='=='
c='2'

instruction ="df[\"" + a + "\"]" + b  + c
>>>> 'df["col1"]==2'
df[eval(instruction)]
>>>>
    col1    col2
  2  2      12


问:
how to design a communicate channel of game server
I am planning to design a game server. I wish it could take a very heavy load, reusable, flexiable, but easy to programming, I want to get a balance of those points.

I decide to use nodejs and redis, the data formate of protocal is JSON, websocket

I have experience of web development, but have no idea of game server development, I notice that game server is very Real-Time, and the message is not peer to peer, but pub-sub channel,

Does nodejs, redis, JSON is a good choice for design the communicate channel, does websocket support by most browser?

Maybe there are too many questions, the only question is how to design a communicate channel for a game server?

答:
Websockets aren't supported my most browsers that are on the PCs of endusers. Try to use endlessly-loading iframes over HTTPS (over SSL to avoid stupid proxys that want to fully load the endlessly-loading iframe before passing it on) for receiving data, that's widely supported. For sending, use AJAX requests.

Make the iframe page push lines like this one over http:

```<code><script>newData("...")</script>
</code>```

If that's too slow for you, use a flash/java applet that does the communication.

Body:
Websockets aren't supported my most browsers that are on the PCs of endusers. Try to use endlessly-loading iframes over HTTPS (over SSL to avoid stupid proxys that want to fully load the endlessly-loading iframe before passing it on) for receiving data, that's widely supported. For sending, use AJAX requests.

Make the iframe page push lines like this one over http:

<script>newData("...")</script>

If that's too slow for you, use a flash/java applet that does the communication.


问:
Why is "using namespace std;" considered bad practice?
I have heard using namespace std; is bad practice, and that I should use std::cout and std::cin directly instead.
Why is this? Does it risk declaring variables that share the same name as something in the std namespace?

答:
Here's a point of view I haven't found in any of the other answers: use only one namespace. The main reason why namespaces are bad, according to most of the answers, is that you can have conflicting function names which can result in a total mess. However, this won't occur if you use only one namespace. Decide which library it is that you will use the most (maybe using namespace std;) and stick with it.

One can think of it as having an invisible library prefix - std::vector becomes just vector. This, in my opinion, is the best of both worlds: on one hand it reduces the amount of typing you have to do (as intended by namespaces) and on the other, it still requires you to use the prefixes for clarity and security. If there's a function or object without a namespace prefix - you know it's from the one namespace you declared.

Just remember that if you will decide to use one globally - don't use others locally. This comes back to the other answers that local namespaces are often more useful than global ones since they provide variety in convenience.


问:
Extracted Keypoints and Features are not at points of interest
I am working with an image that has blue and gray spots. Eventually I want to recognise all the images in a dataset that have this scene. I am using SIFT for this. I tried to map the keypoints that looks like this:

The generated keypoints are not at points of interest according to me. Am I doing anything wrong?

```<code>im1 = im2single(im1) ;
im1g = rgb2gray(im1) ;
[fa,da] = vl_sift(im1g) ; % fa is 4x14869, da is 128x14869
perm = randperm(size(fa,2)) ;
start=-49;
int=49;
while start<length(fa)
    figure % image(im1) % start=start+50
    sel=perm(start:start+int)
    h1=vl_plotframe(fa(:,sel)) ;
    set(h1, 'color', 'y', 'linewidth',3);
    start;
    pause;
end
</code>```

答:
Your code doesn't work for me. It says in this line:

```<code>sel=perm(start:start+int)
</code>```

Subscript indices must either be real positive integers or logicals.

You set start=-49, which is a negative index. Also start=start+50 gives an error... sorry, I can't reproduce your example.

Could you please correct your code?

Body:
I am working with an image that has blue and gray spots. Eventually I want to recognise all the images in a dataset that have this scene. I am using SIFT for this. I tried to map the keypoints that looks like this:

The generated keypoints are not at points of interest according to me. Am I doing anything wrong?

im1 = im2single(im1) ;
im1g = rgb2gray(im1) ;
[fa,da] = vl_sift(im1g) ; % fa is 4x14869, da is 128x14869
perm = randperm(size(fa,2)) ;
start=-49;
int=49;
while start<length(fa)
    figure % image(im1) % start=start+50
    sel=perm(start:start+int)
    h1=vl_plotframe(fa(:,sel)) ;
    set(h1, 'color', 'y', 'linewidth',3);
    start;
    pause;
end

Body:
Your code doesn't work for me. It says in this line:

sel=perm(start:start+int)

Subscript indices must either be real positive integers or logicals.

You set start=-49, which is a negative index. Also start=start+50 gives an error... sorry, I can't reproduce your example.

Could you please correct your code?


问:
jmeter- Throughput Shaping meter Request generation
I have created a profile of maximum peak load of 5000 rps using Throughput shaping meter provided as a jmeter plugin.

When I add  "transaction per second" as a listener to analyze the request per second. It does not show a peak load of 5000rps.

Does the transaction per second listener shows the plot of generation of the request by Throughput shaping meter or the actual execution plot of those generated requests against any target server.

How can I confirm the generation of the requests reaches he maximum peak load of 5000 rps? Currently I am using http sampler for request generation.

答:
Throughput shaping timer can only pause the threads to limit JMeter throughput to the defined value(s), it won't be kicking off any extra threads so make sure you provide enough threads (virtual users) and loops (so all the threads would be up and running) in order to reach the desired throughput.

Also be aware that JMeter waits for previous response prior to starting next request so depending on you application response time you may (or may not) reach the desired value of 5k requests per second.

Example sample figures:

If you have 5000 virtual users and application response time is 1 second - you will have 5000 RPS

If you have 5000 virtual users and application response time is 2 seconds - you will have 2500 RPS

If you have 5000 virtual users and application response time is 500 ms - you will have 10000 RPS

It is also highly unlikely that you will be able to reach 5000 RPS throughput using JMeter default configuration which is good for tests development and/or debugging but it not suitable for the high loads, so make sure you're following JMeter Best Practices and recommendations from the 9 Easy Solutions for a JMeter Load Test “Out of Memory” Failure guide.


问:
Python: Callbacks, Delegates, ... ? What is common?
Just want to know what's the common way to react on events in python. There are several ways in other languages like callback functions, delegates, listener-structures and so on.
Is there a common way? Which default language concepts or additional modules are there and which can you recommend?</p>

答:
It all depends on the level of complexity your application requires. For simple events, callbacks will probably do. For more complex patterns and decoupled levels you should use some kind of a publish-subscribe implementation, such as PyDispatcher or wxPython's pubsub.

See also this discussion.

OwnerDisplayName: okoman

OwnerDisplayName: eliben


问:
Java: XML to Object (or Array)
How could I convert a XML Document to a Java Object (or Array)?
I readed the XML like this:

```<code>DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dFactory.newDocumentBuilder();

Document doc = dBuilder.parse(new File("file.xml"));
doc.getDocumentElement().normalize();
</code>```

Now I want that XML as Object (or Array) but how should I do this?
Are there any methods or tutorials or classes out there to do that?

答: You will need JAXB unmarshaling.</p>

Title: Java: XML to Object (or Array)

Body:
How could I convert a XML Document to a Java Object (or Array)?
I readed the XML like this:

DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dFactory.newDocumentBuilder();

Document doc = dBuilder.parse(new File("file.xml"));
doc.getDocumentElement().normalize();

Now I want that XML as Object (or Array) but how should I do this?
Are there any methods or tutorials or classes out there to do that?

Body: You will need JAXB unmarshaling.


问:
Windowed functions cannot be used in the context of another windowed function or aggregate.SQL Server error
I am trying to get the row number for the rank. Below is the query,

```<code> SELECT *
FROM (
    SELECT DISTINCT TOP 100 PERCENT rank() OVER (
                PARTITION BY o.panel_id
                ,o.combo_type_code ORDER BY row_number() OVER (
                        ORDER BY o.panel_id
                        )
                ) AS rank
            ,panel_code
        FROM tbk_offer_head o
            ,tbk_combo_type ct
            ,tbk_panel p
        WHERE o.panel_id = p.panel_id
            AND o.combo_type_code = ct.combo_type_code
            AND o.panel_id IN (
                SELECT p.panel_id
                FROM tbk_panel p
                WHERE p.campaign_id = 7392
                )
        ) A
    WHERE A.rank = 1
    ORDER BY panel_code
</code>```

Getting the error, Windowed functions cannot be used in the context of another one. Please help how can i solve this problem.

答:
I have no idea what you are really trying to do.  But you should definitely learn to use proper, explicit JOIN syntax.

But there is no need to nest the functions.  Your logic should be equivalent to:

```<code>row_number() over (partition by o.panel_id, o.combo_type_code
                   order by o.panel_id
                  ) as rank
</code>```

Why does this use row_number() instead of rank()?  Your original order by used row_number() which never has duplicates.  Hence, if rank() could use it, the values would all be distinct, and the rank() would be equivalent to row_number() -- even when panel_id is duplicated.

Body:
I am trying to get the row number for the rank. Below is the query,

 SELECT *
FROM (
    SELECT DISTINCT TOP 100 PERCENT rank() OVER (
                PARTITION BY o.panel_id
                ,o.combo_type_code ORDER BY row_number() OVER (
                        ORDER BY o.panel_id
                        )
                ) AS rank
            ,panel_code
        FROM tbk_offer_head o
            ,tbk_combo_type ct
            ,tbk_panel p
        WHERE o.panel_id = p.panel_id
            AND o.combo_type_code = ct.combo_type_code
            AND o.panel_id IN (
                SELECT p.panel_id
                FROM tbk_panel p
                WHERE p.campaign_id = 7392
                )
        ) A
    WHERE A.rank = 1
    ORDER BY panel_code

Getting the error, Windowed functions cannot be used in the context of another one. Please help how can i solve this problem.

Body:
I have no idea what you are really trying to do.  But you should definitely learn to use proper, explicit JOIN syntax.

But there is no need to nest the functions.  Your logic should be equivalent to:

row_number() over (partition by o.panel_id, o.combo_type_code
                   order by o.panel_id
                  ) as rank

Why does this use row_number() instead of rank()?  Your original order by used row_number() which never has duplicates.  Hence, if rank() could use it, the values would all be distinct, and the rank() would be equivalent to row_number() -- even when panel_id is duplicated.


问:
React Native and Drawer : undefined is not an object navigator
I want to set up a sidebar menu with Drawer (Native Base).

I have a App.js :

```<code>export default class ReactProject extends Component {

 renderScene (route, navigator) {
  return <route.component navigator={navigator} />
}

render() {
  return (
  <Navigator
  style={styles.container}
  renderScene={this.renderScene.bind(this)}
  initialRoute={{component: Home}}
  />
  );
}
}
</code>```

A Home.js with the drawer :

```<code>export default class Home extends Component {

    render() {
    return (
      <Drawer
        ref={(ref) => { this._drawer = ref; }}
        content={<SideBar />} navigator={this.props.navigator}>
        <Container>
        </Container>
      </Drawer>
    );
}
}
</code>```

And sidebar.js which is loaded into the drawer :

```<code>export default class SideBar extends Component {

constructor(props) {
    super(props);
}

redirect(routeName){
    this.props.navigator.push({
      component: routeName
    });
  }

  render() {
    return (
      <Content style={styles.sidebar}>
          <ListItem button >
            <Text>Home</Text>
          </ListItem>
          <ListItem button >
            <Text>Test</Text>
          </ListItem>
           <ListItem button onPress={this.redirect.bind('Blank')}>
            <Text>Blank Page</Text>
          </ListItem>
      </Content>
    );
  }
}
</code>```

But when I click i have this error:

Undefined is not an object (evaluating 'this.props.navigator.push')

I do not have this problem when the button is in the page but only in the sidebar.js

Could someone help me?

thank you,
Thomas.

答:
I think you have to change little bit code of your Home.js as per mentioned below:

```<code>render() {
return (
  <Drawer
    ref={(ref) => { this._drawer = ref; }}
    content={<SideBar navigator={this.props.navigator} />}
    <Container>
    </Container>
  </Drawer>
);
</code>```

And add this lines of code in your sidebar.js file:

```<code>  static propTypes = {
      navigator: React.PropTypes.object,
   }
</code>```

Body:
I want to set up a sidebar menu with Drawer (Native Base).

I have a App.js :

export default class ReactProject extends Component {

 renderScene (route, navigator) {
  return <route.component navigator={navigator} />
}

render() {
  return (
  <Navigator
  style={styles.container}
  renderScene={this.renderScene.bind(this)}
  initialRoute={{component: Home}}
  />
  );
}
}

A Home.js with the drawer :

export default class Home extends Component {

    render() {
    return (
      <Drawer
        ref={(ref) => { this._drawer = ref; }}
        content={<SideBar />} navigator={this.props.navigator}>
        <Container>
        </Container>
      </Drawer>
    );
}
}

And sidebar.js which is loaded into the drawer :

export default class SideBar extends Component {

constructor(props) {
    super(props);
}

redirect(routeName){
    this.props.navigator.push({
      component: routeName
    });
  }

  render() {
    return (
      <Content style={styles.sidebar}>
          <ListItem button >
            <Text>Home</Text>
          </ListItem>
          <ListItem button >
            <Text>Test</Text>
          </ListItem>
           <ListItem button onPress={this.redirect.bind('Blank')}>
            <Text>Blank Page</Text>
          </ListItem>
      </Content>
    );
  }
}

But when I click i have this error:

Undefined is not an object (evaluating 'this.props.navigator.push')

I do not have this problem when the button is in the page but only in the sidebar.js

Could someone help me?

thank you,
Thomas.

Body:
I think you have to change little bit code of your Home.js as per mentioned below:

render() {
return (
  <Drawer
    ref={(ref) => { this._drawer = ref; }}
    content={<SideBar navigator={this.props.navigator} />}
    <Container>
    </Container>
  </Drawer>
);

And add this lines of code in your sidebar.js file:

  static propTypes = {
      navigator: React.PropTypes.object,
   }


问:
I want to read and confirm data from a dictionary
I want to write a simple login script for existing users, I've created a dictionary for it but my code doesn't work.

I've tried the following:

```<code>d = {'apple':'red','green':'lettuce','yellow':'lemon','orange':'orange'}
print "Please enter your username: "
user_name = raw_input()
print "Please enter your password: "
password = raw_input
for user_name,password in d:
    if user_name in d and password in d:
        print "great"
    else:
        print "Password incorrect!"
</code>```

The code doesn't work, I always get incorrect password.

答:
```<code>d = {'apple':'red','green':'lettuce','yellow':'lemon','orange':'orange'}

user_name = raw_input() #apple
password = raw_input() # red

if user_name in d.keys():
    #check if username: apple == password : red (key=value)
    if password == d.get(user_name)
        print "great"
    else:
        print "Password incorrect!"
</code>```

Body:
I want to write a simple login script for existing users, I've created a dictionary for it but my code doesn't work.

I've tried the following:

d = {'apple':'red','green':'lettuce','yellow':'lemon','orange':'orange'}
print "Please enter your username: "
user_name = raw_input()
print "Please enter your password: "
password = raw_input
for user_name,password in d:
    if user_name in d and password in d:
        print "great"
    else:
        print "Password incorrect!"

The code doesn't work, I always get incorrect password.


问:
AngularJS mechanism to ask server for token based status
In my client side I have a button that triggers an api call that take few minuts to reply, so in the server side I want to return a token to the client and and then the client can ask for status based on the token.

How the client can ask for status every 1 min lets say? and I also dont want to use database and just want to save the token in cache, how can I do that too?

thansk!

答:
This might not be the best or the only solution. But I have been using this library for a while and its good and simple.

ngIdle  helps you track the time against your angular app and perform function as and when that time elapses. This is usually for a timeout and idle type of stuff but I suppose you too can use it.

Usage:

In your app's config, initialize the library as:

```<code> function ConfigFn(IdleProvider) {

        //set configuration for ng-idle
        IdleProvider.idle(60); //in seconds
        IdleProvider.timeout(120); //do not use this if not really required
}
</code>```

AFAIK, it provides you 2 time hooks and an event is raised at each time hook. You can listen to this event and perform any function.

In your run block :

```<code>function runtimeFn(Idle) {
        //setting a timer watch as soon as application bootstraps, you have to reset it every time your time elapses and you call server.
        Idle.watch(); //Idle is just a service from the library

        //responsing to various events in the application
        $rootScope.$on('IdleStart', callServerForToken);
        $rootScope.$on('IdleTimeout', doSomethingAgainIfYouWant); //do not use this if not really required
    }
</code>```

This should help you. Let me know if something remains unclear.

Body:
This might not be the best or the only solution. But I have been using this library for a while and its good and simple.

ngIdle  helps you track the time against your angular app and perform function as and when that time elapses. This is usually for a timeout and idle type of stuff but I suppose you too can use it.

Usage:

In your app's config, initialize the library as:

 function ConfigFn(IdleProvider) {

        //set configuration for ng-idle
        IdleProvider.idle(60); //in seconds
        IdleProvider.timeout(120); //do not use this if not really required
}

AFAIK, it provides you 2 time hooks and an event is raised at each time hook. You can listen to this event and perform any function.

In your run block :

function runtimeFn(Idle) {
        //setting a timer watch as soon as application bootstraps, you have to reset it every time your time elapses and you call server.
        Idle.watch(); //Idle is just a service from the library

        //responsing to various events in the application
        $rootScope.$on('IdleStart', callServerForToken);
        $rootScope.$on('IdleTimeout', doSomethingAgainIfYouWant); //do not use this if not really required
    }

This should help you. Let me know if something remains unclear.


问:
AWS DynamoDB Table Design: Store two UserIDs and Details in Table
I'm building an app where two users can connect with each other and I need to store that connection (e.g. a friendship) in a DynamoDB table. Basically, the connection table has have two fields:

userIdA (hash key)

userIdB (sort key)

I was thinking to add an index on userIdB to query on both fields. Should I store a connection with one record (ALICE, BOB) or two records (ALICE, BOB; BOB, ALICE)? The first option needs one write operation and less space, but I have to query twice to get all all connections of an user. The second option needs two write operations and more space, but I only have to query once for the userId.

The user tablehas details like name and email:

userId (hash key)

name (sort key)

email

In my app, I want to show all connections of a certain user with user details in a listview. That means I have two options:

Store the user details of the connected users also in the connection table, e.g. add two name fields to that table. This is fast, but if the user name changes (name and email are retrieved from Facebook), the details are invalid and I need to update all entries.

Query the user details of each userId with a Batch Get request to read multiple items. This may be slower, but I always have up to date user details and don't need to store them in the connection table.

So what is the better solution, or are there any other advantages/disadvantages that I may have overlooked?

EDIT

After some google research regarding friendship tables with NoSQL databases, I found the following two links:

How does Facebook maintain a list of friends for each user? Does it maintain a separate table for each user?

NoSQL Design Patterns for Relational Data

The first link suggests to store the connection (or friendship) in a two way direction with two records, because it makes it easier and faster to query:

```<code>Connections:
    1 userIdA    userIdB
    2 userIdB    userIdA
</code>```

The second link suggests to save a subset of duplicated data (“summary”) into the tables to read it faster with just one query. That would be mean to save the user details also into the connection table and to save the userIds into an attribute of the user table:

```<code>Connections:
    #    userIdA    userIdB    userDetails                    status
    1        123        456    { userId: 456, name: "Bob" }   connected
    2        456        123    { userId: 123, name: "Alice" } connected

Users:
    #     userId       name    connections
    1        123      Alice    { 456 }
    2        456        Bob    { 123 }
</code>```

This database model makes it pretty easy to query connections, but seems to be difficult to update if some user details may change. Also, I'm not sure if I need the userIds within the user table again because I can easily query on a userId.

What do you think about that database model?

答:
I suggest you have the following fields in the table:

userId (hash key)

name (sort key)

email

connections (Comma separated or an array of userId assuming you have multiple connections for a user)

This structure can ensure consistency across your data.

Body:
I'm building an app where two users can connect with each other and I need to store that connection (e.g. a friendship) in a DynamoDB table. Basically, the connection table has have two fields:

userIdA (hash key)

userIdB (sort key)

I was thinking to add an index on userIdB to query on both fields. Should I store a connection with one record (ALICE, BOB) or two records (ALICE, BOB; BOB, ALICE)? The first option needs one write operation and less space, but I have to query twice to get all all connections of an user. The second option needs two write operations and more space, but I only have to query once for the userId.

The user tablehas details like name and email:

userId (hash key)

name (sort key)

email

In my app, I want to show all connections of a certain user with user details in a listview. That means I have two options:

Store the user details of the connected users also in the connection table, e.g. add two name fields to that table. This is fast, but if the user name changes (name and email are retrieved from Facebook), the details are invalid and I need to update all entries.

Query the user details of each userId with a Batch Get request to read multiple items. This may be slower, but I always have up to date user details and don't need to store them in the connection table.

So what is the better solution, or are there any other advantages/disadvantages that I may have overlooked?

EDIT

After some google research regarding friendship tables with NoSQL databases, I found the following two links:

How does Facebook maintain a list of friends for each user? Does it maintain a separate table for each user?

NoSQL Design Patterns for Relational Data

The first link suggests to store the connection (or friendship) in a two way direction with two records, because it makes it easier and faster to query:

Connections:
    1 userIdA    userIdB
    2 userIdB    userIdA

The second link suggests to save a subset of duplicated data (“summary”) into the tables to read it faster with just one query. That would be mean to save the user details also into the connection table and to save the userIds into an attribute of the user table:

Connections:
    #    userIdA    userIdB    userDetails                    status
    1        123        456    { userId: 456, name: "Bob" }   connected
    2        456        123    { userId: 123, name: "Alice" } connected

Users:
    #     userId       name    connections
    1        123      Alice    { 456 }
    2        456        Bob    { 123 }

This database model makes it pretty easy to query connections, but seems to be difficult to update if some user details may change. Also, I'm not sure if I need the userIds within the user table again because I can easily query on a userId.

What do you think about that database model?


问:
How to configure Wildfly 8.2 to include ETag response header for static files (html, js, css, etc)
I am running into to some caching problems because Wildfly 8.2 only includes the Last-Modified response header by default when serving static files from a deployed war file. I would like Wildfly to include ETag, response header, which would solve my caching problems. Does anyone know if possible to configure in the standalone.xml file?</p>

答:
I have implemented workaround with special "resource" servlet serving war resources with ETag header.

Servlet extends from FileServlet class implemented in Omnifaces library (http://showcase.omnifaces.org/servlets/FileServlet). FileServlet implementation handles all HTTP caching headers correctly, all you need is to implement resource loading method getFile() to serve war resource files.
Here is the example for correct cached serving all resources from "app" directory:

```<code>@WebServlet(value = {"/app/*"})
public class ApplicationResourceServlet extends FileServlet {

  @Override
  protected File getFile(HttpServletRequest request) throws IllegalArgumentException {
    final String pathInfo = request.getPathInfo();
    if (pathInfo == null || pathInfo.isEmpty() || "/".equals(pathInfo)) {
        return null;
    }
    final String realPath = getServletContext().getRealPath("/app" + pathInfo);
    if (realPath != null && Paths.get(realPath).toFile().exists()) {
        return new File(realPath);
    }
    return null;
  }
}
</code>```

Body:
I have implemented workaround with special "resource" servlet serving war resources with ETag header.

Servlet extends from FileServlet class implemented in Omnifaces library (http://showcase.omnifaces.org/servlets/FileServlet). FileServlet implementation handles all HTTP caching headers correctly, all you need is to implement resource loading method getFile() to serve war resource files.
Here is the example for correct cached serving all resources from "app" directory:

@WebServlet(value = {"/app/*"})
public class ApplicationResourceServlet extends FileServlet {

  @Override
  protected File getFile(HttpServletRequest request) throws IllegalArgumentException {
    final String pathInfo = request.getPathInfo();
    if (pathInfo == null || pathInfo.isEmpty() || "/".equals(pathInfo)) {
        return null;
    }
    final String realPath = getServletContext().getRealPath("/app" + pathInfo);
    if (realPath != null && Paths.get(realPath).toFile().exists()) {
        return new File(realPath);
    }
    return null;
  }
}


问:
Django - how can i filter a list of objects checking a foreign key attribute?
First of all sorry for my bad English.

I have to filter a query but using a foreign key attribute. I have a WorkOrder model and have other model with the order movements.

this is the model

```<code>class OrderMovements(models.Model):
    workorder = models.ForeignKey(
            WorkOrder,
            verbose_name=_('order'),
        )
    status = models.IntegerField(
            choices=FULL_CHOICES,
            default=1,
            verbose_name=_('status'),
        )
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
</code>```

Well like you see a work order can have a lot of movements, the queryset that i need to make is a query that take the last 10 WorkOrders that have a OrderMovement with status 3 or 4 included in any of the movements of that WorkOrder.

I really don't know how can a make this.

Hope you can understand me.

Thanks!

答:
First use related_name to easily perform reverse relation look ups

```<code>class OrderMovements(models.Model):
    workorder = models.ForeignKey(
        WorkOrder,
        related_name='ordermovements',
        verbose_name=_('order'),
    )
    // rest code
</code>```

Then you can query workorder and use related_name for reverse relationship filter.

Also you require distinct to avoid duplicates

Your query should be:

```<code>WorkOrder.objects.order_by('-timestamp').filter(
    ordermovements__status__in=[3, 4]).distinct('-timestamp')[:10]
</code>```

Body:
First of all sorry for my bad English.

I have to filter a query but using a foreign key attribute. I have a WorkOrder model and have other model with the order movements.

this is the model

class OrderMovements(models.Model):
    workorder = models.ForeignKey(
            WorkOrder,
            verbose_name=_('order'),
        )
    status = models.IntegerField(
            choices=FULL_CHOICES,
            default=1,
            verbose_name=_('status'),
        )
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)

Well like you see a work order can have a lot of movements, the queryset that i need to make is a query that take the last 10 WorkOrders that have a OrderMovement with status 3 or 4 included in any of the movements of that WorkOrder.

I really don't know how can a make this.

Hope you can understand me.

Thanks!

Body:
First use related_name to easily perform reverse relation look ups

class OrderMovements(models.Model):
    workorder = models.ForeignKey(
        WorkOrder,
        related_name='ordermovements',
        verbose_name=_('order'),
    )
    // rest code

Then you can query workorder and use related_name for reverse relationship filter.

Also you require distinct to avoid duplicates

Your query should be:

WorkOrder.objects.order_by('-timestamp').filter(
    ordermovements__status__in=[3, 4]).distinct('-timestamp')[:10]


问:
If-else statement giving error
normal if else statement is working but optimized if else not working

calVal == "0" ? "1" : employee.TotalLeaveDays.TotalCorrectValue.ToString();

答:
```<code>calVal == "0" ? "1" : employee.TotalLeaveDays.TotalCorrectValue.ToString();
</code>```

statement will return true or false so must assign to any variable or kept this statement in if condition.

Title: If-else statement giving error

Body:
calVal == "0" ? "1" : employee.TotalLeaveDays.TotalCorrectValue.ToString();

statement will return true or false so must assign to any variable or kept this statement in if condition.


问:
Cell coloring vba excel
I tried to write code to colour all cells in column D which are not in the format ow,ol,od.  However my code coloured all cells, regardless of the cell value. I could need your help.

Data Column D

```<code>Sub colour()

For Z = 1 To ActiveSheet.UsedRange.Rows.Count
  If Cells(Z, 4) = "OW" And Cells(Z + 1, 4) = "OL" And Cells(Z + 2, 4) = "OA" Then
    Else
    Cells(Z, 4).Interior.ColorIndex = 7
  End If
Next Z

End Sub
</code>```

答:
```<code>If Cells(Z, 4) = "OW" And Cells(Z + 1, 4) = "OL" And Cells(Z + 2, 4) = "OA"
</code>```

Your code checks (I even tested it) if 3 consecutive cells in a column have the values "OW", "OL" and "OA". For example if D1 = "OW" , D2 = "OL" and D3 = "OA" then the cell D1 won't get colored. In every other case it will.

If this isn't what you are looking for then try to elaborate your goal.

Title: Cell coloring vba excel

Body:
I tried to write code to colour all cells in column D which are not in the format ow,ol,od.  However my code coloured all cells, regardless of the cell value. I could need your help.

Data Column D

Sub colour()

For Z = 1 To ActiveSheet.UsedRange.Rows.Count
  If Cells(Z, 4) = "OW" And Cells(Z + 1, 4) = "OL" And Cells(Z + 2, 4) = "OA" Then
    Else
    Cells(Z, 4).Interior.ColorIndex = 7
  End If
Next Z

End Sub

Body:
If Cells(Z, 4) = "OW" And Cells(Z + 1, 4) = "OL" And Cells(Z + 2, 4) = "OA"

Your code checks (I even tested it) if 3 consecutive cells in a column have the values "OW", "OL" and "OA". For example if D1 = "OW" , D2 = "OL" and D3 = "OA" then the cell D1 won't get colored. In every other case it will.

If this isn't what you are looking for then try to elaborate your goal.


问:
marker.setIcon throws java.lang.IllegalArgumentException: Unmanaged descriptor
I am having trouble with changing googlemap marker on the googlemap.

Neither this method works

```<code>MarkerOptions markerOptions = new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(MarkerManager.getBitmapFromVectorDrawable(context, R.drawable.marker_no_issues)));
                    marker.setIcon(markerOptions.getIcon());
</code>```

nor this

```<code>marker.setIcon(BitmapDescriptorFactory.fromBitmap(MarkerManager.getBitmapFromVectorDrawable(context, R.drawable.marker_no_issues)));
</code>```

Method getBitmapFromVectorDrawable:

```<code>public static Bitmap getBitmapFromVectorDrawable(Context context, int drawableId) {
    Drawable drawable = AppCompatDrawableManager.get().getDrawable(context, drawableId);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        drawable = (DrawableCompat.wrap(drawable)).mutate();
    }

    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
            drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}
</code>```

What i am doing wrong? Why i cant change marker icon with setIcon method.
I have also tried raw .png files and i know that vector to bitmap works well.

答:
I had the same problem solved this as follows -
before setting the icon to the marker object just check if the marker is still visible on googlemap
If you had cleared the map and setting the icon to this marker object on map,
would result in this error

In that case, just create another new object instead of updating the same object by setter methods

Body:
I am having trouble with changing googlemap marker on the googlemap.

Neither this method works

MarkerOptions markerOptions = new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(MarkerManager.getBitmapFromVectorDrawable(context, R.drawable.marker_no_issues)));
                    marker.setIcon(markerOptions.getIcon());

nor this

marker.setIcon(BitmapDescriptorFactory.fromBitmap(MarkerManager.getBitmapFromVectorDrawable(context, R.drawable.marker_no_issues)));

Method getBitmapFromVectorDrawable:

public static Bitmap getBitmapFromVectorDrawable(Context context, int drawableId) {
    Drawable drawable = AppCompatDrawableManager.get().getDrawable(context, drawableId);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        drawable = (DrawableCompat.wrap(drawable)).mutate();
    }

    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
            drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}

What i am doing wrong? Why i cant change marker icon with setIcon method.
I have also tried raw .png files and i know that vector to bitmap works well.


问:
Converting <select></option> in  links (Ajax)
My ajax script is working fine with this:

```<code><head>
<script>
function showUser(str) {
    if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("txtHint").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET","y.php?q="+str,true);
        xmlhttp.send();
    }
}
</script>
</head>

<select  onchange="showUser(this.value)">
  <option value="">Select a person:</option>
  <option value="1">Peter Griffin</option>
  <option value="2">Lois Griffin</option>
  <option value="3">Joseph Swanson</option>
  <option value="4">Glenn Quagmire</option>
  <option value="5">Glenn Quagmire</option>
  </select>
</code>```

But, instead of <select><option>I want to convert it into link.

But the ajax script do not work, when I do this:

```<code><div onchange="showUser(this.value)">
<a value="1" href="">1</a>
<a value="2" href="">2</a>
<a value="3" href="">3</a>
</div>
</code>```

How to change them? I need them for pagination.

答:
You need to remove onchange and can add below HTML & JQuery code. Now that we have div and a tags, we should use click() event.

$(".selectOptions a").on('click', function() {
  alert('You clicked on: ' + $(this).attr('value'));
  return false;
});```
<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="selectOptions">
  1
  2
  3
</div></code>```

Body:
My ajax script is working fine with this:

<select  onchange="showUser(this.value)">
  <option value="">Select a person:</option>
  <option value="1">Peter Griffin</option>
  <option value="2">Lois Griffin</option>
  <option value="3">Joseph Swanson</option>
  <option value="4">Glenn Quagmire</option>
  <option value="5">Glenn Quagmire</option>
  </select>

But, instead of <select><option>I want to convert it into link.

But the ajax script do not work, when I do this:

1
2
3

How to change them? I need them for pagination.

Body:
You need to remove onchange and can add below HTML & JQuery code. Now that we have div and a tags, we should use click() event.

$(".selectOptions a").on('click', function() {
  alert('You clicked on: ' + $(this).attr('value'));
  return false;
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="selectOptions">
  <a value="1" href="">1</a>
  <a value="2" href="">2</a>
  <a value="3" href="">3</a>
</div>


问:
Cannot add user to Sharepoint 2010 within event handler
Using both synchronous and asycnhronous event handlers (itemAdded and itemAdding), I have been unable to add a user to my Sharepoint 2010 site - using Forms Based Authentication (which I know to be properly setup and working because it has been working perfectly from the Sharepoint UI from what I can tell)

Calling Membership.CreateUser is not working and constantly throws an exception of "object reference not set to an instance of an object".  Debugging and looking into Membership, it is clear that something is wrong. Most members are null or throw exceptions as well.  I know Membership doesn't have this issue in an Application Page (I can add users, add them to groups, etc.. from an Application page, but it fails inside of an event handler).  We originally thought it was a HttpContext issue, but we can get HttpContext.Current inside itemAdding(), so that might not make much difference.

Any clues?  Is it possible to add users to SP2010 within an event handler?

Background: when I add a new row to a list (with an Email column), permissions are granted to the user with the specified email address - if that user doesn't exist I want to create it (again, for Forms Based Authentication)

答:
Im have never done any share point development but it sounds like a cross thread problem.. The event will create a new thread which wont have acces to the thread that contains 'Membership'. try passing it through using a delegate?
eg</p>

```<code>Object.ItemAdded+= (o, args) => Class.Method(o, args, Membership);
</code>```

Body:
Im have never done any share point development but it sounds like a cross thread problem.. The event will create a new thread which wont have acces to the thread that contains 'Membership'. try passing it through using a delegate?
eg

Object.ItemAdded+= (o, args) => Class.Method(o, args, Membership);


问:
Entity Framework GroupBy, Select all if one
I have a table and I want to Group the table by its Id, and also for example, if I search for "Statoil Nig Ltd" in ValStr column, I want to retrieve all the data in ValStr with the same id (323439, in such a way that each can be used individually like this (i.e title will be a string from the ValStr, address will be another string).

So far this is what I've done:

```<code>var groups = _entities.LLAttrDatas
    .Where(r => r.ValStr.Contains("4502207741") && r.AttrID == 2)
    .GroupBy(r => r.ID);

foreach (var group in groups)
{
    Console.WriteLine("List with ID == {0}", group.Key);

    foreach (var item in group)
    {
        if (item.ValStr.Contains("4502207741") && item.AttrID == 2)
        {
        }

        Console.WriteLine(" Item: {0}", item.ValStr);
    }
}
</code>```

Please how do I go about this?

答:
I think I understand what you're looking for...
If you want to get all sets, grouped by ID, that share a common value (valStr /w given AttrId) then what you have is close to there:

```<code>var ids = _entities.LLAttrDatas
  .Where(r=> r.Valstr.Contains("4502207741") && r.AttrId == 2)
  .Select(r=> r.ID);
var groups = _entities.LLAtrDatas
  .Where(r=> ids.Contains(r.ID))
  .GroupBy(r=> r.ID);
</code>```

From there you would have a set of Groups of related items, by ID, that each contained the requested search criteria.

Body:
I have a table and I want to Group the table by its Id, and also for example, if I search for "Statoil Nig Ltd" in ValStr column, I want to retrieve all the data in ValStr with the same id (323439, in such a way that each can be used individually like this (i.e title will be a string from the ValStr, address will be another string).

So far this is what I've done:

var groups = _entities.LLAttrDatas
    .Where(r => r.ValStr.Contains("4502207741") && r.AttrID == 2)
    .GroupBy(r => r.ID);

foreach (var group in groups)
{
    Console.WriteLine("List with ID == {0}", group.Key);

    foreach (var item in group)
    {
        if (item.ValStr.Contains("4502207741") && item.AttrID == 2)
        {
        }

        Console.WriteLine(" Item: {0}", item.ValStr);
    }
}

Please how do I go about this?

Body:
I think I understand what you're looking for...
If you want to get all sets, grouped by ID, that share a common value (valStr /w given AttrId) then what you have is close to there:

var ids = _entities.LLAttrDatas
  .Where(r=> r.Valstr.Contains("4502207741") && r.AttrId == 2)
  .Select(r=> r.ID);
var groups = _entities.LLAtrDatas
  .Where(r=> ids.Contains(r.ID))
  .GroupBy(r=> r.ID);

From there you would have a set of Groups of related items, by ID, that each contained the requested search criteria.