问:
Calling a controller action using AJAX with an anchor vs a button
I have a IActionResult on my controller that returns a Partial View via AJAX:

```<code>[HttpGet]
[Route("/propertycoverages/loss")]
public IActionResult GetNewLoss()
{
    return PartialView("_Loss");
}
</code>```

If I put an  tag in my Razor view with the following:

```<code><a asp-controller="PropertyCoverages" asp-action="GetNewLoss" id="loss-btn" data-ajax="true" data-ajax-update="losses" data-ajax-success="addLoss" data-ajax-method="GET">Add</a>
</code>```

the following HTML attribute gets generated in the  tag: href="/propertycoverages/loss"

it works as expected and the partial view is returned within the page. However, if I try to use a button:

```<code><button asp-controller="PropertyCoverages" asp-action="GetNewLoss" id="loss-btn" type="submit" data-ajax="true" data-ajax-update="losses" data-ajax-success="addLoss" data-ajax-method="GET">Add</button>
</code>```

the following HTML attribute gets generated in the <button> tag: formaction="/propertycoverages/loss"

and I get redirected to /propertycoverages/loss which is not what I want. Is there a way I can make the button behave like the  tag?

Note: These elements are inside a <form>. I also tried switching the <button> from type="submit" to type="button" but the controller action doesn't get called.

答:
You will want to attach a JavaScript method to your button click action.

```<code><button onclick="myFunction()">Click me</button>
</code>```

In the JS method you can call back to the action get the HTML and lay in on the page in the AJAX call success method.

```<code>    function onClick() {
    var url = [setURL];

        $.ajax({
            type: "GET",
            url: url,
            data: { },
            success: function (response) {
                $('#[setElementToReplace]').html(response);
            }
        });
    }
</code>```

Body:
I have a IActionResult on my controller that returns a Partial View via AJAX:

[HttpGet]
[Route("/propertycoverages/loss")]
public IActionResult GetNewLoss()
{
    return PartialView("_Loss");
}

If I put an  tag in my Razor view with the following:

Add

the following HTML attribute gets generated in the  tag: href="/propertycoverages/loss"

it works as expected and the partial view is returned within the page. However, if I try to use a button:

<button asp-controller="PropertyCoverages" asp-action="GetNewLoss" id="loss-btn" type="submit" data-ajax="true" data-ajax-update="losses" data-ajax-success="addLoss" data-ajax-method="GET">Add</button>

the following HTML attribute gets generated in the <button> tag: formaction="/propertycoverages/loss"

and I get redirected to /propertycoverages/loss which is not what I want. Is there a way I can make the button behave like the  tag?

Note: These elements are inside a <form>. I also tried switching the <button> from type="submit" to type="button" but the controller action doesn't get called.

Body:
You will want to attach a JavaScript method to your button click action.

<button onclick="myFunction()">Click me</button>

In the JS method you can call back to the action get the HTML and lay in on the page in the AJAX call success method.

    function onClick() {
    var url = [setURL];

        $.ajax({
            type: "GET",
            url: url,
            data: { },
            success: function (response) {
                $('#[setElementToReplace]').html(response);
            }
        });
    }


来源: stackexchange

问:
Copying text from many div to many input value
I have a page with many product listed. Each of those products is inside a div and has a form like this:

```<code><form class="cart" method="post" enctype="multipart/form-data">
    <input type="hidden" name="add-to-cart" value="">
    <button type="submit" class="single_add_to_cart_button button">Add to Cart</button>
</form>
</code>```

As you can see the value of add-to-cart is missing.

In the same div where the form is, we have an other div like this that contains the ID of the product (for instance IDPRODUCT), that needs to go inside the value:

```<code><div class="vc_gitem-woocommerce vc_gitem-woocommerce-product-id hideidfromcart vc_gitem-align-left">IDPRODUCT</div>
</code>```

I need a javascript function that on document ready(?) or onmouseover the div searches for the value inside the div, for instance IDPRODUCT, and copy this value into the value of the input name="add-to-cart"

Of course for each of those different divs there should be the proper IDPRODUCT.

Here is one JSFiddle I tried but it doesn't seem to work:JSFiddle

Any idea of how to solve this?
Thank you so much

答:
UPDATE

The full Example again

$('.cart-add-wrapper').each(function(){
    var id = $(this).find('.vc_gitem-woocommerce-product-id').text();
    $(this).find('input[name=add-to-cart]').val(id);
    console.log("id", id);
});```
<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="cart-add-wrapper">
    <form class="cart" method="post" enctype="multipart/form-data">
        <input type="hidden" name="add-to-cart" value="">
        <button type="submit" class="single_add_to_cart_button button">Add to Cart</button>
    </form>
    <div class="vc_gitem-woocommerce vc_gitem-woocommerce-product-id hideidfromcart vc_gitem-align-left">4321</div>
</div>
<div class="cart-add-wrapper">
    <form class="cart" method="post" enctype="multipart/form-data">
        <input type="hidden" name="add-to-cart" value="">
        <button type="submit" class="single_add_to_cart_button button">Add to Cart</button>
    </form>
    <div class="vc_gitem-woocommerce vc_gitem-woocommerce-product-id hideidfromcart vc_gitem-align-left">1234</div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a page with many product listed. Each of those products is inside a div and has a form like this:

<form class="cart" method="post" enctype="multipart/form-data">
    <input type="hidden" name="add-to-cart" value="">
    <button type="submit" class="single_add_to_cart_button button">Add to Cart</button>
</form>

As you can see the value of add-to-cart is missing.

In the same div where the form is, we have an other div like this that contains the ID of the product (for instance IDPRODUCT), that needs to go inside the value:

IDPRODUCT

I need a javascript function that on document ready(?) or onmouseover the div searches for the value inside the div, for instance IDPRODUCT, and copy this value into the value of the input name="add-to-cart"

Of course for each of those different divs there should be the proper IDPRODUCT.

Here is one JSFiddle I tried but it doesn't seem to work:JSFiddle

Any idea of how to solve this?
Thank you so much

Body:
UPDATE

The full Example again

$('.cart-add-wrapper').each(function(){
    var id = $(this).find('.vc_gitem-woocommerce-product-id').text();
    $(this).find('input[name=add-to-cart]').val(id);
    console.log("id", id);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cart-add-wrapper">
    <form class="cart" method="post" enctype="multipart/form-data">
        <input type="hidden" name="add-to-cart" value="">
        <button type="submit" class="single_add_to_cart_button button">Add to Cart</button>
    </form>
    <div class="vc_gitem-woocommerce vc_gitem-woocommerce-product-id hideidfromcart vc_gitem-align-left">4321</div>
</div>
<div class="cart-add-wrapper">
    <form class="cart" method="post" enctype="multipart/form-data">
        <input type="hidden" name="add-to-cart" value="">
        <button type="submit" class="single_add_to_cart_button button">Add to Cart</button>
    </form>
    <div class="vc_gitem-woocommerce vc_gitem-woocommerce-product-id hideidfromcart vc_gitem-align-left">1234</div>
</div>


问:
SonarQube issue raised on use of string formatter
SonarQube is raising an issue on my string formatter use:

Format specifiers should be used instead of string concatenation.

I have used below java code to add padding 0 in the number.

```<code>int paddingLength = seqLength - seqNoLength;
String.format("%0" + paddingLength + "d", seqNo);
</code>```

答:
The issue is raised because you're passing a concatenated string to your formatter. If you're going to use string formatting, then use string formatting:

```<code>int paddingLength = seqLength - seqNoLength;
String fmt = String.format("%%0%dd", paddingLength);
String.format(fmt, seqNo);
</code>```

Or even

```<code>int paddingLength = seqLength - seqNoLength;
String.format(String.format("%%0%dd", paddingLength), seqNo);
</code>```

Although the first version is far more readable.

Body:
SonarQube is raising an issue on my string formatter use:

Format specifiers should be used instead of string concatenation.

I have used below java code to add padding 0 in the number.

int paddingLength = seqLength - seqNoLength;
String.format("%0" + paddingLength + "d", seqNo);

Body:
The issue is raised because you're passing a concatenated string to your formatter. If you're going to use string formatting, then use string formatting:

int paddingLength = seqLength - seqNoLength;
String fmt = String.format("%%0%dd", paddingLength);
String.format(fmt, seqNo);

Or even

int paddingLength = seqLength - seqNoLength;
String.format(String.format("%%0%dd", paddingLength), seqNo);

Although the first version is far more readable.

ContentLicense: CC BY-SA 4.0


问:
How to run a .bat (that runs an .exe that is in the same directory) as administrator from a pendrive?
I'm able to run a .bat (that runs an .exe that is in the same directory) as administrator: I right-click in the bat file and select "Run as administrator".

To be able to do that, I used the following answer: Run exe from current directory in batch

Here's the code:

@echo off
:A
cls
echo This will start the program.
pause
cd %~dp0
start %1myprogram.exe
exit

However, this will only work if the .bat file and the program are in the system drive.

Because if they are, for instance, in a pendrive, and I right-click and select "Run as Administrator", I get the error:

"Windows cannot find 'myprogram.exe'. Make sure you've typed the name correctly, then try again."

Why this happens and how can I fix it?
I thought that by using cd %~dp0 it would always point to the folder in which the bat .file resides.

Thanks in advance.

答:
If the current drive is C: (e.g., the prompt says C:\>), and you do CD D:\FOO, the current directory on drive D: is set to \FOO, but you will still be "on" drive C:. Try the following:

```<code>@echo off
:A
cls
echo This will start the program.
pause
cd %~dp0
%~d0
start %1myprogram.exe
exit
</code>```

(also, why %1myprogram.exe instead of just myprogram.exe, or even just myprogram? If you're right-clicking on the batch file to run it, there isn't going to be a %1.)

Body:
If the current drive is C: (e.g., the prompt says C:\>), and you do CD D:\FOO, the current directory on drive D: is set to \FOO, but you will still be "on" drive C:. Try the following:

@echo off
:A
cls
echo This will start the program.
pause
cd %~dp0
%~d0
start %1myprogram.exe
exit

(also, why %1myprogram.exe instead of just myprogram.exe, or even just myprogram? If you're right-clicking on the batch file to run it, there isn't going to be a %1.)


问:
Handsontable - Horizontal Scroll Bar Disappearing
I have created four Handsontable instances split evenly accross four windows using a library called split.js.

I have then enabled scroll bars on each window by setting the containers overflow to auto.

```<code>#equipment {
  overflow: auto;
}
</code>```

This successfully displays the scroll bars in the vertical position under all GUI manipulation.

However, the horizontal scroll bars are a bit more buggy. Specifically, on initial load of the windows the horizontal scroll bars are nowhere to be seen. But on dragging the split.js gutters the scroll bar magically appears again! But then on clicking the handsontables within the containers the horizontal scroll bar disspears again (to the base of the handsontable). See image below.

I have also created a fiddle that shows this issue.

https://jsfiddle.net/JoshAdams/4p8jLcnk/

So my question is how do I make the horizontal scroll bar always be displayed under all circumstances above?

答:
The overflow:auto was on an element that had a height higher than it's parent. The parent had overflow:hidden, so the horizontal scroll on the child element was hidden from view. I wasn't sure if you wanted the on hover scroll bars, so I have added it to the CSS but commented it out. Here is an updated fiddle.

https://jsfiddle.net/4p8jLcnk/9/

Body:
I have created four Handsontable instances split evenly accross four windows using a library called split.js.

I have then enabled scroll bars on each window by setting the containers overflow to auto.

#equipment {
  overflow: auto;
}

This successfully displays the scroll bars in the vertical position under all GUI manipulation.

However, the horizontal scroll bars are a bit more buggy. Specifically, on initial load of the windows the horizontal scroll bars are nowhere to be seen. But on dragging the split.js gutters the scroll bar magically appears again! But then on clicking the handsontables within the containers the horizontal scroll bar disspears again (to the base of the handsontable). See image below.

I have also created a fiddle that shows this issue.

https://jsfiddle.net/JoshAdams/4p8jLcnk/

So my question is how do I make the horizontal scroll bar always be displayed under all circumstances above?


问:
reducing list based on fuzzy values in python
I have a list that contains groups of nearly identical numeric values. i.e. (1004.523, 1004.575, 1004.475, 791.385, 791.298, 791.301, 791.305, 791.299)

What I am trying to do is read through the list and find all the 1004.5 +- values aggregate them and find the average value. then continue on and find all the 791.0 +- values and do the same to them.

I do not know how many individual values there will be in each "group" nor do I know how many groups there will be.

The result I am looking for is another list which would contain the average values of each of the groups. So in the example my result would be (1004.524, 791.3176)

The code I'm currently using is very Kludgey and it seems there should be a much better way to do it.

As you can see I have to repeat code twice once in the else and once at the end of the if since the last set of numbers does not trigger the else. Plus at the completion of the if I need to add the last value.

If I use the len(tones) rather that len(tones)-i I get an out of range error.

Any thoughts or suggestions would be appreciated. Thanks for your help.

Ed

```<code>    toneLen = len(tones) -1
    for i in range(0, toneLen):
        if abs(tones[i]-tones[i+1]) <= 2.0:
            tmpTones.append(tones[i])
        else:
            freq = mean(tmpTones)
            newTones.append(freq)
            tmpTones = []
    tmpTones.append(tones[i+1])
    freq = mean(tmpTones)
    newTones.append(freq)
    tones = newTones
</code>```

UPDATE:
First I wanted to thank everyone who submitted suggestions. The response was very quick and helpful. I should have probably included some more info which I am doing below. Thanks so much for your help.

Second , a quick explanation of what I am trying to do. Our local Fire Department is looking for a way to track dispatches for departments close to them. For the most part they use two tone sequential paging i.e. 1000Hz followed by 500Hz.

So I am using numpy fft to find the tone frequency. Since the accuracy of the tone appears to be about +- 2 Hz, I compare the calculated frequency to a list of known paging tones and pick the closest match. After all the tones have been matched to the paging tones I look for matches to departments of interest.

One thing I did not know when I started this that in any given dispatch the same tone can be repeated several times, so the order of the tones is important. An example:
707.3, 339.6, 707.3, 569.1, 447.2, 569.1 would be a typical dispatch. I then look to see if any of the tone pairs are ones I'm interested in if so I display a message

Thanks again for all your help.

Ed

答:
This does without the intermediate temp list:</p>

```<code>assert tones
total = prev = tones[0]
count = 1
newlist = []
for i in xrange(1, len(tones)):
    t = tones[i]
    if abs(t - prev) <= DELTA:
        total += t
        count += 1
        prev = t
    else:
        newlist.append(total / count)
        total = prev = t
        count = 1
newlist.append(total / count)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a list that contains groups of nearly identical numeric values. i.e. (1004.523, 1004.575, 1004.475, 791.385, 791.298, 791.301, 791.305, 791.299)

What I am trying to do is read through the list and find all the 1004.5 +- values aggregate them and find the average value. then continue on and find all the 791.0 +- values and do the same to them.

I do not know how many individual values there will be in each "group" nor do I know how many groups there will be.

The result I am looking for is another list which would contain the average values of each of the groups. So in the example my result would be (1004.524, 791.3176)

The code I'm currently using is very Kludgey and it seems there should be a much better way to do it.

As you can see I have to repeat code twice once in the else and once at the end of the if since the last set of numbers does not trigger the else. Plus at the completion of the if I need to add the last value.

If I use the len(tones) rather that len(tones)-i I get an out of range error.

Any thoughts or suggestions would be appreciated. Thanks for your help.

Ed

    toneLen = len(tones) -1
    for i in range(0, toneLen):
        if abs(tones[i]-tones[i+1]) <= 2.0:
            tmpTones.append(tones[i])
        else:
            freq = mean(tmpTones)
            newTones.append(freq)
            tmpTones = []
    tmpTones.append(tones[i+1])
    freq = mean(tmpTones)
    newTones.append(freq)
    tones = newTones

UPDATE:
First I wanted to thank everyone who submitted suggestions. The response was very quick and helpful. I should have probably included some more info which I am doing below. Thanks so much for your help.

Second , a quick explanation of what I am trying to do. Our local Fire Department is looking for a way to track dispatches for departments close to them. For the most part they use two tone sequential paging i.e. 1000Hz followed by 500Hz.

So I am using numpy fft to find the tone frequency. Since the accuracy of the tone appears to be about +- 2 Hz, I compare the calculated frequency to a list of known paging tones and pick the closest match. After all the tones have been matched to the paging tones I look for matches to departments of interest.

One thing I did not know when I started this that in any given dispatch the same tone can be repeated several times, so the order of the tones is important. An example:
707.3, 339.6, 707.3, 569.1, 447.2, 569.1 would be a typical dispatch. I then look to see if any of the tone pairs are ones I'm interested in if so I display a message

Thanks again for all your help.

Ed

Body:
This does without the intermediate temp list:

assert tones
total = prev = tones[0]
count = 1
newlist = []
for i in xrange(1, len(tones)):
    t = tones[i]
    if abs(t - prev) <= DELTA:
        total += t
        count += 1
        prev = t
    else:
        newlist.append(total / count)
        total = prev = t
        count = 1
newlist.append(total / count)


问:
sql server complex query

1st one is the source table and 2nd one is the destination table, so in 2nd table by using unpivot the the 12 month columns converted into single column and YTD field should be update automatically. If the month name is Jan means the YTD field will Jan data only, if it is Feb means it will add the Jan data with Feb data. same if it is Dec means it will add from Jan to Dec of the same row.

答:
Looks like what you require is to do unpivot as below:</p>

```<code>Select *, [YTD] = sum(yourYTD calculation column) over(partition by [OruCode],[year] order by Month) from (
   Select OruCode, BGName ---your required columns upto dec
       from table1 t1 cross join table2 t2
 )
 unpivot (KPINo for [Month] in ([Jan],[Feb]...) ) p
</code>```

Title: sql server complex query

Body:
Looks like what you require is to do unpivot as below:

Select *, [YTD] = sum(yourYTD calculation column) over(partition by [OruCode],[year] order by Month) from (
   Select OruCode, BGName ---your required columns upto dec
       from table1 t1 cross join table2 t2
 )
 unpivot (KPINo for [Month] in ([Jan],[Feb]...) ) p


问:
What is discovery url of Okta
I am implementing authentication using openid connect. I have successfully implemented the openid - connect in my website. I am using well known url (https://accounts.google.com/.well-known/openid-configuration) to get the endpoint detail so method should be generic for all the sources (Google, Microsoft etc).

I want to authenticate the user using okta. I did not find discover url of okta so that I can fetch the endpoint details of okta.

Can any one provide me the well known url of okta?

答: If you've created a developer account, you can use your instance's URL to find it. For example, my instance's URL is dev-158606.oktapreview.com and my well-known OIDC info is at https://dev-158606.oktapreview.com/.well-known/openid-configuration.</p>

Title: What is discovery url of Okta


问:
How to to skip invalid XML file with incomplete closing tags in PHP
I am using PHP DOM Xpath to read XML files. In some cases tags are not properly closed like below

```<code><data>
   <name> value </name>
   <address
</code>```

I have following code to check if XML is valid

```<code>$doc = new DOMDocument();

if(!$doc->load(test.xml))
 {
      foreach (libxml_get_errors() as $error)
      {
          print_r($error);
      }
        libxml_clear_errors();
 }
 else
 {
     $valid_xml = 'y';
 }

 if($valid_xml=='y')
 // then process XML
 else
 // skip and take next file
</code>```

but I am getting below errors at line if(!$doc->load(test.xml))

```<code>Message: DOMDocument::load(): Couldn't find end of Start Tag AdjustmentsToReconcile

Message: DOMDocument::load(): Premature end of data in tag
</code>```

答: You were almost there. Try adding the command libxml_use_internal_errors(true); before everything to tell PHP not to throw errors but to cache them for you to iterate through as your code is doing.</p>

Body:
I am using PHP DOM Xpath to read XML files. In some cases tags are not properly closed like below

<data>
   <name> value </name>
   <address

I have following code to check if XML is valid

$doc = new DOMDocument();

if(!$doc->load(test.xml))
 {
      foreach (libxml_get_errors() as $error)
      {
          print_r($error);
      }
        libxml_clear_errors();
 }
 else
 {
     $valid_xml = 'y';
 }

 if($valid_xml=='y')
 // then process XML
 else
 // skip and take next file

but I am getting below errors at line if(!$doc->load(test.xml))

Message: DOMDocument::load(): Couldn't find end of Start Tag AdjustmentsToReconcile

Message: DOMDocument::load(): Premature end of data in tag


问:
Firebase send push notification twice
I wrote a very simple android app to test firebase push notification and I get one notification twice.

this is the manifest service:

```<code><service
        android:name="com.google.firebase.messaging.FirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>
    <service
        android:name="com.google.firebase.iid.FirebaseInstanceIdService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>
</code>```

this is the app gradle:

```<code>    compile 'com.google.android.gms:play-services:9.0.0'
    compile 'com.google.firebase:firebase-core:9.0.0'
    compile 'com.google.firebase:firebase-messaging:9.0.0'
}
apply plugin: 'com.google.gms.google-services'
</code>```

and here is the project level gradle:

```<code>classpath 'com.google.gms:google-services:3.0.0'
</code>```

答:
I was having the same problem when application was in background or closed (and sending both notification and data). Caused by requesting old GCM permissions in AndroidManifest.xml

Take a look at https://stackoverflow.com/a/44435980/1533285

Title: Firebase send push notification twice

Body:
I wrote a very simple android app to test firebase push notification and I get one notification twice.

this is the manifest service:

<service
        android:name="com.google.firebase.messaging.FirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>
    <service
        android:name="com.google.firebase.iid.FirebaseInstanceIdService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>

this is the app gradle:

    compile 'com.google.android.gms:play-services:9.0.0'
    compile 'com.google.firebase:firebase-core:9.0.0'
    compile 'com.google.firebase:firebase-messaging:9.0.0'
}
apply plugin: 'com.google.gms.google-services'

and here is the project level gradle:

classpath 'com.google.gms:google-services:3.0.0'


问:
load list depend on category in knockout
trying to make a small application
there is the category ( places, coffee Shops, Clubs)

how to load the list of respective category in the knockout.

how to load the list of tags (only once) and which is clickable and load the tag list when click

here is my code
JS

```<code>var points = [
    {
        tag: "places",
        name: "Dubai Marina",
    }, {
        tag: "places",
        name: "Burj Khalifa",
    }, {
        tag: "Coffee",
        name: "StarBucks",
    }, {
        tag: "Coffee",
        name: "Costa",
    }, {
        tag: "Club",
        name: "Beach Club",
    }, {
        tag: "Club",
        name: "Cheers Club",
    }
];

var View = function (data) {
    this.name = ko.observable(data.name);
};

var ViewModel = function () {
    var self = this;
    this.pointsList = ko.observableArray([]);

    points.forEach(function (e) {
        self.pointsList.push(new View(e));
        console.log(e)
    });

    self.activeTag = function (a) {
        console.log(a);
    }
}
ko.applyBindings(new ViewModel());
</code>```

** HTML**

```<code><ul class="list-inline" data-bind="foreach:points">
        <li data-bind="text:tag, click: activeTag"></li>
    </ul>

    <ul data-bind="foreach:points">
        <li data-bind="text: name"></li>
    </ul>
</code>```

Or is there any better solution?

答:
This is the ideal problem to get familiar with ko.pureComputed properties!

Your viewmodel has two main properties:

An array of Points

A selected "tag"

All other properties can be computed by combining these two. Here's how:

We create a computed object that orders our Points by their tag property.

```<code>{ "Club": [ Point, ... ] }
</code>```

We create a computed array that takes only the selected tag from this object

We create a computed array that takes all keys of the object to represent the available tags

I've moved some code around and chose a <select> box as a quick UI solution.

var Point = function (name, tag) {
  this.name = ko.observable(name);
  this.tag = ko.observable(tag);
};

Point.fromData = function(data) {
  return new Point(data.name, data.tag);
}

var ViewModel = function () {
  // This is a list of Point viewmodels, only used inside the vm
  var pointsList = ko.observableArray(
    getPoints().map(Point.fromData)
  );

  // This is the tag (string) that is selected, or null if there's
  // no selection
  this.activeTag = ko.observable(null);

  // This is an object that orders your points by their tag name in
  // a plain object. I.e.: { 'tagname': [Point] }
  var pointsMap = ko.pureComputed(function() {
    return pointsList().reduce(function(map, point) {
      var tag = point.tag();
      map[tag] = map[tag] || [];
      map[tag].push(point);
      return map;
    }, {});
  }, this);

  // All the keys in our object represent all available tags
  this.allTags = ko.pureComputed(function() {
    return Object.keys(pointsMap()).sort();
  }, this);

  // This is a computed list of Points. It combines the
  // selected tag and takes corresponding Point array from our map
  this.activePoints = ko.pureComputed(function() {
    var tag = this.activeTag();

    return tag
      ? pointsMap()[tag]
      : pointsList();
  }, this);

}

ko.applyBindings(new ViewModel());

function getPoints() {
  return [{tag:"places",name:"Dubai Marina"},{tag:"places",name:"Burj Khalifa"},{tag:"Coffee",name:"StarBucks"},{tag:"Coffee",name:"Costa"},{tag:"Club",name:"Beach Club"},{tag:"Club",name:"Cheers Club"}];
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select data-bind="options: allTags, value: activeTag, optionsCaption: 'no filter'"></select>
<ul data-bind="foreach: activePoints">
    <li data-bind="text: name"></li>
</ul></code>```

Body:
trying to make a small application
there is the category ( places, coffee Shops, Clubs)

how to load the list of respective category in the knockout.

how to load the list of tags (only once) and which is clickable and load the tag list when click

here is my code
JS

var points = [
    {
        tag: "places",
        name: "Dubai Marina",
    }, {
        tag: "places",
        name: "Burj Khalifa",
    }, {
        tag: "Coffee",
        name: "StarBucks",
    }, {
        tag: "Coffee",
        name: "Costa",
    }, {
        tag: "Club",
        name: "Beach Club",
    }, {
        tag: "Club",
        name: "Cheers Club",
    }
];

var View = function (data) {
    this.name = ko.observable(data.name);
};

var ViewModel = function () {
    var self = this;
    this.pointsList = ko.observableArray([]);

    points.forEach(function (e) {
        self.pointsList.push(new View(e));
        console.log(e)
    });

    self.activeTag = function (a) {
        console.log(a);
    }
}
ko.applyBindings(new ViewModel());

** HTML**

Or is there any better solution?

Body:
This is the ideal problem to get familiar with ko.pureComputed properties!

Your viewmodel has two main properties:

An array of Points

A selected "tag"

All other properties can be computed by combining these two. Here's how:

We create a computed object that orders our Points by their tag property.

{ "Club": [ Point, ... ] }

We create a computed array that takes only the selected tag from this object

We create a computed array that takes all keys of the object to represent the available tags

I've moved some code around and chose a <select> box as a quick UI solution.

var Point = function (name, tag) {
  this.name = ko.observable(name);
  this.tag = ko.observable(tag);
};

Point.fromData = function(data) {
  return new Point(data.name, data.tag);
}

var ViewModel = function () {
  // This is a list of Point viewmodels, only used inside the vm
  var pointsList = ko.observableArray(
    getPoints().map(Point.fromData)
  );

  // This is the tag (string) that is selected, or null if there's
  // no selection
  this.activeTag = ko.observable(null);

  // This is an object that orders your points by their tag name in
  // a plain object. I.e.: { 'tagname': [Point] }
  var pointsMap = ko.pureComputed(function() {
    return pointsList().reduce(function(map, point) {
      var tag = point.tag();
      map[tag] = map[tag] || [];
      map[tag].push(point);
      return map;
    }, {});
  }, this);

  // All the keys in our object represent all available tags
  this.allTags = ko.pureComputed(function() {
    return Object.keys(pointsMap()).sort();
  }, this);

  // This is a computed list of Points. It combines the
  // selected tag and takes corresponding Point array from our map
  this.activePoints = ko.pureComputed(function() {
    var tag = this.activeTag();

    return tag
      ? pointsMap()[tag]
      : pointsList();
  }, this);

}

ko.applyBindings(new ViewModel());

function getPoints() {
  return [{tag:"places",name:"Dubai Marina"},{tag:"places",name:"Burj Khalifa"},{tag:"Coffee",name:"StarBucks"},{tag:"Coffee",name:"Costa"},{tag:"Club",name:"Beach Club"},{tag:"Club",name:"Cheers Club"}];
};

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select data-bind="options: allTags, value: activeTag, optionsCaption: 'no filter'"></select>
<ul data-bind="foreach: activePoints">
    <li data-bind="text: name"></li>
</ul>


问:
Django 1.10 Form doesn't store data to DB
I feel very stupid and confused, tackling this issue for so long.
It works completely fine, displays survey fine, however it does not store(save) submited form to my database. I have seen tons of questions/solutions, however none of them helped me.

Here are my models.py

```<code>from __future__ import unicode_literals
from django.db import models
#from multiselectfield import MultiSelectField,
from django.contrib.auth.models import User
#from django.forms import ModelForm
# Create your models here.

    class user_prefs(models.Model):
            cuisine_choice = (
                ('1', 'Italian'),
                ('2', 'American'),
                ('3', 'Japanese'),
                ('4', 'French'),
                ('5', 'Mexican'),
                ('6', 'Chinese'),
                ('7', 'Indian'),
                ('8', 'Middle Eastern')
            )
            lunch_pref = (
                ('1', 'Coffeehouse'),
                ('2', 'Cafe'),
                ('3', 'Restaurant'),
                ('4', 'Fast Food'),
                ('5', 'Takeaway'),
                ('6', 'Stake House')
            )
            dinner_pref = (
                ('1', 'Restaurant'),
                ('2', 'Takeaway'),
                ('3', 'Delivery'),
                ('4', 'Fast food'),
                ('5', 'Coffeehouse'),
                ('6', 'Cafe'),
                ('7', 'Cooking at home')
            )
            sunday = (
                ('1', 'Cultural activities(Museums, Galleries, Exhibitions etc.)'),
                ('2', 'Sport activities'),
                ('3', 'Attending sport events'),
                ('4', 'Music events'),
                ('5', 'Hiking'),
                ('6', 'Going to park')
            )
            friday = (
                ('1', 'Bar'),
                ('2', 'Nightclub'),
                ('3', 'Karaoke'),
                ('4', 'Netflix & chill'),
                ('5', 'Videogames'),
                ('6', 'Cinema'),
                ('7', 'Theater'),
                ('8', 'Restaurant')
            )
            userID = models.ForeignKey(User) #related_name='User', null=True
            Cuisine = models.IntegerField(choices=cuisine_choice)
            Cuisine1 = models.CharField(max_length=30)
            LunchPref = models.IntegerField(choices=lunch_pref)
            DinnerPref = models.IntegerField(choices=dinner_pref)
            Sunday = models.IntegerField(choices=sunday)
            Friday = models.IntegerField(choices=friday)
</code>```

Seems fine to me so far.

here is ModelForm(forms.py)

```<code>class user_prefsForm(ModelForm):
    class Meta:
        model = user_prefs
        fields = ['Cuisine', 'Cuisine1', 'LunchPref', 'DinnerPref', 'Sunday', 'Friday']

form = user_prefsForm()
</code>```

here is views.py

```<code>def display1(request):
    if not request.user.is_authenticated:
        return redirect(settings.LOGIN_URL)
    #form = user_prefsForm(request.POST)
def display(request):
    if request.method == 'POST':
        form = user_prefsForm(request.POST)
        if form.is_valid():
            form.userID = request.user
            form.save()
        return HttpResponseRedirect('/')
    else:
        form = user_prefsForm()
        return render(request, 'display.html', {'form': form})
</code>```

template

```<code>Please state your preferences below
 <form action='/' method="POST" >
     {% csrf_token %}
     <p>What is you favourite cuisine?</p>
    {{ form.Cuisine }}
    <p>If not listed above or you want to add more to that, coud you please tell us? </p>
    {{ form.Cuisine1 }}
    <p>What would be your lunch preference ?</p>
    {{ form.LunchPref }}
    <p>What would be your Dinner preference ?</p>
    {{ form.DinnerPref }}
    <p>What would you do on your Friday free time ?</p>
    {{ form.Sunday }}
    <p>What would you do on Sunday?</p>
    {{ form.Friday }}
 <button type="submit">Submit</button>
    {% endif %}
 </html>
</code>```

Just in case urls.py(tho i dont think there would be any issues, however):

```<code>urlpatterns = [
    url(r'^$', index),
    url(r'^letusknow/', display, name='display'),
    url(r'^letusknow/', display1, name='display1'),
    ]
</code>```

Initially I had models.CharField in my models, that didnt work either.

答:
Your problem is that you are redirecting to the home page regardless of whether the form is valid or not.

```<code>def display(request):
    if request.method == 'POST':
        form = user_prefsForm(request.POST)
        if form.is_valid():
            form.userID = request.user
            form.save()
            # note indentation change here.
            return HttpResponseRedirect('/')
    else:
        form = user_prefsForm()
    # note identation change here.
    return render(request, 'display.html', {'form': form})
</code>```

Additionally in your template you are not rendering the fields correctly, some of the errors in the form will never be displayed. Please refer to this link: https://docs.djangoproject.com/en/1.11/topics/forms/#rendering-fields-manually

Unless you fix the template the user will never know that he filled the form incorrectly.

Body:
I feel very stupid and confused, tackling this issue for so long.
It works completely fine, displays survey fine, however it does not store(save) submited form to my database. I have seen tons of questions/solutions, however none of them helped me.

Here are my models.py

from __future__ import unicode_literals
from django.db import models
#from multiselectfield import MultiSelectField,
from django.contrib.auth.models import User
#from django.forms import ModelForm
# Create your models here.

    class user_prefs(models.Model):
            cuisine_choice = (
                ('1', 'Italian'),
                ('2', 'American'),
                ('3', 'Japanese'),
                ('4', 'French'),
                ('5', 'Mexican'),
                ('6', 'Chinese'),
                ('7', 'Indian'),
                ('8', 'Middle Eastern')
            )
            lunch_pref = (
                ('1', 'Coffeehouse'),
                ('2', 'Cafe'),
                ('3', 'Restaurant'),
                ('4', 'Fast Food'),
                ('5', 'Takeaway'),
                ('6', 'Stake House')
            )
            dinner_pref = (
                ('1', 'Restaurant'),
                ('2', 'Takeaway'),
                ('3', 'Delivery'),
                ('4', 'Fast food'),
                ('5', 'Coffeehouse'),
                ('6', 'Cafe'),
                ('7', 'Cooking at home')
            )
            sunday = (
                ('1', 'Cultural activities(Museums, Galleries, Exhibitions etc.)'),
                ('2', 'Sport activities'),
                ('3', 'Attending sport events'),
                ('4', 'Music events'),
                ('5', 'Hiking'),
                ('6', 'Going to park')
            )
            friday = (
                ('1', 'Bar'),
                ('2', 'Nightclub'),
                ('3', 'Karaoke'),
                ('4', 'Netflix & chill'),
                ('5', 'Videogames'),
                ('6', 'Cinema'),
                ('7', 'Theater'),
                ('8', 'Restaurant')
            )
            userID = models.ForeignKey(User) #related_name='User', null=True
            Cuisine = models.IntegerField(choices=cuisine_choice)
            Cuisine1 = models.CharField(max_length=30)
            LunchPref = models.IntegerField(choices=lunch_pref)
            DinnerPref = models.IntegerField(choices=dinner_pref)
            Sunday = models.IntegerField(choices=sunday)
            Friday = models.IntegerField(choices=friday)

Seems fine to me so far.

here is ModelForm(forms.py)

class user_prefsForm(ModelForm):
    class Meta:
        model = user_prefs
        fields = ['Cuisine', 'Cuisine1', 'LunchPref', 'DinnerPref', 'Sunday', 'Friday']

form = user_prefsForm()

here is views.py

def display1(request):
    if not request.user.is_authenticated:
        return redirect(settings.LOGIN_URL)
    #form = user_prefsForm(request.POST)
def display(request):
    if request.method == 'POST':
        form = user_prefsForm(request.POST)
        if form.is_valid():
            form.userID = request.user
            form.save()
        return HttpResponseRedirect('/')
    else:
        form = user_prefsForm()
        return render(request, 'display.html', {'form': form})

template

Please state your preferences below
 <form action='/' method="POST" >
     {% csrf_token %}

What is you favourite cuisine?

    {{ form.Cuisine }}

If not listed above or you want to add more to that, coud you please tell us?

    {{ form.Cuisine1 }}

What would be your lunch preference ?

    {{ form.LunchPref }}

What would be your Dinner preference ?

    {{ form.DinnerPref }}

What would you do on your Friday free time ?

    {{ form.Sunday }}

What would you do on Sunday?

    {{ form.Friday }}
 <button type="submit">Submit</button>
    {% endif %}

Just in case urls.py(tho i dont think there would be any issues, however):

urlpatterns = [
    url(r'^$', index),
    url(r'^letusknow/', display, name='display'),
    url(r'^letusknow/', display1, name='display1'),
    ]

Initially I had models.CharField in my models, that didnt work either.

Body:
Your problem is that you are redirecting to the home page regardless of whether the form is valid or not.

def display(request):
    if request.method == 'POST':
        form = user_prefsForm(request.POST)
        if form.is_valid():
            form.userID = request.user
            form.save()
            # note indentation change here.
            return HttpResponseRedirect('/')
    else:
        form = user_prefsForm()
    # note identation change here.
    return render(request, 'display.html', {'form': form})

Additionally in your template you are not rendering the fields correctly, some of the errors in the form will never be displayed. Please refer to this link: https://docs.djangoproject.com/en/1.11/topics/forms/#rendering-fields-manually

Unless you fix the template the user will never know that he filled the form incorrectly.


问:
Should the password field be unique?
In light of the recent Gawker Media password leak, I've realized that many users share the same passwords. To help encourage stronger passwords, would it be helpful if passwords are constrained to be unique among all users?

One immediate downside I could think of (besides account creation performance?) is being able to know that someone is using a given string as a password. This knowledge, combined with a list of users, could be quite dangerous.

Is there a way to mitigate that downside while retaining the alleged benefits of not allowing repeat passwords?

It's kind of like the XKCD kick bot where you aren't allowed to repeat short, unoriginal sentences like "yah" or "lol".

Edit^2: I thought you could unique-ify against a hash, but as someone pointed out, with varying salts, this would not have the intended effect. Good eye!

答:
Really don’t

As long as you have salts, the password won’t be stored the same way anyway.

If you want to ensure password security:

Pick a good hash (sha256, blowfish, etc.)

Use salts

Snap-in a password meter with a minimum threshold

A lot of those can be bundled with wordlists

Check out a post I made about it on reddit:
http://www.reddit.com/r/netsec/comments/ektb8/in_the_light_of_recent_gawker_breakout_lets_talk/

Title: Should the password field be unique?


问:
Ruby jsonapi-resources links (relative/absolute)
I am incredibly new to Ruby, so I apologise in advance if this question seems very simple or vague.

Where, when using jsonapi-resources is the base path for JSON API links specified? I wish to change from specifying full URLs to root-relative paths to these resources.

I've found the routes.rb which has

Rails.application.routes.draw do

# Route / to the front-end
root to: 'root#index'

namespace :api do

   jsonapi_resources :widgets

   // ...more jsonapi_resources calls
end
```

答:
I am guessing you are looking for something like this?</p>

```<code>Rails.application.routes.draw do
  namespace :api do
    namespace :v1 do
      jsonapi_resources :cars, only: [:index]
    end
  end
end
</code>```

Body:
I am guessing you are looking for something like this?

Rails.application.routes.draw do
  namespace :api do
    namespace :v1 do
      jsonapi_resources :cars, only: [:index]
    end
  end
end


问:
R - Find which value of a data frame to minimize a sum
In R, I have the data frame which follows :

```<code>Mean_1     Mean_2        Nb_element_1     Nb_element_2
42.66667   51.89474      3                38
65.00000   -85.87500     1                8
163.32653  -117.96970    49               33
22.83333   247.00000     6                1
</code>```

I would solve this optimization problem which follows :

(1) : argmin Sum(| |Mean_1| - |Mean_2| | + |nb_element_1-nb_element_2|)

(2) : 1.1*|Mean_1| > |Mean_2| > 0.75*|Mean_1|

I want to find which elements give the smallest sum value constrained by (2)

Is there a function which can do that ? Like solve() where we have to solve (1) = 0 or others functions ?

Thank You.

Edit : What I wanted is to have the best combination between an element from Mean_1 and Mean_2 that give the smallest sum value, example :

```<code>(Mean_1[1],Nb_element_1[1]) with (Mean_2[3],Nb_element_2[3])
(Mean_1[2],Nb_element_1[2]) with (Mean_2[1],Nb_element_2[1])
(Mean_1[3],Nb_element_1[3]) with (Mean_2[4],Nb_element_2[4])
(Mean_1[4],Nb_element_1[4]) with (Mean_2[2],Nb_element_2[2])
</code>```

Give the smallest sum value (not in this particular case, it's just an example to explain)

Actually, Mean_1 and Nb_element_1 are associated as Mean_2 and Nb_element_2.

So it faciliates the problem.

Thank you again.

答:
```<code>library(dyplr)

mydf <- read.table(text = "Mean_1     Mean_2        Nb_element_1     Nb_element_2
42.66667   51.89474      3                38
65.00000   -85.87500     1                8
163.32653  -117.96970    49               33
22.83333   247.00000     6                1", header=TRUE)
</code>```

I'll create 3 new column names "ConcolX" (for "Constraint Columns") - had to give them some name.

I think your original dataframe has no rational solution, so here I try a brute force approach with integers permuted between 0 and 200 for all 4 columns. You can refine the search space with more accurate estimates that you might have.

```<code>mydf3 <- expand.grid(seq(0,200,3), seq(0,200,4), seq(0,200,5), seq(0,200,4))
colnames(mydf3) <- c("Mean_1", "Mean_2", "Nb_element_1", "Nb_element_2")

mydf3 <- mydf3 %>%
        mutate(Concol1 = abs(Mean_1) - abs(Mean_2) + abs(Nb_element_1) + abs(Nb_element_2)) %>%
        mutate(Concol2 = 1.1 * abs(Mean_1) > abs(Mean_2)) %>%
        mutate(Concol3 = abs(Mean_2) > 0.75 * abs(Mean_1)) %>%
        filter(Concol2 == TRUE & Concol3 == TRUE) %>%
        filter(Concol1 == min(Concol1))
</code>```

Result:

```<code>mydf3
  Mean_1 Mean_2 Nb_element_1 Nb_element_2 Concol1 Concol2 Concol3
1    171    188            0            0     -17    TRUE    TRUE
2    183    200            0            0     -17    TRUE    TRUE
</code>```

Body:
In R, I have the data frame which follows :

Mean_1     Mean_2        Nb_element_1     Nb_element_2
42.66667   51.89474      3                38
65.00000   -85.87500     1                8
163.32653  -117.96970    49               33
22.83333   247.00000     6                1

I would solve this optimization problem which follows :

(1) : argmin Sum(| |Mean_1| - |Mean_2| | + |nb_element_1-nb_element_2|)

(2) : 1.1*|Mean_1| > |Mean_2| > 0.75*|Mean_1|

I want to find which elements give the smallest sum value constrained by (2)

Is there a function which can do that ? Like solve() where we have to solve (1) = 0 or others functions ?

Thank You.

Edit : What I wanted is to have the best combination between an element from Mean_1 and Mean_2 that give the smallest sum value, example :

(Mean_1[1],Nb_element_1[1]) with (Mean_2[3],Nb_element_2[3])
(Mean_1[2],Nb_element_1[2]) with (Mean_2[1],Nb_element_2[1])
(Mean_1[3],Nb_element_1[3]) with (Mean_2[4],Nb_element_2[4])
(Mean_1[4],Nb_element_1[4]) with (Mean_2[2],Nb_element_2[2])

Give the smallest sum value (not in this particular case, it's just an example to explain)

Actually, Mean_1 and Nb_element_1 are associated as Mean_2 and Nb_element_2.

So it faciliates the problem.

Thank you again.

Body:
library(dyplr)

mydf <- read.table(text = "Mean_1     Mean_2        Nb_element_1     Nb_element_2
42.66667   51.89474      3                38
65.00000   -85.87500     1                8
163.32653  -117.96970    49               33
22.83333   247.00000     6                1", header=TRUE)

I'll create 3 new column names "ConcolX" (for "Constraint Columns") - had to give them some name.

I think your original dataframe has no rational solution, so here I try a brute force approach with integers permuted between 0 and 200 for all 4 columns. You can refine the search space with more accurate estimates that you might have.

mydf3 <- expand.grid(seq(0,200,3), seq(0,200,4), seq(0,200,5), seq(0,200,4))
colnames(mydf3) <- c("Mean_1", "Mean_2", "Nb_element_1", "Nb_element_2")

mydf3 <- mydf3 %>%
        mutate(Concol1 = abs(Mean_1) - abs(Mean_2) + abs(Nb_element_1) + abs(Nb_element_2)) %>%
        mutate(Concol2 = 1.1 * abs(Mean_1) > abs(Mean_2)) %>%
        mutate(Concol3 = abs(Mean_2) > 0.75 * abs(Mean_1)) %>%
        filter(Concol2 == TRUE & Concol3 == TRUE) %>%
        filter(Concol1 == min(Concol1))

Result:

mydf3
  Mean_1 Mean_2 Nb_element_1 Nb_element_2 Concol1 Concol2 Concol3
1    171    188            0            0     -17    TRUE    TRUE
2    183    200            0            0     -17    TRUE    TRUE


问:
Good way to sanitize input in classic asp
I have to update old projects at work. I do not have any experience with classic asp, although i'm familiar with php scripting.

Are there any functions I should use?

Can you provide me with a good function for some basic protection?

Is there something like a parameterized query in asp?

Thanks!

答:
One way to do it might be to add a check in a header.asp file that iterates through the Request object looking for inappropriate characters.  For example:

```<code><%
    for each x in Request.Form ' Do this for Request.Querystring also
        If InStr(x,"<") <> 0 Then
            ' encode the value or redirect to error page?
        End If
    next
%>
</code>```

OwnerDisplayName: Sander Versluys

LastEditorDisplayName: Sander Versluys

Body:
One way to do it might be to add a check in a header.asp file that iterates through the Request object looking for inappropriate characters.  For example:

<%
    for each x in Request.Form ' Do this for Request.Querystring also
        If InStr(x,"<") <> 0 Then
            ' encode the value or redirect to error page?
        End If
    next
%>


问:
ERROR: 'object' does not contain a definition for 'methodName'
I need to pass different objects instantiated from different classes which they have a function with same name, and I would like to call that function.

For example:

```<code>Class1 object1;
Class2 object2;
Class3 object3;

Object object = object1;
object1->functionname();

Object object = object2;
object2->functionname();

Object object = object3;
object3->functionname();
</code>```

this is not possible in c#...

In php it's pretty simple you can just do it with object like the sample above but in c# i get this error:  ERROR: 'object' does not contain a definition for 'methodName'

I though it's legal to call any method name on a object object! since it doesn't know what is really inside.

How can I do that?

答:
I though it's legal to call any method name on a object object! since it doesn't know what is really inside.

No, it's illegal to call any method apart from the ones defined on Object itself. Perhaps you are thinking of dynamic?

But instead I think you should create a common interface.

```<code>interface IProcessable
{
    void Process();
}
</code>```

Body:
I need to pass different objects instantiated from different classes which they have a function with same name, and I would like to call that function.

For example:

Class1 object1;
Class2 object2;
Class3 object3;

Object object = object1;
object1->functionname();

Object object = object2;
object2->functionname();

Object object = object3;
object3->functionname();

this is not possible in c#...

In php it's pretty simple you can just do it with object like the sample above but in c# i get this error:  ERROR: 'object' does not contain a definition for 'methodName'

I though it's legal to call any method name on a object object! since it doesn't know what is really inside.

How can I do that?

Body:
I though it's legal to call any method name on a object object! since it doesn't know what is really inside.

No, it's illegal to call any method apart from the ones defined on Object itself. Perhaps you are thinking of dynamic?

But instead I think you should create a common interface.

interface IProcessable
{
    void Process();
}


问:
How to find delimiter from string in Console Application
```<code>Console.WriteLine("Enter a string");
string str = Console.ReadLine();
</code>```

Note: User can enter any delimiter like , @ # $ % * &  ; : etc.

Example: For input: 1*2*5*9 the delimiter is *

答:
```<code>  Using system.text.regularexpressions;
  Regex ptr = new Regex(@"^[a-zA-Z0-9]*$") ;
  if(!ptr.Ismatch(str)) //whatever you want
</code>```

Body:
Console.WriteLine("Enter a string");
string str = Console.ReadLine();

Note: User can enter any delimiter like , @ # $ % * &  ; : etc.

Example: For input: 1*2*5*9 the delimiter is *


问:
Retrofit: Android app fails SSL handshakes when launched on API21+ devices
I am building an App that fetches some JSON data via HTTPS, using Retrofit with a custom OkHttp client. It works fine on KitKat. Once I move to Android 5, 6 or 7, SSL handshakes fail.

The server supports TLSv1 and nothing else. It also uses an ancient, expired, self-signed certificate. Tested it with the Qualys' SSL tool, which told me that all versions of Android should be able to connect. Here's what I've got:

OkHttp client:

```<code>public class HTTPClient {

public static OkHttpClient getUnsafeOkHttpClient() {
    try {
        // Create a trust manager that does not validate certificate chains

        final TrustManager[] trustAllCerts = new TrustManager[] {
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return new java.security.cert.X509Certificate[]{};
                    }
                }
        };

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("TLSv1");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create a ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        //URL url = new URL(ApiIntentService.getHostAddress());
        //final SSLSocketFactory sslSocketFactory = new NoSSLv3SocketFactory(url);

//            ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS)
//                    .tlsVersions(TlsVersion.TLS_1_0)
//                    .cipherSuites(
//                            CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
//                            CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
//                            CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
//                            CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
//                            CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
//                            CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
//                            CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
//                            CipherSuite.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
//                            CipherSuite.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
//                            CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA)
//                    .build();

//            String hostname = "api.server.domain";
//            CertificatePinner certificatePinner = new CertificatePinner.Builder()
//                    .add(hostname, "sha256/3Iiwgs3a0qjPCnBQzW/GeHhPbZvhaJtxKvMJJVO5KdU=")
//                    .build();

        final OkHttpClient.Builder builder = new OkHttpClient.Builder();
//            builder.connectionSpecs(Collections.singletonList(spec));
//            builder.certificatePinner(certificatePinner);
            builder.sslSocketFactory(sslSocketFactory);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            builder.authenticator(new Authenticator() {
                @Override
                public Request authenticate(Route route, Response response) throws IOException {
                    String credential = Credentials.basic("user", "pass");
                    return response.request().newBuilder()
                            .header("Authorization", credential)
                            .build();
                }
            });
        OkHttpClient okHttpClient = builder.build();
        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
</code>```

I am aware how terribly butchered in terms of security this code is. My supervisor demanded it to be that way, and I informed him how bad this is.

I have tried 2 things to solve my problem, they're commented out in that piece of code - certificate pinning and requesting TLSv1 specifically, with a list of ciphers. Found those two in other questions, but they changed nothing (stack trace is exactly the same).

Stack trace

Here are the interesting bits of the stack trace:

```<code>I/RETROFIT: Data retrieval failed! javax.net.ssl.SSLHandshakeException: Handshake failed
*snip*
Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0xb43eb200: Failure in SSL library, usually a protocol error
error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:770 0xac6fedd4:0x00000000)
                at       com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
</code>```

It looks as if Android tries to use SSLv3 all of a sudden, but Wireshark shows communication via TLSv1. It starts with Client Hello, as it should, but the server immediately answers with Handshake Failure (40).

All help is greatly appreaciated, since I'm all out of ideas. Please ask for clarification if it's needed.

Thank you.

答:
The solution for me was adding more ciphers as acceptable for OkHttpClient. Since API 21, some TLS certificates are deprecated for Android. This might help:

```<code>ConnectionSpec spec = new
ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
            .tlsVersions(TlsVersion.TLS_1_2)
            .cipherSuites(
CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256)
            .build();

OkHttpClient client = new OkHttpClient.Builder()
        .connectionSpecs(Collections.singletonList(spec))
        .build();
</code>```

For more info please visit: https://github.com/square/okhttp/wiki/HTTPS

Body:
I am building an App that fetches some JSON data via HTTPS, using Retrofit with a custom OkHttp client. It works fine on KitKat. Once I move to Android 5, 6 or 7, SSL handshakes fail.

The server supports TLSv1 and nothing else. It also uses an ancient, expired, self-signed certificate. Tested it with the Qualys' SSL tool, which told me that all versions of Android should be able to connect. Here's what I've got:

OkHttp client:

public class HTTPClient {

public static OkHttpClient getUnsafeOkHttpClient() {
    try {
        // Create a trust manager that does not validate certificate chains

        final TrustManager[] trustAllCerts = new TrustManager[] {
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return new java.security.cert.X509Certificate[]{};
                    }
                }
        };

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("TLSv1");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create a ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        //URL url = new URL(ApiIntentService.getHostAddress());
        //final SSLSocketFactory sslSocketFactory = new NoSSLv3SocketFactory(url);

//            ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS)
//                    .tlsVersions(TlsVersion.TLS_1_0)
//                    .cipherSuites(
//                            CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
//                            CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
//                            CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
//                            CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
//                            CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
//                            CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
//                            CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
//                            CipherSuite.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
//                            CipherSuite.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
//                            CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA)
//                    .build();

//            String hostname = "api.server.domain";
//            CertificatePinner certificatePinner = new CertificatePinner.Builder()
//                    .add(hostname, "sha256/3Iiwgs3a0qjPCnBQzW/GeHhPbZvhaJtxKvMJJVO5KdU=")
//                    .build();

        final OkHttpClient.Builder builder = new OkHttpClient.Builder();
//            builder.connectionSpecs(Collections.singletonList(spec));
//            builder.certificatePinner(certificatePinner);
            builder.sslSocketFactory(sslSocketFactory);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            builder.authenticator(new Authenticator() {
                @Override
                public Request authenticate(Route route, Response response) throws IOException {
                    String credential = Credentials.basic("user", "pass");
                    return response.request().newBuilder()
                            .header("Authorization", credential)
                            .build();
                }
            });
        OkHttpClient okHttpClient = builder.build();
        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

I am aware how terribly butchered in terms of security this code is. My supervisor demanded it to be that way, and I informed him how bad this is.

I have tried 2 things to solve my problem, they're commented out in that piece of code - certificate pinning and requesting TLSv1 specifically, with a list of ciphers. Found those two in other questions, but they changed nothing (stack trace is exactly the same).

Stack trace

Here are the interesting bits of the stack trace:

I/RETROFIT: Data retrieval failed! javax.net.ssl.SSLHandshakeException: Handshake failed
*snip*
Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0xb43eb200: Failure in SSL library, usually a protocol error
error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:770 0xac6fedd4:0x00000000)
                at       com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)

It looks as if Android tries to use SSLv3 all of a sudden, but Wireshark shows communication via TLSv1. It starts with Client Hello, as it should, but the server immediately answers with Handshake Failure (40).

All help is greatly appreaciated, since I'm all out of ideas. Please ask for clarification if it's needed.

Thank you.

Body:
The solution for me was adding more ciphers as acceptable for OkHttpClient. Since API 21, some TLS certificates are deprecated for Android. This might help:

ConnectionSpec spec = new
ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
            .tlsVersions(TlsVersion.TLS_1_2)
            .cipherSuites(
CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256)
            .build();

OkHttpClient client = new OkHttpClient.Builder()
        .connectionSpecs(Collections.singletonList(spec))
        .build();

For more info please visit: https://github.com/square/okhttp/wiki/HTTPS


问:
Why did my Git repo enter a detached HEAD state?
I ended up with a detached head today, the same problem as described in: git push says everything up-to-date even though I have local changes

As far as I know I didn't do anything out of the ordinary, just commits and pushes from my local repo.

So how did I end up with a detached HEAD?

答:
A simple accidental way is to do a git checkout head as a typo of HEAD.

Try this:

```<code>git init
touch Readme.md
git add Readme.md
git commit
git checkout head
</code>```

which gives

```<code>Note: checking out 'head'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch-name>

HEAD is now at 9354043... Readme
</code>```

Body:
A simple accidental way is to do a git checkout head as a typo of HEAD.

Try this:

git init
touch Readme.md
git add Readme.md
git commit
git checkout head

which gives

Note: checking out 'head'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch-name>

HEAD is now at 9354043... Readme


问:
How to rereduce with Mongoid to aggrerate data from two distinct fields?

The context

Two documents of a mongodb mapped on rails/mongoid classes. The two class are Task and Subscription. For performance reasons, Subscription.current_task stores a Task::CurrentTask which is contains a subset of attributes of a Task, but the real current task matching a subscription is the one with the highest Task#pos for a given Task#subscription_id.

The problem

Some inconsistencies appeared between some attributes from the Subscription.current_task and the should be matching Task, notably the state field.

Goal

Listing all current tasks from Subscriptions which doesn't match the last Task for this subscription.

Solution aimed

First, map/reduce Task to get the last one for each subscription and storing that into a temporary collection. Thirdly rereduce with this temporary collection on Subscription to obtains for each subscription an object containing both the actual last task and the current embeded subset copy. Thirdly, create the report for elements where actual and copied task mismatch.

Difficulty encountered

While having read the official mongodb and mangoid documentation, and other example in misc. blog like MongoDB Map Re-Reduce and joins – performance tuning and MongoDB, Mongoid, MapReduce and Embedded Documents., I'm still unable to come with a working solution for the rereduce step.

The nonfunctional solution wrote so far:

```<code># map/reduce of tasks to get the last one of each subscripton
last_task_map = %Q{
  function() {
    var key = this.subscription_id;
    var value = {
        task: {
          pos: this.pos,
          task_id: this._id,
          state: this.state
        },
        current_task: null
    };
    emit(key, value);
  }
}
last_task_reduce = %Q{
  function(key, tasks) {
    var last_task = tasks[0];
    for ( var i=1; i < tasks.length; i++ ) {
      if(tasks[i].pos > last_task.pos) {
        last_task = tasks[i];
      }
    }

    var value = {
      task: {pos: last_task.pos, task_id: last_task.task_id, state: last_task.state},
      current_task: null
    };
    return value;
  }
}

# map/reduce of `current_task`s to merged with previous results
subscription_map = %Q{
  function() {
    if(!this.current_task) {
      return;
    }
    var key = this._id;
    var value = {
      task: null,
      current_task: {
        pos: this.current_task.pos,
        task_id: this.current_task.task_id,
        state: this.current_task.state,
        source: 'current_task',
      }
    };
    emit(key, value);
  };
}

reduce = %Q{
  function(key, tasks) {
    if(tasks[0].current_task == nill) {
      return {task: tasks[0].task, current_task: tasks[1].current_task};
    }
    return {task: tasks[1].task, current_task: tasks[0].current_task};
  }
}

buffer = 'current_task_consistency'
# temporary collection seems unremoved when serially calling the script with
# `load` in a `rails c` prompt, so we drop it to avoid unwanted glitch merge
Mongoid.default_client[buffer].drop
t = Task.map_reduce(last_task_map, last_task_reduce).out(replace: buffer)
s = Subscription.map_reduce(subscription_map, reduce).out(reduce: buffer)
t.each{ |e| puts e } # ok: `{"_id"=>BSON::ObjectId('592dd603e138236671587b04'), "value"=>{"task"=>{"pos"=>0.0, "task_id"=>BSON::ObjectId('592dd604e138236671587b0f'), "state"=>40.0}, "current_task"=>nil}}`
puts t.counts # ok: {"input"=>83900, "emit"=>83900, "reduce"=>36115, "output"=>28625}
s.each{ |e| puts e } # ko: {"_id"=>BSON::ObjectId('592dd603e138236671587b04'), "value"=>{"task"=>nil, "current_task"=>{"pos"=>0.0, "task_id"=>BSON::ObjectId('592dd604e138236671587b0f'), "state"=>40.0, "source"=>"current_task"}}}
puts s.counts # ko: {"input"=>28632, "emit"=>28624, "reduce"=>0, "output"=>28624}
</code>```

The expected result for the second map/reduce is a merge of the current_task_consistency and the subscription_map results which should all pass within the reduce, when none is performed according to counts, and indeed the output from s elements reveals that no task key was assigned with the current_task_consistency value.

Questions related to the exposed problem

What does the implementation lakes?

As far as I understand, this solution do provide merge functions which are idempotent and which provides output consistent with the corresponding match function returns. What do I may misunderstand about how the out parameter works and how the rereduce input/output should be managed?

Additional remarks

The third step, to generate the report, is intended to be implemented as a finalize function applied on the second map/reduce. But maybe a third map/reduce might be a better way, or not. As a whole the implementation might be badly poorly structured at least from a performance point of view, and feed back is welcome on that point too.

答:
A first problem of the proposed solution was simply a ruby/js syntax mix up, nill instead of null. Unfortunately the script was failing silently, at least in the pry console where I was running load current_task_consistency.rb.

Here is a working solution, with two map/reduce and a query on the resulting temporary collection.

```<code># map/reduce of tasks to get the last one of each subscripton
last_task_map = %Q{
  function() {
    var key = this.subscription_id;
    var value = {
        task: {
          pos: this.pos,
          task_id: this._id,
          state: this.state
        },
        current_task: null
    };
    emit(key, value);
  }
}
last_task_reduce = %Q{
  function(key, tasks) {
    var last_task = tasks[0];
    for ( var i=1; i < tasks.length; i++ ) {
      if(tasks[i].pos > last_task.pos) {
        last_task = tasks[i];
      }
    }

    var value = {
      task: {pos: last_task.pos, task_id: last_task.task_id, state: last_task.state},
      current_task: null
    };
    return value;
  }
}

# map/reduce of `current_task`s merged side by side with the corresponding
# subscription last task
subscription_map = %Q{
  function() {
    if(!this.current_task) {
      return;
    }
    var key = this._id;
    var value = {
      task: null,
      current_task: {
        pos: this.current_task.pos,
        task_id: this.current_task.task_id,
        state: this.current_task.state,
      }
    };
    emit(key, value);
  };
}

subscription_reduce = %Q{
  function(key, tasks) {
    if(tasks[0].current_task == null) {
      return {task: tasks[0].task, current_task: tasks[1].current_task};
    }
    return {task: tasks[1].task, current_task: tasks[0].current_task};
  }
}

buffer = 'current_task_consistency'
# temporary collection seems unremoved when serially calling the script with
# `load` in a `rails c` prompt, so we drop it to avoid unwanted merge glitch
Mongoid.default_client[buffer].drop

Task.map_reduce(last_task_map, last_task_reduce).
  out(replace: buffer).
  execute

Subscription.
  map_reduce(subscription_map, subscription_reduce).
  out(reduce: buffer).
  execute

ascertain_inconsistency = %Q{
  this.value.current_task == null ||
    this.value.current_task.state != this.value.task.state
}

inconsistencies = Mongoid.default_client['current_task_consistency'].
  find( { "$where": ascertain_inconsistency } )
</code>```

Body:
The context

Two documents of a mongodb mapped on rails/mongoid classes. The two class are Task and Subscription. For performance reasons, Subscription.current_task stores a Task::CurrentTask which is contains a subset of attributes of a Task, but the real current task matching a subscription is the one with the highest Task#pos for a given Task#subscription_id.

The problem

Some inconsistencies appeared between some attributes from the Subscription.current_task and the should be matching Task, notably the state field.

Goal

Listing all current tasks from Subscriptions which doesn't match the last Task for this subscription.

Solution aimed

First, map/reduce Task to get the last one for each subscription and storing that into a temporary collection. Thirdly rereduce with this temporary collection on Subscription to obtains for each subscription an object containing both the actual last task and the current embeded subset copy. Thirdly, create the report for elements where actual and copied task mismatch.

Difficulty encountered

While having read the official mongodb and mangoid documentation, and other example in misc. blog like MongoDB Map Re-Reduce and joins – performance tuning and MongoDB, Mongoid, MapReduce and Embedded Documents., I'm still unable to come with a working solution for the rereduce step.

The nonfunctional solution wrote so far:

# map/reduce of tasks to get the last one of each subscripton
last_task_map = %Q{
  function() {
    var key = this.subscription_id;
    var value = {
        task: {
          pos: this.pos,
          task_id: this._id,
          state: this.state
        },
        current_task: null
    };
    emit(key, value);
  }
}
last_task_reduce = %Q{
  function(key, tasks) {
    var last_task = tasks[0];
    for ( var i=1; i < tasks.length; i++ ) {
      if(tasks[i].pos > last_task.pos) {
        last_task = tasks[i];
      }
    }

    var value = {
      task: {pos: last_task.pos, task_id: last_task.task_id, state: last_task.state},
      current_task: null
    };
    return value;
  }
}

# map/reduce of `current_task`s to merged with previous results
subscription_map = %Q{
  function() {
    if(!this.current_task) {
      return;
    }
    var key = this._id;
    var value = {
      task: null,
      current_task: {
        pos: this.current_task.pos,
        task_id: this.current_task.task_id,
        state: this.current_task.state,
        source: 'current_task',
      }
    };
    emit(key, value);
  };
}

reduce = %Q{
  function(key, tasks) {
    if(tasks[0].current_task == nill) {
      return {task: tasks[0].task, current_task: tasks[1].current_task};
    }
    return {task: tasks[1].task, current_task: tasks[0].current_task};
  }
}

buffer = 'current_task_consistency'
# temporary collection seems unremoved when serially calling the script with
# `load` in a `rails c` prompt, so we drop it to avoid unwanted glitch merge
Mongoid.default_client[buffer].drop
t = Task.map_reduce(last_task_map, last_task_reduce).out(replace: buffer)
s = Subscription.map_reduce(subscription_map, reduce).out(reduce: buffer)
t.each{ |e| puts e } # ok: `{"_id"=>BSON::ObjectId('592dd603e138236671587b04'), "value"=>{"task"=>{"pos"=>0.0, "task_id"=>BSON::ObjectId('592dd604e138236671587b0f'), "state"=>40.0}, "current_task"=>nil}}`
puts t.counts # ok: {"input"=>83900, "emit"=>83900, "reduce"=>36115, "output"=>28625}
s.each{ |e| puts e } # ko: {"_id"=>BSON::ObjectId('592dd603e138236671587b04'), "value"=>{"task"=>nil, "current_task"=>{"pos"=>0.0, "task_id"=>BSON::ObjectId('592dd604e138236671587b0f'), "state"=>40.0, "source"=>"current_task"}}}
puts s.counts # ko: {"input"=>28632, "emit"=>28624, "reduce"=>0, "output"=>28624}

The expected result for the second map/reduce is a merge of the current_task_consistency and the subscription_map results which should all pass within the reduce, when none is performed according to counts, and indeed the output from s elements reveals that no task key was assigned with the current_task_consistency value.

Questions related to the exposed problem

What does the implementation lakes?

As far as I understand, this solution do provide merge functions which are idempotent and which provides output consistent with the corresponding match function returns. What do I may misunderstand about how the out parameter works and how the rereduce input/output should be managed?

Additional remarks

The third step, to generate the report, is intended to be implemented as a finalize function applied on the second map/reduce. But maybe a third map/reduce might be a better way, or not. As a whole the implementation might be badly poorly structured at least from a performance point of view, and feed back is welcome on that point too.

Body:
A first problem of the proposed solution was simply a ruby/js syntax mix up, nill instead of null. Unfortunately the script was failing silently, at least in the pry console where I was running load current_task_consistency.rb.

Here is a working solution, with two map/reduce and a query on the resulting temporary collection.

# map/reduce of tasks to get the last one of each subscripton
last_task_map = %Q{
  function() {
    var key = this.subscription_id;
    var value = {
        task: {
          pos: this.pos,
          task_id: this._id,
          state: this.state
        },
        current_task: null
    };
    emit(key, value);
  }
}
last_task_reduce = %Q{
  function(key, tasks) {
    var last_task = tasks[0];
    for ( var i=1; i < tasks.length; i++ ) {
      if(tasks[i].pos > last_task.pos) {
        last_task = tasks[i];
      }
    }

    var value = {
      task: {pos: last_task.pos, task_id: last_task.task_id, state: last_task.state},
      current_task: null
    };
    return value;
  }
}

# map/reduce of `current_task`s merged side by side with the corresponding
# subscription last task
subscription_map = %Q{
  function() {
    if(!this.current_task) {
      return;
    }
    var key = this._id;
    var value = {
      task: null,
      current_task: {
        pos: this.current_task.pos,
        task_id: this.current_task.task_id,
        state: this.current_task.state,
      }
    };
    emit(key, value);
  };
}

subscription_reduce = %Q{
  function(key, tasks) {
    if(tasks[0].current_task == null) {
      return {task: tasks[0].task, current_task: tasks[1].current_task};
    }
    return {task: tasks[1].task, current_task: tasks[0].current_task};
  }
}

buffer = 'current_task_consistency'
# temporary collection seems unremoved when serially calling the script with
# `load` in a `rails c` prompt, so we drop it to avoid unwanted merge glitch
Mongoid.default_client[buffer].drop

Task.map_reduce(last_task_map, last_task_reduce).
  out(replace: buffer).
  execute

Subscription.
  map_reduce(subscription_map, subscription_reduce).
  out(reduce: buffer).
  execute

ascertain_inconsistency = %Q{
  this.value.current_task == null ||
    this.value.current_task.state != this.value.task.state
}

inconsistencies = Mongoid.default_client['current_task_consistency'].
  find( { "$where": ascertain_inconsistency } )


问:
How does this C code work but the other says L-value required?
This code works fine when b is incremented and a is printed upon increment

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

int main()
{
int a[] = {10,20,30,40,50}, *p, j;
int *b = a;
for(j=0;j<5;j++)
{
printf("%d\n",*b);
b++;
}
return 0;
}
</code>```

What happens here? What effect does a++ have here to suggest lvalue is required. Does a++ move to a point after all the elements of the array a?

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

int main()
{
int a[] = {10,20,30,40,50}, *p, j;
for(j=0;j<5;j++)
{
printf("%d\n",*a);
a++;
}
return 0;
}
</code>```

答:
a is an array which decays into a (unmodifiable) pointer to the array (and only and always to the array) when used in pointer context. So it cannot be modified, so a++ doesn't work.

b is a pointer which can point everywhere and thus as well can be modified, so b++ works.

Body:
This code works fine when b is incremented and a is printed upon increment

#include<stdio.h>

int main()
{
int a[] = {10,20,30,40,50}, *p, j;
int *b = a;
for(j=0;j<5;j++)
{
printf("%d\n",*b);
b++;
}
return 0;
}

What happens here? What effect does a++ have here to suggest lvalue is required. Does a++ move to a point after all the elements of the array a?

#include<stdio.h>

int main()
{
int a[] = {10,20,30,40,50}, *p, j;
for(j=0;j<5;j++)
{
printf("%d\n",*a);
a++;
}
return 0;
}


问:
Defensive copy of a mutable collection in Kotlin data class
I want to have a data class accepting a read-only list:

```<code>data class Notebook(val notes: List<String>) {
}
</code>```

But it can accept MutableList as well, because it is a subtype of the List.

For example the following code modifies the passed in list:

```<code>fun main(args: Array<String>) {
    val notes = arrayListOf("One", "Two")
    val notebook = Notebook(notes)

    notes.add("Three")

    println(notebook)       // prints: Notebook(notes=[One, Two, Three])
}
</code>```

Is there a way how perform defensive copy of the passed in list in the data class?

答:
I think better is to use JetBrains library for immutable collections - https://github.com/Kotlin/kotlinx.collections.immutable

Import in your project

Add the bintray repository:

```<code>repositories {
    maven {
        url "http://dl.bintray.com/kotlin/kotlinx"
    }
}
</code>```

Add the dependency:

```<code>compile 'org.jetbrains.kotlinx:kotlinx-collections-immutable:0.1'
</code>```

Result:

```<code>data class Notebook(val notes: ImmutableList<String>) {}

fun main(args: Array<String>) {
    val notes = immutableListOf("One", "Two")
    val notebook = Notebook(notes)

    notes.add("Three") // creates a new collection

    println(notebook)       // prints: Notebook(notes=[One, Two])
}
</code>```

Note:
You also can use add and remove methods with ImmutableList, but this methods doesn't modify current list just creates new one with your changes and return it for you.

Body:
I want to have a data class accepting a read-only list:

data class Notebook(val notes: List<String>) {
}

But it can accept MutableList as well, because it is a subtype of the List.

For example the following code modifies the passed in list:

fun main(args: Array<String>) {
    val notes = arrayListOf("One", "Two")
    val notebook = Notebook(notes)

    notes.add("Three")

    println(notebook)       // prints: Notebook(notes=[One, Two, Three])
}

Is there a way how perform defensive copy of the passed in list in the data class?

Body:
I think better is to use JetBrains library for immutable collections - https://github.com/Kotlin/kotlinx.collections.immutable

Import in your project

Add the bintray repository:

repositories {
    maven {
        url "http://dl.bintray.com/kotlin/kotlinx"
    }
}

Add the dependency:

compile 'org.jetbrains.kotlinx:kotlinx-collections-immutable:0.1'

Result:

data class Notebook(val notes: ImmutableList<String>) {}

fun main(args: Array<String>) {
    val notes = immutableListOf("One", "Two")
    val notebook = Notebook(notes)

    notes.add("Three") // creates a new collection

    println(notebook)       // prints: Notebook(notes=[One, Two])
}

Note:
You also can use add and remove methods with ImmutableList, but this methods doesn't modify current list just creates new one with your changes and return it for you.


问:
How do I change image on hover of  that the img is in - in jQuery?
You can see the implementation here http://jsfiddle.net/xNSFA/

Right now, when you hover over the cell, it changes some of the characteristics. But the image doesn't change. The image only changes when you hover over the image specifically.

How do I get the image to change with everything else?

By the way, it doesn't HAVE to be done in jQuery. If there is a nice elegant way to do this in CSS, I would love that. But I just assumed it was impossible to do - because of the image manipulation and I didn't want to set the background of the  to be that image. I want the image inside the cell.

Thanks.

答:
New answer: I didn't notice that you didn't want to use a background image. It can be done without, but you would just need to load both images.

Example: http://jsfiddle.net/patrick_dw/xNSFA/7/

html

```<code><td>
    <span class="sit-in-the-corner">1</span>
    <img class="on" src="http://fiwishop.com/feedback/images/2-up-icon-blk.png" />
    <img class="off" src="http://fiwishop.com/feedback/images/2-up-icon-grey.png" />
</td>
</code>```

css

```<code>table td img.off{
    display:none;
}
table td:hover img.off{
    display:inline;
}
table td:hover img.on{
    display:none;
}
</code>```

Original answer:

I'd use CSS instead of javascript, but you'll need to change the  element to an  element, and use the background- properties.

Example: http://jsfiddle.net/patrick_dw/xNSFA/5/

html

```<code><td>
    <span class="sit-in-the-corner">1</span>
    <a class='image'></a>
</td>
</code>```

css

```<code>table td a.image {
    width: 100%;
    height: 100%;
    background-image:url(http://fiwishop.com/feedback/images/2-up-icon-blk.png);
    background-repeat:no-repeat;
    background-position: center center;
    display:block;
}
table td a.image:hover {
    background-image:url(http://fiwishop.com/feedback/images/2-up-icon-grey.png);
}
</code>```

Title: How do I change image on hover of <td> that the img is in - in jQuery?

Body:
New answer: I didn't notice that you didn't want to use a background image. It can be done without, but you would just need to load both images.

Example: http://jsfiddle.net/patrick_dw/xNSFA/7/

html

<td>
    <span class="sit-in-the-corner">1</span>
    <img class="on" src="http://fiwishop.com/feedback/images/2-up-icon-blk.png" />
    <img class="off" src="http://fiwishop.com/feedback/images/2-up-icon-grey.png" />
</td>

css

table td img.off{
    display:none;
}
table td:hover img.off{
    display:inline;
}
table td:hover img.on{
    display:none;
}

Original answer:

I'd use CSS instead of javascript, but you'll need to change the <img> element to an <a> element, and use the background- properties.

Example: http://jsfiddle.net/patrick_dw/xNSFA/5/

html

<td>
    <span class="sit-in-the-corner">1</span>
    <a class='image'></a>
</td>

css

table td a.image {
    width: 100%;
    height: 100%;
    background-image:url(http://fiwishop.com/feedback/images/2-up-icon-blk.png);
    background-repeat:no-repeat;
    background-position: center center;
    display:block;
}
table td a.image:hover {
    background-image:url(http://fiwishop.com/feedback/images/2-up-icon-grey.png);
}


问:
Can multiple consumers consume at the same time?
I am new to Kafka . I wanted to know if multiple consumers can consume data from the topic at the same time and process them simultaneously or they are consumed and processed in batches ? </p>

答:
Kafka Consumers group themselves under a consumer group name, and each record published to a topic is delivered to one consumer instance within each subscribing consumer group. Consumer instances can be in separate processes or on separate machines.

If all the consumer instances have the same consumer group, then the records will effectively be load balanced over the consumer instances.

If all the consumer instances have different consumer groups, then each record will be broadcast to all the consumer processes.

The processing of the data can be done simultaneously or in batches based on your requirement.