答:
First of all, you don't pass "by value" by passing a full slice of a sequence, Python always passes by assignment, i.e. the first thing that implicitly happens is foo = argument when calling your function.

Now for your actual question:

Creating a full slice of a list creates a new list. You are passing a shallow copy of your original list to the function.

Creating a (full) slice of a numpy array produces a view onto the same data (somewhere in memory) the original array holds. The view and the original share the same data in the sense that if you change the content of one the change is visible across all views.

Further reading: http://scipy-cookbook.readthedocs.io/items/ViewsVsCopies.html

Title: Python - Why ndarray passed by value changes outside function?


来源: stackexchange

问:
Displaying 3 columns of data using bootstrap? Data shows as a row instead
Why are the class="col" classes not causing the data to show as a row containing 3 columns?

https://jsfiddle.net/bobbyrne01/b63g4kpe/1/

Html:

```<code>https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js
https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css
<div id="results"></div>
</code>```

Js:

```<code>document.getElementById('results').innerHTML += '<div class="container">';
document.getElementById('results').innerHTML += '<div class="row">';
for (var i = 0; i < 3; i++) {
  document.getElementById('results').innerHTML += '<div class="col">';
  document.getElementById('results').innerHTML += i + ' Col';
}
document.getElementById('results').innerHTML += '</div>';
document.getElementById('results').innerHTML += '</div><br/>';
document.getElementById('results').innerHTML += 'After container';
</code>```

答:
Because the syntax is (for example) col-md-4 also you are closing your row div too early. UPDATE: In fact it's somewhat worse than that, your output renders as:

0 Col

1 Col

2 Col

  After container

```

ContentLicense: CC BY-SA 3.0

Body:
Why are the class="col" classes not causing the data to show as a row containing 3 columns?

https://jsfiddle.net/bobbyrne01/b63g4kpe/1/

Html:

https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js
https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css

Js:

document.getElementById('results').innerHTML += '
';
document.getElementById('results').innerHTML += '
';
for (var i = 0; i < 3; i++) {
  document.getElementById('results').innerHTML += '
';
  document.getElementById('results').innerHTML += i + ' Col';
}
document.getElementById('results').innerHTML += '
';
document.getElementById('results').innerHTML += '

';
document.getElementById('results').innerHTML += 'After container';

Body:
Because the syntax is (for example) col-md-4 also you are closing your row div too early. UPDATE: In fact it's somewhat worse than that, your output renders as:

<div id="results">
  <div class="container">
  </div>
  <div class="row"></div>
  <div class="col"></div>0 Col
  <div class="col"></div>1 Col
  <div class="col"></div>2 Col<br>
  After container
  </div>


问:
php delete sql query not working
```<code><?php
    include('session.php');
?>

<?php
    $conn = new mysqli("127.0.0.1","root","","foo");
    if ($conn->connect_errno) {
        echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " .         $conn->connect_error;
    }
    $sew = $_SESSION['login_user'];
    $a = $_GET["en"];
    $l = 1;
    $d = -1;

    if($a == 1)
    {
        $sqlw = " INSERT into dlkeuser VALUES('$a','$sew')" ;

        if ($conn->query($sqlw) === FALSE)
        {
            echo "you have already disliked the song";
        }
        else
        {
        //query1
            $sql = " DELETE FROM lkeuser WHERE userid = '$sew' AND songid = '$a' ";

        //query2
            $sql = "UPDATE liking
            SET count = count - 1 ";

            if ($conn->query($sql) === TRUE) {
                echo "you disliked the song";
            }
            else {
                echo "Error: " . $sql . "<br>" . $conn->error;
            }
        }
</code>```

In this php code snippet, query1 is not working whereas query 2 is fine.

I am trying to insert (songid, userid) in dlkeuser(dislike) table against user i/p($_GET["en"]) and delete the record(songid,userid) from lkeuser(like) table if it exists. (songid,userid) pair is the composite primary key here. count is the net like/dislike of a song.

答:
let's try this,

it will work

```<code><?php
    include('session.php');
?>

<?php
    $conn = new mysqli("127.0.0.1","root","","foo");
    if ($conn->connect_errno) {
       echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " .           $conn->connect_error;
    }
    $sew = $_SESSION['login_user'];
    $a = $_GET["en"];
    $l = 1;
    $d = -1;

    if($a == 1)
    {
    $sqlw = " INSERT into dlkeuser VALUES('$a','$sew')";

        if ($conn->query($sqlw) === FALSE)
        {
            echo "you have already disliked the song";
        }
        else
        {
        //query1
            $sql  = " DELETE FROM lkeuser WHERE userid = '$sew' AND songid = '$a' " ;

        //query2
            $sql1 = "UPDATE liking
            SET count = count - 1 ";

            if ($conn->query($sql) === TRUE) {
                echo "deleted the song";
            }

            if ($conn->query($sql1) === TRUE) {
                echo "you disliked the song";
            }
            else {
                echo "Error: " . $sql . "<br>" . $conn->error;
            }
        }
</code>```

ContentLicense: CC BY-SA 4.0

Title: php delete sql query not working

Body:
<?php
    include('session.php');
?>

<?php
    $conn = new mysqli("127.0.0.1","root","","foo");
    if ($conn->connect_errno) {
        echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " .         $conn->connect_error;
    }
    $sew = $_SESSION['login_user'];
    $a = $_GET["en"];
    $l = 1;
    $d = -1;

    if($a == 1)
    {
        $sqlw = " INSERT into dlkeuser VALUES('$a','$sew')" ;

        if ($conn->query($sqlw) === FALSE)
        {
            echo "you have already disliked the song";
        }
        else
        {
        //query1
            $sql = " DELETE FROM lkeuser WHERE userid = '$sew' AND songid = '$a' ";

        //query2
            $sql = "UPDATE liking
            SET count = count - 1 ";

            if ($conn->query($sql) === TRUE) {
                echo "you disliked the song";
            }
            else {
                echo "Error: " . $sql . "
" . $conn->error;
            }
        }

In this php code snippet, query1 is not working whereas query 2 is fine.

I am trying to insert (songid, userid) in dlkeuser(dislike) table against user i/p($_GET["en"]) and delete the record(songid,userid) from lkeuser(like) table if it exists. (songid,userid) pair is the composite primary key here. count is the net like/dislike of a song.

Body:
let's try this,

it will work

<?php
    include('session.php');
?>

<?php
    $conn = new mysqli("127.0.0.1","root","","foo");
    if ($conn->connect_errno) {
       echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " .           $conn->connect_error;
    }
    $sew = $_SESSION['login_user'];
    $a = $_GET["en"];
    $l = 1;
    $d = -1;

    if($a == 1)
    {
    $sqlw = " INSERT into dlkeuser VALUES('$a','$sew')";

        if ($conn->query($sqlw) === FALSE)
        {
            echo "you have already disliked the song";
        }
        else
        {
        //query1
            $sql  = " DELETE FROM lkeuser WHERE userid = '$sew' AND songid = '$a' " ;

        //query2
            $sql1 = "UPDATE liking
            SET count = count - 1 ";

            if ($conn->query($sql) === TRUE) {
                echo "deleted the song";
            }

            if ($conn->query($sql1) === TRUE) {
                echo "you disliked the song";
            }
            else {
                echo "Error: " . $sql . "<br>" . $conn->error;
            }
        }


问:
How to ignore user's time zone and force Date() use specific time zone
In an JS app, I receive timestamp (eq. 1270544790922) from server (Ajax).

Basing on that timestamp I create Date object using:

```<code>var _date = new Date();
_date.setTime(1270544790922);
</code>```

Now, _date decoded timestamp in current user locale time zone. I don't want that.

I would like _date to convert this timestamp to current time in city of Helsinki in Europe (disregarding current time zone of the user).

How can I do that?

答:
Presuming you get the timestamp in Helsinki time, I would create a date object set to midnight January 1 1970 UTC (for disregarding the local timezone settings of the browser).
Then just add the needed number of milliseconds to it.

var _date = new Date( Date.UTC(1970, 0, 1, 0, 0, 0, 0) );
_date.setUTCMilliseconds(1270544790922);

alert(_date); //date shown shifted corresponding to local time settings
alert(_date.getUTCFullYear());    //the UTC year value
alert(_date.getUTCMonth());       //the UTC month value
alert(_date.getUTCDate());        //the UTC day of month value
alert(_date.getUTCHours());       //the UTC hour value
alert(_date.getUTCMinutes());     //the UTC minutes value```

Watch out later, to always ask UTC values from the date object. This way users will see the same date values regardless of local settings.
Otherwise date values will be shifted corresponding to local time settings.

ContentLicense: CC BY-SA 2.5

Body:
In an JS app, I receive timestamp (eq. 1270544790922) from server (Ajax).

Basing on that timestamp I create Date object using:

var _date = new Date();
_date.setTime(1270544790922);

Now, _date decoded timestamp in current user locale time zone. I don't want that.

I would like _date to convert this timestamp to current time in city of Helsinki in Europe (disregarding current time zone of the user).

How can I do that?

Body:
Presuming you get the timestamp in Helsinki time, I would create a date object set to midnight January 1 1970 UTC (for disregarding the local timezone settings of the browser).
Then just add the needed number of milliseconds to it.

var _date = new Date( Date.UTC(1970, 0, 1, 0, 0, 0, 0) );
_date.setUTCMilliseconds(1270544790922);

alert(_date); //date shown shifted corresponding to local time settings
alert(_date.getUTCFullYear());    //the UTC year value
alert(_date.getUTCMonth());       //the UTC month value
alert(_date.getUTCDate());        //the UTC day of month value
alert(_date.getUTCHours());       //the UTC hour value
alert(_date.getUTCMinutes());     //the UTC minutes value

Watch out later, to always ask UTC values from the date object. This way users will see the same date values regardless of local settings.
Otherwise date values will be shifted corresponding to local time settings.


问:
Alternative for Windows Task Scheduler
I need a Task Scheduler for Windows. Unfortunately the builtin scheduler doesn't meet my needs, which are:

can run tasks every minute/hour

runs on Linux and Windows

32 and 64 bit versions

GUI interface

free

Nice to haves:

supports CRON files

open source

status reports of execution times

thanks!

答:
Windows task scheduler is great....... except when it loses its cookies and forgets all the credentials for your tasks.  It has had this issue for years, there have been hotfixes for NT and beyond, but the issue is still there circa Server 2003 R2.  I have no idea if it is finally corrected in newer versions, but it has lasted far too long.

Unacceptable.

Title: Alternative for Windows Task Scheduler


问:
Hypermedia API - Is direct requests an anti pattern?
I'm designing an API using Hypermedia concepts. I saw that is a good practice have a root route that returns the others API links to navigate.

Ex.: I made a request to http://myapi.com and it returns

```<code>{
  links: [
    { 'rel': 'profile', href: '/profile' },
    { 'rel': 'orders', href: '/orders' },
    { 'rel': 'order_types', href: '/order_types' },
    ...
  ]
}
</code>```

But, in this way, if the root had 20 resources it will be very large.

So, made a direct request to order_types instead request root and then request the order_types is a anti pattern?

答:
As I am currently suffering a lot under a large scale HATEOAS style REST API, from my point of view do yourself a favor and place all links (methods) on the start page.

You really do not want to follow several links to find the method you want to use (or test). Of course you could use the direct path, but then again its just RPC-style again.

And as I am sorry to say, the whole concept of HATEOAS though not sounding bad IMHO is a real pain when it comes to implementing and testing.

Body:
I'm designing an API using Hypermedia concepts. I saw that is a good practice have a root route that returns the others API links to navigate.

Ex.: I made a request to http://myapi.com and it returns

{
  links: [
    { 'rel': 'profile', href: '/profile' },
    { 'rel': 'orders', href: '/orders' },
    { 'rel': 'order_types', href: '/order_types' },
    ...
  ]
}

But, in this way, if the root had 20 resources it will be very large.

So, made a direct request to order_types instead request root and then request the order_types is a anti pattern?


问:
CListCtrl does not render well elements' images
I have a CListCtrl and a Picture control and both are rendering the images wrongly. It is happenning for PNG images loaded through CImage::Load

The images are scaled down and have a vertical lines background that should not appear.

答:
It turns out there is the need of a manifest, which I added to stdafx.h

```<code>#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
</code>```

Body:
It turns out there is the need of a manifest, which I added to stdafx.h

#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")


问:
Django: How can I provide different users a different subset of options for the same ManyToManyField

The Question:

How can I provide different users a different subset of options for the same ManyToManyField in the admin, and have each user's selections only affect their options?

The Scenario:

I am building an interactive map web app. There can be many Maps. There can be many MapItems.
MapItems can be on many Maps and Maps can have many Map Items. Thus a ManyToMany relationship.

Each Map has an owner, and I want only the owner of a Map to be able to add or remove MapItems from his/her Map.

Here are the relevant parts of my models:

```<code>class Map(models.Model):
    # Omit
    owner = models.ForeignKey(User, default=1)

class MapItem(models.Model):
    # Omit
    map = models.ManyToManyField(Map, default=None, blank=True)
</code>```

MapItem.map is represented by a <select> on the MapItem admin interface:

```<code><select multiple="multiple" id="id_map" name="map">
  <option value="1">Bob's Map</option>
  <option value="2">Sally's Map</option>
</select>
</code>```

I want Bob to only have the option to select/deselect Bob's Map and not even see Sally's Map as an option.

I have been able to filter the options that are displayed in the admin <select> widget by overriding get_form() on the ModelAdmin.

```<code>def get_form(self, request, obj=None, **kwargs):
    kwargs['form'] = MapItemAdminForm
    form = super(MapItemAdmin, self).get_form(request, obj, **kwargs)
    form.base_fields['map'].queryset = form.base_fields['map'].queryset.filter(Q(owner=request.user) | Q(groups__in=request.user.groups.all()))
    return form
</code>```

So far so good. This gives me a select with only the desired options:

```<code><select multiple="multiple" id="id_map" name="map">
  <option value="1">Bob's Map</option>
</select>
</code>```

The problem comes in when Bob saves. When Bob saves, it wipes out any saved value for Sally's Map. So if Sally's Map was selected, when Bob saves (even though Bob can't see it), Sally's Map gets deselected.

Is there a better approach to this problem? Is there a way to ensure that unchanged values (like Sally's Map being selected) persist on save?

答:
Try overriding the ModelAdmin's save_model method.

In it, you will need to delete all relations that belong to the current user (instead of deleting all relations which is the current behavior) and save all submitted relations (which you know belong to the current user because you filtered the options, but you should probably re-validate this in a previous step because HTTP requests can be tampered with) again.

Body:
The Question:

How can I provide different users a different subset of options for the same ManyToManyField in the admin, and have each user's selections only affect their options?

The Scenario:

I am building an interactive map web app. There can be many Maps. There can be many MapItems.
MapItems can be on many Maps and Maps can have many Map Items. Thus a ManyToMany relationship.

Each Map has an owner, and I want only the owner of a Map to be able to add or remove MapItems from his/her Map.

Here are the relevant parts of my models:

class Map(models.Model):
    # Omit
    owner = models.ForeignKey(User, default=1)

class MapItem(models.Model):
    # Omit
    map = models.ManyToManyField(Map, default=None, blank=True)

MapItem.map is represented by a <select> on the MapItem admin interface:

<select multiple="multiple" id="id_map" name="map">
  <option value="1">Bob's Map</option>
  <option value="2">Sally's Map</option>
</select>

I want Bob to only have the option to select/deselect Bob's Map and not even see Sally's Map as an option.

I have been able to filter the options that are displayed in the admin <select> widget by overriding get_form() on the ModelAdmin.

def get_form(self, request, obj=None, **kwargs):
    kwargs['form'] = MapItemAdminForm
    form = super(MapItemAdmin, self).get_form(request, obj, **kwargs)
    form.base_fields['map'].queryset = form.base_fields['map'].queryset.filter(Q(owner=request.user) | Q(groups__in=request.user.groups.all()))
    return form

So far so good. This gives me a select with only the desired options:

<select multiple="multiple" id="id_map" name="map">
  <option value="1">Bob's Map</option>
</select>

The problem comes in when Bob saves. When Bob saves, it wipes out any saved value for Sally's Map. So if Sally's Map was selected, when Bob saves (even though Bob can't see it), Sally's Map gets deselected.

Is there a better approach to this problem? Is there a way to ensure that unchanged values (like Sally's Map being selected) persist on save?


问:
How to align an image to the bottom of the div?
I'm trying to align an image to the bottom of the out div element using vertical-align,but this vertical-align doesn't seem to work,the image is not moving at all.

```<code> <div class="row">
     <div class="col-md-1">
       <img src="../images/image.png" style="height: 20px; width: 20px;cursor:pointer"/>
     </div>
     <div class=col-md-11 >
        <div  style="overflow:auto;height:300px"></div>
     </div>
</div>
</code>```

I'm using bootstrap classes for alignments. Is there anything that can make the image div align to the bottom of the outer div?Which is taking the height of second div which is 300px;.

答:
You can use flexbox for this. Appling the parent styles to the DIV. No extra styling needed for img

```<code>.parent {
  display: flex;
  justify-content: flex-end;
  flex-direction: column;
}
</code>```

Here's what you'll want to add if you don't have a taskrunner adding the prefixes for maximum compatibility.

```<code>.parent {
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-justify-content: flex-end;
            -ms-flex-pack: end;
          justify-content: flex-end;
  -webkit-flex-direction: column;
      -ms-flex-direction: column;
          flex-direction: column;
}
</code>```

Currently 97% of the browsers used today support flex.

Body:
I'm trying to align an image to the bottom of the out div element using vertical-align,but this vertical-align doesn't seem to work,the image is not moving at all.

I'm using bootstrap classes for alignments. Is there anything that can make the image div align to the bottom of the outer div?Which is taking the height of second div which is 300px;.

Body:
You can use flexbox for this. Appling the parent styles to the DIV. No extra styling needed for img

.parent {
  display: flex;
  justify-content: flex-end;
  flex-direction: column;
}

Here's what you'll want to add if you don't have a taskrunner adding the prefixes for maximum compatibility.

.parent {
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-justify-content: flex-end;
            -ms-flex-pack: end;
          justify-content: flex-end;
  -webkit-flex-direction: column;
      -ms-flex-direction: column;
          flex-direction: column;
}

Currently 97% of the browsers used today support flex.


问:
jQuery plugin which lets users draw rectangles in a div works in basic setup, but not when implemented in my page?
I'm using this Boxer plugin to allow the user to draw rectangles in a div. I've got it working in this jsFiddle.

But I can't get it working in this one, which is how I would be using it. I think it may be because of the CSS styling? Can anyone tell why it doesn't work?

Thanks for reading.

答:
You're missing
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>

```

Sometimes it's the simplest things that get ya :)

Updated sample: http://jsfiddle.net/q75J7/

Body:
You're missing <script> declarations for jQuery and jQuery UI:  I updated the head of your sample:

<head>
    <title>Page</title>
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" media="screen" rel="stylesheet" type="text/css" />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
</head>

Sometimes it's the simplest things that get ya :)

Updated sample: http://jsfiddle.net/q75J7/


问:
Difference between prune and recursive-exclude in setuptools?
I am using setuptools to package a custom module for deployment, which should not include certain files in the data/ directory that were used for development. I have succesfully excluded the necessary files using recursive-exclude data/ * in my MANIFEST.in file, but I also see that I could do this via prune data/

Both approaches remove the intended files from package.egg-info/SOURCES.txt after packaging via python setup.py egg_info

Is there any difference between the two?

答:
Based on the documentation behaviour is:

recursive-exclude dir pat1 pat2 takes the directory dir and ignores all the files that match patterns pat1 and pat2

prune dir will exclude all files within the directory dir

So in your case recursive-exclude dir * and prune dir should have the same behaviour, except that prune will remove the whole directory, whereas recursive-exclude will preserve an empty folder.


问:
AngularJS directives: ng-click is not triggered after blur
DEMO

Consider the following example:

<input type="text" ng-model="client.phoneNumber" phone-number>
<button ng-click="doSomething()">Do Something</button>
```

<pre class="lang-javascript prettyprint-override"><code>.directive("phoneNumber", function($compile) {
  return {
    restrict: 'A',
    scope: true,
    link: function(scope, element, attrs) {
      scope.mobileNumberIsValid = true;

      var errorTemplate = "<span ng-show='!mobileNumberIsValid'>Error</span>";

      element.after($compile(errorTemplate)(scope)).on('blur', function() {
        scope.$apply(function() {
          scope.mobileNumberIsValid = /^\d*$/.test(element.val());
        });
      });
    }
  };
});
</code>```

Looking at the demo, if you add say 'a' at the end of the phone number, and click the button, doSomething() is not called. If you click the button again, then doSomething() is called.

Why doSomething() is not called for the first time? Any ideas how to fix this?

Note: It is important to keep the validation on blur.

答:
I fixed it with the following.</p>

```<code><button class="submitButton form-control" type="submit" ng-mousedown="this.form.submit();" >
</code>```

Body:
DEMO

Consider the following example:

<input type="text" ng-model="client.phoneNumber" phone-number>
<button ng-click="doSomething()">Do Something</button>

.directive("phoneNumber", function($compile) {
  return {
    restrict: 'A',
    scope: true,
    link: function(scope, element, attrs) {
      scope.mobileNumberIsValid = true;

      var errorTemplate = "Error";

      element.after($compile(errorTemplate)(scope)).on('blur', function() {
        scope.$apply(function() {
          scope.mobileNumberIsValid = /^\d*$/.test(element.val());
        });
      });
    }
  };
});

Looking at the demo, if you add say 'a' at the end of the phone number, and click the button, doSomething() is not called. If you click the button again, then doSomething() is called.

Why doSomething() is not called for the first time? Any ideas how to fix this?

Note: It is important to keep the validation on blur.

Body:
I fixed it with the following.

<button class="submitButton form-control" type="submit" ng-mousedown="this.form.submit();" >


问:
Show listview in middle of method but wait until SelectionChanged event fires before method continues
Windows UWP app in C#. I have a method that checks a condition and depending on the condition, it may need to show a listview to the user so they can select an item from the list. I have more code in the method, after I potentially show the list view that needs to run after. However, because the listview shows and I have to wait for the SelectionChanged event handler to fire, I cannot figure out how to pause the calling method on that line until the event handler is completed for SelectionChanged. I don't have code written yet, so here is some pseduo code to illustrate:

```<code>private void LookupEmployee(string searchCriteria)
{
     List<string> matches = GetEmployeeNameMatchesFromCriteria(searchCriteria);

     if(matches.Count == null || matches.Count == 0)
     {
         //No matches found, warn user
         return;
     }
     if(matches.Count == 1)
     {
         //We are good, we have just one match which is desirable.
     }
     if(matches.Count > 1)
     {
         //This means we have more than one match and we need to popup list view to have user select one
         ShowListView(matches);
     }

     //Process Employee data here.
}
</code>```

I know one option is to "daisy chain" calls by breaking out the final processing of employee data to another method and call that from the event handler for SelectionChanged of the listview. However, this has two issues. First, if I just have one match, then I will not be showing the listview or getting the SelectionChanged anyway. Second, if I had a bunch of variables and other things at the beginning of the method to be used at the end of the method, I don't want to (nor do I know how to) pass all of that through and back from the event handler in the event I need to show it.

I guess what I am looking for in a way is how the MessageDialog is handled.

```<code> var md = new MessageDialog("My Message");

 md.Commands.Add(new UICommand("Okay")
 {

 });

 var result = await md.ShowAsync();

 if (result.Label == "Okay")
 {
     DoStuff;
 }
</code>```

Where using this will wait on the line:

await md.ShowAsync();

Until the user clicks the button, at which point the method can continue from there.

I guess I am looking for something similar to that where I can hold on the line of the method in the case that I need to show the listview until the user selects and item and grab the item that was selected.

Thoughts?

Thanks!

答:
Okay, I think I found what I was looking for so I wanted to post the code. This is similar to how a modal window worked in the old days. Basically, you can use a ContentDialog which will allow you to "wrap" any controls you want in it. In my case, I want to show a ListView, so I wrap that in the ContentDialog. Here is what I have:

First we can do our tests and based on the tests, we can create the ContentDialog/ListView if needed. If we do create the ContentDialog, we can also setup the Display parameters so it fits the way we want it to.

```<code>private async void checkProductMatches()
{
    var selectedItem = string.Empty;

    //Check our results from DB.
    if (productResults.Count == 0)
    {
        //This means we didn't find any matches, show message dialog
    }
    if (productResults.Count == 1)
    {
        //We found one match, this is ideal. Continue processing.
        selectedItem = productResults.FirstOrDefault().Name;
    }
    if (productResults.Count > 1)
    {
        //Multiple matches, need to show ListView so they can select one.
        var myList = new ListView
        {
            ItemTemplate = Create(),
            ItemsSource =
                productResults,
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Stretch
        };

        var bounds = Window.Current.Bounds;
        var height = bounds.Height;
        var scroll = new ScrollViewer() { HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Stretch, Height = height - 100 };

        var grid = new StackPanel();
        grid.Children.Add(myList);
        scroll.Content = grid;
        var dialog = new ContentDialog { Title = "Title", Content = scroll };
</code>```

Now, we wire up the event handler for the ListView SelectionChanged event and grab the selectedItem should this event raise.

```<code>        myList.SelectionChanged += delegate (object o, SelectionChangedEventArgs args)
        {
            if (args.AddedItems.Count > 0)
            {
                MyProducts selection = args.AddedItems[0] as MyProducts;
                if (selection != null)
                {
                    selectedItem = selection.Name;
                }
            }
            dialog.Hide();
        };
</code>```

Finally, we await the showing of the ContentDialog.

```<code>        var s = await dialog.ShowAsync();
</code>```

What this will do is, if we have one item, there is no need to popup the content dialog. So, we can assign the one result to our selectedItem variable and proceed. However, if we have multiple matches, we want to display a list for the user to select the one item. In this case, we create the ContentDialog, ListView and display parameters. They key is to wire up the event handler before we call to show the dialog and inside of the event handler, we make sure to cancel or close the dialog. Then we call to await the dialog showing. This will pause execution of this method on that line while the dialog is showing. Once the user selects an item, the event handler will raise, get the selected item and then close the dialog, which will then allow the method to continue execution from the awaited line.

Here is the full method:

```<code>    private async void checkProductMatches()
    {
        var selectedItem = string.Empty;

        //Check our results from DB.
        if (productResults.Count == 0)
        {
            //This means we didn't find any matches, show message dialog
        }
        if (productResults.Count == 1)
        {
            //We found one match, this is ideal. Continue processing.
            selectedItem = productResults.FirstOrDefault().Name;
        }
        if (productResults.Count > 1)
        {
            //Multiple matches, need to show ListView so they can select one.
            var myList = new ListView
            {
                ItemTemplate = Create(),
                ItemsSource =
                    productResults,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch
            };

            var bounds = Window.Current.Bounds;
            var height = bounds.Height;
            var scroll = new ScrollViewer() { HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Stretch, Height = height - 100 };

            var grid = new StackPanel();
            grid.Children.Add(myList);
            scroll.Content = grid;
            var dialog = new ContentDialog { Title = "Title", Content = scroll };

            myList.SelectionChanged += delegate (object o, SelectionChangedEventArgs args)
            {
                if (args.AddedItems.Count > 0)
                {
                    MyProducts selection = args.AddedItems[0] as MyProducts;
                    if (selection != null)
                    {
                        selectedItem = selection.Name;
                    }
                }
                dialog.Hide();
            };

            var s = await dialog.ShowAsync();
        }

        //Test furter execution. Ideally, selected item will either be the one record or we will
        //get here after the list view allows user to select one.
        var stringTest = string.Format("Selected Item: {0}", selectedItem);
    }
</code>```

Hope this helps someone.

Body:
Windows UWP app in C#. I have a method that checks a condition and depending on the condition, it may need to show a listview to the user so they can select an item from the list. I have more code in the method, after I potentially show the list view that needs to run after. However, because the listview shows and I have to wait for the SelectionChanged event handler to fire, I cannot figure out how to pause the calling method on that line until the event handler is completed for SelectionChanged. I don't have code written yet, so here is some pseduo code to illustrate:

private void LookupEmployee(string searchCriteria)
{
     List<string> matches = GetEmployeeNameMatchesFromCriteria(searchCriteria);

     if(matches.Count == null || matches.Count == 0)
     {
         //No matches found, warn user
         return;
     }
     if(matches.Count == 1)
     {
         //We are good, we have just one match which is desirable.
     }
     if(matches.Count > 1)
     {
         //This means we have more than one match and we need to popup list view to have user select one
         ShowListView(matches);
     }

     //Process Employee data here.
}

I know one option is to "daisy chain" calls by breaking out the final processing of employee data to another method and call that from the event handler for SelectionChanged of the listview. However, this has two issues. First, if I just have one match, then I will not be showing the listview or getting the SelectionChanged anyway. Second, if I had a bunch of variables and other things at the beginning of the method to be used at the end of the method, I don't want to (nor do I know how to) pass all of that through and back from the event handler in the event I need to show it.

I guess what I am looking for in a way is how the MessageDialog is handled.

 var md = new MessageDialog("My Message");

 md.Commands.Add(new UICommand("Okay")
 {

 });

 var result = await md.ShowAsync();

 if (result.Label == "Okay")
 {
     DoStuff;
 }

Where using this will wait on the line:

await md.ShowAsync();

Until the user clicks the button, at which point the method can continue from there.

I guess I am looking for something similar to that where I can hold on the line of the method in the case that I need to show the listview until the user selects and item and grab the item that was selected.

Thoughts?

Thanks!

Body:
Okay, I think I found what I was looking for so I wanted to post the code. This is similar to how a modal window worked in the old days. Basically, you can use a ContentDialog which will allow you to "wrap" any controls you want in it. In my case, I want to show a ListView, so I wrap that in the ContentDialog. Here is what I have:

First we can do our tests and based on the tests, we can create the ContentDialog/ListView if needed. If we do create the ContentDialog, we can also setup the Display parameters so it fits the way we want it to.

private async void checkProductMatches()
{
    var selectedItem = string.Empty;

    //Check our results from DB.
    if (productResults.Count == 0)
    {
        //This means we didn't find any matches, show message dialog
    }
    if (productResults.Count == 1)
    {
        //We found one match, this is ideal. Continue processing.
        selectedItem = productResults.FirstOrDefault().Name;
    }
    if (productResults.Count > 1)
    {
        //Multiple matches, need to show ListView so they can select one.
        var myList = new ListView
        {
            ItemTemplate = Create(),
            ItemsSource =
                productResults,
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Stretch
        };

        var bounds = Window.Current.Bounds;
        var height = bounds.Height;
        var scroll = new ScrollViewer() { HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Stretch, Height = height - 100 };

        var grid = new StackPanel();
        grid.Children.Add(myList);
        scroll.Content = grid;
        var dialog = new ContentDialog { Title = "Title", Content = scroll };

Now, we wire up the event handler for the ListView SelectionChanged event and grab the selectedItem should this event raise.

        myList.SelectionChanged += delegate (object o, SelectionChangedEventArgs args)
        {
            if (args.AddedItems.Count > 0)
            {
                MyProducts selection = args.AddedItems[0] as MyProducts;
                if (selection != null)
                {
                    selectedItem = selection.Name;
                }
            }
            dialog.Hide();
        };

Finally, we await the showing of the ContentDialog.

        var s = await dialog.ShowAsync();

What this will do is, if we have one item, there is no need to popup the content dialog. So, we can assign the one result to our selectedItem variable and proceed. However, if we have multiple matches, we want to display a list for the user to select the one item. In this case, we create the ContentDialog, ListView and display parameters. They key is to wire up the event handler before we call to show the dialog and inside of the event handler, we make sure to cancel or close the dialog. Then we call to await the dialog showing. This will pause execution of this method on that line while the dialog is showing. Once the user selects an item, the event handler will raise, get the selected item and then close the dialog, which will then allow the method to continue execution from the awaited line.

Here is the full method:

    private async void checkProductMatches()
    {
        var selectedItem = string.Empty;

        //Check our results from DB.
        if (productResults.Count == 0)
        {
            //This means we didn't find any matches, show message dialog
        }
        if (productResults.Count == 1)
        {
            //We found one match, this is ideal. Continue processing.
            selectedItem = productResults.FirstOrDefault().Name;
        }
        if (productResults.Count > 1)
        {
            //Multiple matches, need to show ListView so they can select one.
            var myList = new ListView
            {
                ItemTemplate = Create(),
                ItemsSource =
                    productResults,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch
            };

            var bounds = Window.Current.Bounds;
            var height = bounds.Height;
            var scroll = new ScrollViewer() { HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Stretch, Height = height - 100 };

            var grid = new StackPanel();
            grid.Children.Add(myList);
            scroll.Content = grid;
            var dialog = new ContentDialog { Title = "Title", Content = scroll };

            myList.SelectionChanged += delegate (object o, SelectionChangedEventArgs args)
            {
                if (args.AddedItems.Count > 0)
                {
                    MyProducts selection = args.AddedItems[0] as MyProducts;
                    if (selection != null)
                    {
                        selectedItem = selection.Name;
                    }
                }
                dialog.Hide();
            };

            var s = await dialog.ShowAsync();
        }

        //Test furter execution. Ideally, selected item will either be the one record or we will
        //get here after the list view allows user to select one.
        var stringTest = string.Format("Selected Item: {0}", selectedItem);
    }

Hope this helps someone.


问:
Is it possible to combine this javascript function into JQuery?
I have a function written in javascript and I'd like to know how, if it's possible, to use it in my JQuery file. I'm using the following function and my selector id is '#comments'.

Again, all I want to do is just consolidate this function which now resides in another file, into my main JQuery file. Is this possible?

```<code>onkeydown="textCounter(this.form.notes, this.form.remLen,240); "onkeyup="textCounter(this.form.notes, this.form.remLen, 240);"
</code>```

The selector id is #comments.

```<code>function textCounter( field, countfield, maxlimit ){
if ( field.value.length > maxlimit )    {
    field.value = field.value.substring( 0, maxlimit );
}else{
    countfield.value = maxlimit - field.value.length;
}
</code>```

答:
I'm not quite sure what you're asking, but you can easily use your own function in these event handlers like this:

```<code>$(document).ready( function(){
  $('#comments').bind('keydown keyup', function(){
    textCounter( ...etc... );
  });
});
</code>```

Depending on what you're trying to do, you might have better luck with the keypress event instead:

```<code>  $('#comments').keypress( function(){...} );
</code>```

Keypress has the advantages of being triggered for every character when a key is held down for auto-repeating, and not being triggered for keys like shift. With keydown and keyup you'll be running your function twice for each pressed key, which may not be what you want.

Update: If all you're looking to do is truncate and show the current count, why not make a simpler function, like this:

```<code>function textCounter( field, countfield, limit ){
  field.value = field.value.substring(0,limit);
  countfield.val( limit-field.value.length );
}
</code>```

And then:

```<code>$('#comments').keypress( function(){
  textCounter(this, $('#bar'), 240 );
});
</code>```

Example: http://jsfiddle.net/redler/c5sUU/1/

Body:
I have a function written in javascript and I'd like to know how, if it's possible, to use it in my JQuery file. I'm using the following function and my selector id is '#comments'.

Again, all I want to do is just consolidate this function which now resides in another file, into my main JQuery file. Is this possible?

onkeydown="textCounter(this.form.notes, this.form.remLen,240); "onkeyup="textCounter(this.form.notes, this.form.remLen, 240);"

The selector id is #comments.

function textCounter( field, countfield, maxlimit ){
if ( field.value.length > maxlimit )    {
    field.value = field.value.substring( 0, maxlimit );
}else{
    countfield.value = maxlimit - field.value.length;
}

Body:
I'm not quite sure what you're asking, but you can easily use your own function in these event handlers like this:

$(document).ready( function(){
  $('#comments').bind('keydown keyup', function(){
    textCounter( ...etc... );
  });
});

Depending on what you're trying to do, you might have better luck with the keypress event instead:

  $('#comments').keypress( function(){...} );

Keypress has the advantages of being triggered for every character when a key is held down for auto-repeating, and not being triggered for keys like shift. With keydown and keyup you'll be running your function twice for each pressed key, which may not be what you want.

Update: If all you're looking to do is truncate and show the current count, why not make a simpler function, like this:

function textCounter( field, countfield, limit ){
  field.value = field.value.substring(0,limit);
  countfield.val( limit-field.value.length );
}

And then:

$('#comments').keypress( function(){
  textCounter(this, $('#bar'), 240 );
});

Example: http://jsfiddle.net/redler/c5sUU/1/


问:
Is it possible to mix 2 ORMS in same web app?
So is it possible to mix 2 ORM's in same web app,and if so how optimal would it be ? Why so?
- I'm working on a web app in flask using flask-mysqldb and I came to a point where I need to implement an auth system, and on flask-mysqldb there's no secure way to do it.
- With that said now I'm trying to implement flask-security but it only works on flask-sqlalchemy so I'm trying to mix sqlalchemy with mysqldb and before that I want to know if it's optimal and if it works.That would lead to using user auth along sqlalchemy and other data to mysqldb.Thanks!</p>

答: You can have a module for each orm. One module can be called auth_db and the other can be called data_db. In your main app file just import both modules and initialize the database connections. That being said, this approach will be harder to maintain in the future, and harder for other developers to understand what's going on. I'd recommend moving your flask-mysqldb code to sqlalchemy so that you are only using one ORM.</p>


问:
Is there a way of making the following shape by CSS coding
Is there a way of making the following shape by CSS coding, without JavaScript?

答:
I have to add the alternative :) (edited to add: as inline SVG)</p>

```<code><svg height="55" width="50">
 <path d="M 45 40 A 25 25 0 0 1 5 40" stroke="blue" stroke-width="10" fill="none" />
  Sorry, your browser does not support inline SVG.
</svg>
</code>```

Body:
I have to add the alternative :) (edited to add: as inline SVG)

<svg height="55" width="50">
 <path d="M 45 40 A 25 25 0 0 1 5 40" stroke="blue" stroke-width="10" fill="none" />
  Sorry, your browser does not support inline SVG.
</svg>


问:
What tool can I use to build a nicely-formatted SQL DB diagram on a Mac?
I need to create an entity relationship diagram for a MySQL database. It doesn't need to be automatically generated or anything, and I don't have foreign keys defined anyway.

I could swear that I once used a tool that would display the relationships between fields, but this old screenshot from MS Access is the closest I've been able to find to what I'm trying to do (source: http://acdrupal.evergreen.edu/files/studycenter/database_entity_relationship_diagram.jpg).

Can anyone name an app (preferably for Macs) that can be used to build this kind of diagram? I've tried several of the popular ones - ArgoUML, OmniGraffle, MySQL Workbench - but it doesn't seem that any of them will show those relationship lines from one specific field to another. Instead, they have a generic one-to-one or many-to-one line that goes to the table, but not the specific field.

答:
http://www.malcolmhardie.com/sqleditor/

This looks like it supports it if I understand what you need


问:
Difference time between two string not time of day in vba
I don't find a solution for this problem, I have two string with this format :

```<code>string1 = "23:19:03" (hh:mm:ss)
string2 = "27:08:03" (hh:mm:ss)
</code>```

I'll need calculate time difference between this two string like

```<code>string1 = "23:19:03"
string2 = "27:08:03"
diff = 3:49:00   (h:m:s)
</code>```

UPDATE
I found a solution :

fell free to use my code with mention me, thanks

```<code>Public Function timediff(ByVal time1 As String, ByVal time2 As String) As String
'Author: © Copyright 2017 Audisio Francesco **************************
'Description: Time diffence betweem two string no time of day!!,the format of this two string is ([h]:mm:ss) like excel function
'             time2 must be greater than time1
Dim ore1, ore2, min1, min2, sec1, sec2, tot1, tot2, tot, ore, apsec, min, sec As Double
Dim aladin1() As String
Dim aladin2() As String
'Dim time1, time2 As String
'genero secondi totali
aladin1 = Split(time1, ":")
    ore1 = Val(aladin1(0)) 'Ore
    ore1 = ore1 * 3600
    min1 = Val(aladin1(1)) 'minuti
    min1 = min1 * 60
    sec1 = Val(aladin1(2)) 'secondi
    sec1 = sec1
aladin2 = Split(time2, ":")
    ore2 = Val(aladin2(0)) 'Ore
    ore2 = ore2 * 3600
    min2 = Val(aladin2(1)) 'minuti
    min2 = min2 * 60
    sec2 = Val(aladin2(2)) 'secondi
    sec2 = sec2
'prendo i totali
tot1 = ore1 + min1 + sec1
tot2 = ore2 + min2 + sec2
tot = tot2 - tot1

ore = Int(tot / 3600)
apsec = tot - (3600 * ore)
min = Int(apsec / 60)
sec = apsec - (min * 60)
result = (ore & ":" & min & ":" & sec)
timediff = result
End Function
</code>```

Use:

```<code>string1 = "23:19:03"
string2 = "27:08:03"
ore1 = timediff(time1, time2)
ore1 = 3:49:0
</code>```

答:
you could use this helper function

```<code>Function GetDiffTime(string1 As String, string2 As String) As String
    GetDiffTime = GetTime(GetSeconds(string2) - GetSeconds(string1))
End Function
</code>```

which, on its turn, uses the following functions:

```<code>Function GetTime(seconds As Long) As String
    Dim rest As Long

    rest = seconds \ 3600
    GetTime = GetTime & Format(rest, "00")
    seconds = seconds - rest * 3600

    rest = seconds \ 60
    GetTime = GetTime & ":" & Format(rest, "00")
    seconds = seconds - rest * 60

    GetTime = GetTime & ":" & Format(seconds, "00")
End Function

Function GetSeconds(strng As String) As Long
    Dim timeParts As Variant
    Dim iPart As Integer

    timeParts = Split(strng, ":")
    For iPart = UBound(timeParts) To LBound(timeParts) Step -1
        GetSeconds = GetSeconds + CInt(timeParts(iPart)) * 60 ^ (UBound(timeParts) - iPart)
    Next
End Function
</code>```

Body:
I don't find a solution for this problem, I have two string with this format :

string1 = "23:19:03" (hh:mm:ss)
string2 = "27:08:03" (hh:mm:ss)

I'll need calculate time difference between this two string like

string1 = "23:19:03"
string2 = "27:08:03"
diff = 3:49:00   (h:m:s)

UPDATE
I found a solution :

fell free to use my code with mention me, thanks

Public Function timediff(ByVal time1 As String, ByVal time2 As String) As String
'Author: © Copyright 2017 Audisio Francesco **************************
'Description: Time diffence betweem two string no time of day!!,the format of this two string is ([h]:mm:ss) like excel function
'             time2 must be greater than time1
Dim ore1, ore2, min1, min2, sec1, sec2, tot1, tot2, tot, ore, apsec, min, sec As Double
Dim aladin1() As String
Dim aladin2() As String
'Dim time1, time2 As String
'genero secondi totali
aladin1 = Split(time1, ":")
    ore1 = Val(aladin1(0)) 'Ore
    ore1 = ore1 * 3600
    min1 = Val(aladin1(1)) 'minuti
    min1 = min1 * 60
    sec1 = Val(aladin1(2)) 'secondi
    sec1 = sec1
aladin2 = Split(time2, ":")
    ore2 = Val(aladin2(0)) 'Ore
    ore2 = ore2 * 3600
    min2 = Val(aladin2(1)) 'minuti
    min2 = min2 * 60
    sec2 = Val(aladin2(2)) 'secondi
    sec2 = sec2
'prendo i totali
tot1 = ore1 + min1 + sec1
tot2 = ore2 + min2 + sec2
tot = tot2 - tot1

ore = Int(tot / 3600)
apsec = tot - (3600 * ore)
min = Int(apsec / 60)
sec = apsec - (min * 60)
result = (ore & ":" & min & ":" & sec)
timediff = result
End Function

Use:

string1 = "23:19:03"
string2 = "27:08:03"
ore1 = timediff(time1, time2)
ore1 = 3:49:0

Body:
you could use this helper function

Function GetDiffTime(string1 As String, string2 As String) As String
    GetDiffTime = GetTime(GetSeconds(string2) - GetSeconds(string1))
End Function

which, on its turn, uses the following functions:

Function GetTime(seconds As Long) As String
    Dim rest As Long

    rest = seconds \ 3600
    GetTime = GetTime & Format(rest, "00")
    seconds = seconds - rest * 3600

    rest = seconds \ 60
    GetTime = GetTime & ":" & Format(rest, "00")
    seconds = seconds - rest * 60

    GetTime = GetTime & ":" & Format(seconds, "00")
End Function

Function GetSeconds(strng As String) As Long
    Dim timeParts As Variant
    Dim iPart As Integer

    timeParts = Split(strng, ":")
    For iPart = UBound(timeParts) To LBound(timeParts) Step -1
        GetSeconds = GetSeconds + CInt(timeParts(iPart)) * 60 ^ (UBound(timeParts) - iPart)
    Next
End Function


问:
docker-credential-osxkeychain wants to use your confidential information
This has started happening recently after a docker update on my Macbook.
I am using Docker version 17.03.0-ce-mac2 on macos-sierra.

If I run a docker build -t . from a terminal I get a pop-up warning which says:

docker-credential-osxkeychain wants to use your confidential information stored in mydomain.com in your keychain.
Do you want to allow access to this item?

If I click 'deny' everything continues as normal without any issues. But I have to do this every time.

What does this mean ?

答:
It looks like it was a bug in this particular release of Docker and that the new release 17.03.1-ce-mac5 is solving this issue.  There is a reference in the release notes: https://github.com/docker/docker-credential-helpers/releases/tag/v0.5.0

I just installed this release and I don't have this behaviour on my El Capitan install.


问:
Close Bootstrap modal from inside iframe and go to a specific section of parent page
index.html

```<code><a href="" data-toggle="modal" data-target="#myModal">Open Modal</a>

<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog" style="width:100%;margin: 0px auto;">
    <!-- Modal content-->
    <div class="modal-content">
        <div class="modal-body modalIframe">
            <iframe src="services/abc.html" frameborder="0" height="650px" width="100%"></iframe>
       </div>
    </div>
  </div>
</div>
</code>```

SCRIPT

```<code>    window.closeModal = function(){
        $('#myModal').modal('hide');
    };
    $('#contactClick,.closeMain').click(function(){
        window.parent.closeModal();
    });
</code>```

abc.html

```<code><button type="button" class="btn btn-default serviceButton fontSize16px" id="contactClick">Contact us directly   </button>
</code>```

On click of this button I need to go to a section called hire-us i.e it should redirect to index.html#hire-us.
I tried to give anchor tag instead of button and give path in href but it doesn't work.
Please help me solve this.

答:
This worked for me (Inside the iframe page):

```<code>  $('#btnCancel').click(function() {
      parent.$('#ModalEquipment').modal('hide');
   });
</code>```

ModalEquipment -> the name of the modal in the principal page.

```<code><div class="modal fade" id="ModalEquipment" tabindex="-1" role="dialog"      aria-labelledby="videoModal" aria-hidden="true">
       <div class="modal-dialog">
         <div class="modal-content">
             <div class="modal-body">
                  <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                 <div>
                     <iframe src="" frameborder="0"></iframe>
                  </div>
             </div>
         </div>
     </div>
   </div>
</code>```

Body:
index.html

Open Modal

SCRIPT

    window.closeModal = function(){
        $('#myModal').modal('hide');
    };
    $('#contactClick,.closeMain').click(function(){
        window.parent.closeModal();
    });

abc.html

<button type="button" class="btn btn-default serviceButton fontSize16px" id="contactClick">Contact us directly   </button>

On click of this button I need to go to a section called hire-us i.e it should redirect to index.html#hire-us.
I tried to give anchor tag instead of button and give path in href but it doesn't work.
Please help me solve this.

Body:
This worked for me (Inside the iframe page):

  $('#btnCancel').click(function() {
      parent.$('#ModalEquipment').modal('hide');
   });

ModalEquipment -> the name of the modal in the principal page.

<div class="modal fade" id="ModalEquipment" tabindex="-1" role="dialog"      aria-labelledby="videoModal" aria-hidden="true">
       <div class="modal-dialog">
         <div class="modal-content">
             <div class="modal-body">
                  <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                 <div>
                     <iframe src="" frameborder="0"></iframe>
                  </div>
             </div>
         </div>
     </div>
   </div>


问:
Graphql ruby how to create interface type and implement it
I have follow this docs about to create and implement interface on graphql:

here is my code:

```<code>PaymentInterface = GraphQL::InterfaceType.define do
  name 'Payment'

  field :name, types.String
  field :grand_total, MoneyType
  field :subtotal, MoneyType
  field :shipping_fee, MoneyType
end
</code>```

and this is the object type that implement previous interface

```<code>PaypalPaymentType = GraphQL::ObjectType.define do
  interfaces [PaymentInterface]

  field :paypal_charge do
    type -> { MoneyType }
    type types.String
    resolve lambda { |obj, _args, _ctx|
      Hashie::Mash.new(
        currency: obj.currency,
        price: obj.paypal_charge
      )
    }
  end
end
</code>```

Here is the query:

```<code>interface PaymentInterface {
    name: String
    grand_total: MoneyType
    subtotal: MoneyType
    shipping_fee: MoneyType
}
type PaypalPaymentType implements PaymentInterface {
    name: String
    grand_total: MoneyType
    subtotal: MoneyType
    shipping_fee: MoneyType
    paypal_charge: MoneyType
}
{
  purchasables {
    isService
    isProduct
    price
    ... on PaypalPaymentType {
      paypal_charge { raw formatted }
    }
  }
}
</code>```

But Im keep getting error, anyone has the same experience before? thanks in advance

```<code>GraphQL::Schema::InvalidTypeError (Field PaymentMethod.paypal_charge is invalid: name must return String, not NilClass (nil)):
</code>```

答:
In here you are defining twice the type of the field:</p>

```<code>PaypalPaymentType = GraphQL::ObjectType.define do
  interfaces [PaymentInterface]

  field :paypal_charge do
    type -> { MoneyType } # <--- Defined type as Money Type
    type types.String # <--- Overwritten defined type as String
    ...
  end
end
</code>```

Body:
I have follow this docs about to create and implement interface on graphql:

here is my code:

PaymentInterface = GraphQL::InterfaceType.define do
  name 'Payment'

  field :name, types.String
  field :grand_total, MoneyType
  field :subtotal, MoneyType
  field :shipping_fee, MoneyType
end

and this is the object type that implement previous interface

PaypalPaymentType = GraphQL::ObjectType.define do
  interfaces [PaymentInterface]

  field :paypal_charge do
    type -> { MoneyType }
    type types.String
    resolve lambda { |obj, _args, _ctx|
      Hashie::Mash.new(
        currency: obj.currency,
        price: obj.paypal_charge
      )
    }
  end
end

Here is the query:

interface PaymentInterface {
    name: String
    grand_total: MoneyType
    subtotal: MoneyType
    shipping_fee: MoneyType
}
type PaypalPaymentType implements PaymentInterface {
    name: String
    grand_total: MoneyType
    subtotal: MoneyType
    shipping_fee: MoneyType
    paypal_charge: MoneyType
}
{
  purchasables {
    isService
    isProduct
    price
    ... on PaypalPaymentType {
      paypal_charge { raw formatted }
    }
  }
}

But Im keep getting error, anyone has the same experience before? thanks in advance

GraphQL::Schema::InvalidTypeError (Field PaymentMethod.paypal_charge is invalid: name must return String, not NilClass (nil)):

Body:
In here you are defining twice the type of the field:

PaypalPaymentType = GraphQL::ObjectType.define do
  interfaces [PaymentInterface]

  field :paypal_charge do
    type -> { MoneyType } # <--- Defined type as Money Type
    type types.String # <--- Overwritten defined type as String
    ...
  end
end


问:
How to detect if user is away in OS X?
I want to start a script when user goes away or returns back to computer. Is there any built-in method in AppleScript to check user's state? If not what else can I use in OS X?</p>

答: Have a look at iAway, a small App which allows you to run Apple Script when you step away from your Mac and return. I use it to set my online status of my messenger Apps and start my screen saver when away and when return to set my online status back. The app comes with other cool features to actually detect if you are physically away utilizing computer vision.</p>

Title: How to detect if user is away in OS X?


问:
Install Angular Material 2 with Angular 4 Unmet Dependency
How do I get Angular Material 2 to work with Angular 4?

I re-installed Angular CLI and now it is at 1.0.0 using: npm install -g @angular/cli

I created a new Angular 4 project using:  ng new MyProject

I tried to install Material 2 but it failed using: npm install --save @angular/material

+-- UNMET PEER DEPENDENCY @angular/common@4.0.0

+-- UNMET PEER DEPENDENCY @angular/core@4.0.0

+-- UNMET PEER DEPENDENCY @angular/http@4.0.0

-- @angular/material@2.0.0-beta.2

Here is what I get when I do a ng -v for the project:
@angular/cli: 1.0.0

node: 6.10.0

os: win32 x64

@angular/common: 4.0.0

@angular/compiler: 4.0.0

@angular/core: 4.0.0

@angular/forms: 4.0.0

@angular/http: 4.0.0

@angular/material: 2.0.0-beta.2

@angular/platform-browser: 4.0.0

@angular/platform-browser-dynamic: 4.0.0

@angular/router: 4.0.0

@angular/cli: 1.0.0

@angular/compiler-cli: 4.0.0

答:
As the previous answer stated, you can use the master as described in their readme on github.

I have been doing this for a while now, and it is a good solution since this project's realease schedule seems to have slowed to about once every 200-300 commits.

CAUTION, however, since these are basically their daily builds. Things get fixed, but sometimes things get broken as well. Even the build itself might be wonky (e.g. a few times they've left out all of the theming files). But if you go to the releases of the material2/builds project, you can get links to all of the past daily builds. That exact build can be referenced precisely in your package.json.

So if at first when you switch to master, everything breaks. Do not despair... yet. First go back to the builds for the last week or two and see if you can't make your project unbroken by linking directly to that one of them.


答:
It's possible, but not recommended. Consider this:

Half of your app will not benefit from anything a proper ORM offers

Adding a field to the table means editing raw SQL in many places, and then changing the model.

Don't forget to keep them in sync.

Alternatively, you can port everything that uses raw mysqldb to use SQLAlchemy:

Need to add a field to your table? Just change the model in one place.

Don't like SQL queries that ORM generates for you? You still have a low-level control over this.

Title: Is it possible to mix 2 ORMS in same web app?

Body:
So is it possible to mix 2 ORM's in same web app,and if so how optimal would it be ? Why so?
- I'm working on a web app in flask using flask-mysqldb and I came to a point where I need to implement an auth system, and on flask-mysqldb there's no secure way to do it.
- With that said now I'm trying to implement flask-security but it only works on flask-sqlalchemy so I'm trying to mix sqlalchemy with mysqldb and before that I want to know if it's optimal and if it works.That would lead to using user auth along sqlalchemy and other data to mysqldb.Thanks!


问:
Can I have two rows inside a detail row in kendo grid?
I want to make a Kendo grid with rowTemplate and detailTemplate.
Inside the rowTemplate I want to put an extra row (tr).
It renders fine, but the last main row does not expand.
See the example in jsfiddle:

Example

Templates and grid:

```<code><div id="grid"></div>
<script id="rowTemplate" type="text/x-kendo-tmpl">
    <tr class="k-master-row">
        <td class="k-hierarchy-cell"><a href="\#" class="k-icon k-plus"></a></td>
        <td> #= FirstName # </td>
        <td> #= LastName # </td>
    </tr>
    <tr >
        <td colspan=4 >#= FirstName # </td>
    </tr>
</script>

<script id="detailTemplate" type="text/x-kendo-tmpl">
    <p>detail stuff</p>
</script>
</code>```

Javascript:

```<code>$("#grid").kendoGrid({
 columns:[
          {
              field: "FirstName",
              title: "First Name"
          },
          {
              field: "LastName",
              title: "Last Name"
          }
 ],

dataSource: {
          data: [
              {
                  FirstName: "Joe",
                  LastName: "Smith"
              },
              {
                  FirstName: "Jane",
                  LastName: "Smith"
              }]
},

rowTemplate:kendo.template($("#rowTemplate").html()),
detailTemplate: kendo.template($("#detailTemplate").html())});
</code>```

Please Help.

答:
Row template is intended to have a single
. If you have multiple, it throws off the selector for the k-master-row. So if you have an extra
, last detail row not selectable, if you have 3
 last 2 rows not selectable, etc.

One workaround would be to use a
 instead of a
 for the additional stuff:

```<code><script id="rowTemplate" type="text/x-kendo-tmpl">
    <tr class="k-master-row">
        <td class="k-hierarchy-cell"><a href="\#" class="k-icon k-plus"></a></td>
        <td> #= FirstName # </td>
        <td> #= LastName # </td>
    </tr>
    <div> // extra stuff with a div so selector of detailRow still works...
        <span>#= FirstName # </span>
    </div>
</script>
</code>```

Body:
I want to make a Kendo grid with rowTemplate and detailTemplate.
Inside the rowTemplate I want to put an extra row (tr).
It renders fine, but the last main row does not expand.
See the example in jsfiddle:

Example

Templates and grid:

Javascript:

$("#grid").kendoGrid({
 columns:[
          {
              field: "FirstName",
              title: "First Name"
          },
          {
              field: "LastName",
              title: "Last Name"
          }
 ],

dataSource: {
          data: [
              {
                  FirstName: "Joe",
                  LastName: "Smith"
              },
              {
                  FirstName: "Jane",
                  LastName: "Smith"
              }]
},

rowTemplate:kendo.template($("#rowTemplate").html()),
detailTemplate: kendo.template($("#detailTemplate").html())});

Please Help.

Body:
Row template is intended to have a single <tr>. If you have multiple, it throws off the selector for the k-master-row. So if you have an extra <tr>, last detail row not selectable, if you have 3 <tr> last 2 rows not selectable, etc.

One workaround would be to use a <div> instead of a <tr> for the additional stuff:

<script id="rowTemplate" type="text/x-kendo-tmpl">
    <tr class="k-master-row">
        <td class="k-hierarchy-cell"><a href="\#" class="k-icon k-plus"></a></td>
        <td> #= FirstName # </td>
        <td> #= LastName # </td>
    </tr>
    <div> // extra stuff with a div so selector of detailRow still works...
        <span>#= FirstName # </span>
    </div>
</script>


问:
adding a textbox to the right corner of the existing pdf using ITextSharp in C#
I tiied to add a TextBox to the right corner of the existing pdf using c#, but im unable to get it done. I have wrote the following code,but it is not helping in solving the problem, can any body please suggest me</p>

```<code>using (MemoryStream stream = new MemoryStream())
{
        PdfReader reader = new PdfReader(bytes);
        PdfReader.unethicalreading = true;
        Paragraph p = new Paragraph();
        Document doc = new Document();

        using (PdfStamper stamper = new PdfStamper(reader, stream))
        {
            PdfContentByte canvas = stamper.GetOverContent(1);
            iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1);

            //PdfContentByte cb = null;
            //PdfImportedPage page;
            int pages = reader.NumberOfPages;
            for (int i = 1; i <= pages; i++)
            {
                var size1 = reader.GetPageSize(i);
                w = size1.Width;
                h = size1.Height;
                stamper.FormFlattening = true;

                TextField tf = new TextField(stamper.Writer, new iTextSharp.text.Rectangle(0, 0, 300, 100), displaytext);
                //Change the orientation of the text
                tf.Rotation = 0;
                stamper.AddAnnotation(tf.GetTextField(), i);
            }
        }
        bytes = stream.ToArray();
}
File.WriteAllBytes(str, bytes);
</code>```

答:
As the OP clarified in comments to the question, he wants

to add the text as a page content in the right bottom corner of the page and

the page content previously existing there to be removed.

A simple implementation of this would include

first covering the existing page content with a filled rectangle and

then writing text there.

These tasks can be achieved with these helper methods:

```<code>void EmptyTextBoxSimple(PdfStamper stamper, int pageNumber, Rectangle boxArea, BaseColor fillColor)
{
    PdfContentByte canvas = stamper.GetOverContent(pageNumber);
    canvas.SaveState();
    canvas.SetColorFill(fillColor);
    canvas.Rectangle(boxArea.Left, boxArea.Bottom, boxArea.Width, boxArea.Height);
    canvas.Fill();
    canvas.RestoreState();
}
</code>```

and

```<code>ColumnText GenerateTextBox(PdfStamper stamper, int pageNumber, Rectangle boxArea)
{
    PdfContentByte canvas = stamper.GetOverContent(pageNumber);
    ColumnText columnText = new ColumnText(canvas);
    columnText.SetSimpleColumn(boxArea);
    return columnText;
}
</code>```

E.g. like this:

```<code>using (PdfReader reader = new PdfReader(source))
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create)))
{
    Rectangle cropBox = reader.GetCropBox(1);
    Rectangle bottomRight = new Rectangle(cropBox.GetRight(216), cropBox.Bottom, cropBox.Right, cropBox.GetBottom(146));
    EmptyTextBoxSimple(stamper, 1, bottomRight, BaseColor.WHITE);
    ColumnText columnText = GenerateTextBox(stamper, 1, bottomRight);
    columnText.AddText(new Phrase("Some test text to draw into a text box in the lower right corner of the first page"));
    columnText.Go();
}
</code>```

For this source page

the sample code generates this

Addendum

In a comment the OP indicated

it is working for all files but for some pdf files it is displaying in the middle

Eventually he supplied a sample file for which the issue occurs. And indeed, with this file the issue could be reproduced.

The cause for the issue is that the pages in the sample file use page rotation, something that iText (only) partially allows users to ignore. In particular iText automatically rotates text to be upright after rotation and transforms coordinates, but when retrieving the cropbox of a page, one still has to apply rotation before making use of it coordinates. Thus, a more complete example would be like this:

```<code>using (PdfReader reader = new PdfReader(source))
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create)))
{
    Rectangle cropBox = reader.GetCropBox(1);
    int rotation = reader.GetPageRotation(1);
    while (rotation > 0)
    {
        cropBox = cropBox.Rotate();
        rotation -= 90;
    }
    Rectangle bottomRight = new Rectangle(cropBox.GetRight(216), cropBox.Bottom, cropBox.Right, cropBox.GetBottom(146));
    EmptyTextBoxSimple(stamper, 1, bottomRight, BaseColor.WHITE);
    ColumnText columnText = GenerateTextBox(stamper, 1, bottomRight);
    columnText.AddText(new Phrase("Some test text to draw into a text box in the lower right corner of the first page"));
    columnText.Go();
}
</code>```

Body:
I tiied to add a TextBox to the right corner of the existing pdf using c#, but im unable to get it done. I have wrote the following code,but it is not helping in solving the problem, can any body please suggest me

using (MemoryStream stream = new MemoryStream())
{
        PdfReader reader = new PdfReader(bytes);
        PdfReader.unethicalreading = true;
        Paragraph p = new Paragraph();
        Document doc = new Document();

        using (PdfStamper stamper = new PdfStamper(reader, stream))
        {
            PdfContentByte canvas = stamper.GetOverContent(1);
            iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1);

            //PdfContentByte cb = null;
            //PdfImportedPage page;
            int pages = reader.NumberOfPages;
            for (int i = 1; i <= pages; i++)
            {
                var size1 = reader.GetPageSize(i);
                w = size1.Width;
                h = size1.Height;
                stamper.FormFlattening = true;

                TextField tf = new TextField(stamper.Writer, new iTextSharp.text.Rectangle(0, 0, 300, 100), displaytext);
                //Change the orientation of the text
                tf.Rotation = 0;
                stamper.AddAnnotation(tf.GetTextField(), i);
            }
        }
        bytes = stream.ToArray();
}
File.WriteAllBytes(str, bytes);

Body:
As the OP clarified in comments to the question, he wants

to add the text as a page content in the right bottom corner of the page and

the page content previously existing there to be removed.

A simple implementation of this would include

first covering the existing page content with a filled rectangle and

then writing text there.

These tasks can be achieved with these helper methods:

void EmptyTextBoxSimple(PdfStamper stamper, int pageNumber, Rectangle boxArea, BaseColor fillColor)
{
    PdfContentByte canvas = stamper.GetOverContent(pageNumber);
    canvas.SaveState();
    canvas.SetColorFill(fillColor);
    canvas.Rectangle(boxArea.Left, boxArea.Bottom, boxArea.Width, boxArea.Height);
    canvas.Fill();
    canvas.RestoreState();
}

and

ColumnText GenerateTextBox(PdfStamper stamper, int pageNumber, Rectangle boxArea)
{
    PdfContentByte canvas = stamper.GetOverContent(pageNumber);
    ColumnText columnText = new ColumnText(canvas);
    columnText.SetSimpleColumn(boxArea);
    return columnText;
}

E.g. like this:

using (PdfReader reader = new PdfReader(source))
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create)))
{
    Rectangle cropBox = reader.GetCropBox(1);
    Rectangle bottomRight = new Rectangle(cropBox.GetRight(216), cropBox.Bottom, cropBox.Right, cropBox.GetBottom(146));
    EmptyTextBoxSimple(stamper, 1, bottomRight, BaseColor.WHITE);
    ColumnText columnText = GenerateTextBox(stamper, 1, bottomRight);
    columnText.AddText(new Phrase("Some test text to draw into a text box in the lower right corner of the first page"));
    columnText.Go();
}

For this source page

the sample code generates this

Addendum

In a comment the OP indicated

it is working for all files but for some pdf files it is displaying in the middle

Eventually he supplied a sample file for which the issue occurs. And indeed, with this file the issue could be reproduced.

The cause for the issue is that the pages in the sample file use page rotation, something that iText (only) partially allows users to ignore. In particular iText automatically rotates text to be upright after rotation and transforms coordinates, but when retrieving the cropbox of a page, one still has to apply rotation before making use of it coordinates. Thus, a more complete example would be like this:

using (PdfReader reader = new PdfReader(source))
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create)))
{
    Rectangle cropBox = reader.GetCropBox(1);
    int rotation = reader.GetPageRotation(1);
    while (rotation > 0)
    {
        cropBox = cropBox.Rotate();
        rotation -= 90;
    }
    Rectangle bottomRight = new Rectangle(cropBox.GetRight(216), cropBox.Bottom, cropBox.Right, cropBox.GetBottom(146));
    EmptyTextBoxSimple(stamper, 1, bottomRight, BaseColor.WHITE);
    ColumnText columnText = GenerateTextBox(stamper, 1, bottomRight);
    columnText.AddText(new Phrase("Some test text to draw into a text box in the lower right corner of the first page"));
    columnText.Go();
}


问:
Adding to Dictionary inside a For Loop
I'm working with a swift playground for a project at Treehouse. I'm having trouble with adding an additional key:value pair to a dictionary inside of a for loop. Here is the code that I have:

```<code>var counter = 0
for (var player) in experiencedPlayers {
counter += 1
if counter % 3 == 0 {
    for team in 1...3 {
        switch team {
            case 1:
                teamSharks.append(player)
                player["Team"] = "Sharks"
            case 2:
                teamDragons.append(player)
                player["Team"] = "Dragons"
            case 3:
                teamRaptors.append(player)
                player["Team"] = "Raptors"
            default: break
            }
        }
    }
}
</code>```

This method does not error out, but it should be adding "Team": "Sharks", etc. to the player's dictionary but it is not. Any suggestions?

答:
You need to modify player before appending player.

```<code>    switch team {
        case 1:
            player["Team"] = "Sharks"
            teamSharks.append(player)
        case 2:
            player["Team"] = "Dragons"
            teamDragons.append(player)
        case 3:
            player["Team"] = "Raptors"
            teamRaptors.append(player)
        default: break
        }
    }
</code>```

This is because player is a value type.

Note that will not have any effect on the data stored in experiencedPlayers, only the teamSharks, etc. arrays.

Title: Adding to Dictionary inside a For Loop

Body:
I'm working with a swift playground for a project at Treehouse. I'm having trouble with adding an additional key:value pair to a dictionary inside of a for loop. Here is the code that I have:

var counter = 0
for (var player) in experiencedPlayers {
counter += 1
if counter % 3 == 0 {
    for team in 1...3 {
        switch team {
            case 1:
                teamSharks.append(player)
                player["Team"] = "Sharks"
            case 2:
                teamDragons.append(player)
                player["Team"] = "Dragons"
            case 3:
                teamRaptors.append(player)
                player["Team"] = "Raptors"
            default: break
            }
        }
    }
}

This method does not error out, but it should be adding "Team": "Sharks", etc. to the player's dictionary but it is not. Any suggestions?

Body:
You need to modify player before appending player.

    switch team {
        case 1:
            player["Team"] = "Sharks"
            teamSharks.append(player)
        case 2:
            player["Team"] = "Dragons"
            teamDragons.append(player)
        case 3:
            player["Team"] = "Raptors"
            teamRaptors.append(player)
        default: break
        }
    }

This is because player is a value type.

Note that will not have any effect on the data stored in experiencedPlayers, only the teamSharks, etc. arrays.


问:
Two stream processing depending on clause filtering java 8
I have Set firstSet and Set secondSet.
I need to get final Set beans;

```<code>Set<Bean> beans = new HashSet<Bean>();
        for(BigDecimal element: firstSet){
            if(secondSet.contains(element)){
                beans.add(new BeanBuilder().id(element).isNew(Boolean.TRUE).build());
            } else {
                beans.add(new BeanBuilder().id(element).isNew(Boolean.FALSE).build());
            }
        }
</code>```

How can I write it using lambda-expression? (need to parse two stream).

```<code>Set<BEBean> arr = firstSet
        .stream()
                   .flatMap( if(secondSet::contains) {
                new BeanBuilder().id(x).isNew(Boolean.TRUE).build();
                } else {
                new BEBuilder().id(x).name(Boolean.FALSE).build();
                })
        .collect(Collectors.toSet());
</code>```

答:
Just avoid the code duplication altogether:

```<code>Set<BEBean> beans = availableResources
    .stream()
    .map(e -> new BeanBuilder().id(e).isNew(secondSet.contains(e)).build())
    .collect(Collectors.toSet());
</code>```

Note that you could have avoided the code duplication in the loop as well:

```<code>Set<Bean> beans = new HashSet<Bean>();
for(BigDecimal element: firstSet)
    beans.add(new BeanBuilder().id(element).isNew(secondSet.contains(element)).build());
</code>```

Body:
I have Set firstSet and Set secondSet.
I need to get final Set beans;

Set<Bean> beans = new HashSet<Bean>();
        for(BigDecimal element: firstSet){
            if(secondSet.contains(element)){
                beans.add(new BeanBuilder().id(element).isNew(Boolean.TRUE).build());
            } else {
                beans.add(new BeanBuilder().id(element).isNew(Boolean.FALSE).build());
            }
        }

How can I write it using lambda-expression? (need to parse two stream).

Set<BEBean> arr = firstSet
        .stream()
                   .flatMap( if(secondSet::contains) {
                new BeanBuilder().id(x).isNew(Boolean.TRUE).build();
                } else {
                new BEBuilder().id(x).name(Boolean.FALSE).build();
                })
        .collect(Collectors.toSet());

Body:
Just avoid the code duplication altogether:

Set<BEBean> beans = availableResources
    .stream()
    .map(e -> new BeanBuilder().id(e).isNew(secondSet.contains(e)).build())
    .collect(Collectors.toSet());

Note that you could have avoided the code duplication in the loop as well:

Set<Bean> beans = new HashSet<Bean>();
for(BigDecimal element: firstSet)
    beans.add(new BeanBuilder().id(element).isNew(secondSet.contains(element)).build());


问:
How can I make certain parts of my html not selectable?
How can I make certain parts of my html not selectable?

I have some absolutely positioned divs that keep getting selected if a user tries to select the content of my page.

Is there a way to make it so certain elements (such as those divs) aren't selectable?

EDIT: The main issue is when someone copies these absolute div's and then pastes them into the rich text editor on my site, the rich text editor breaks on IE.

答:
You can use the ::selection pseudo-element to make the selection of a certain element "invisible":

```<code>p::selection { background-color:transparent; }
p::-moz-selection { background-color:transparent; }
</code>```

However, that doesn't work in IE.

Body:
You can use the ::selection pseudo-element to make the selection of a certain element "invisible":

p::selection { background-color:transparent; }
p::-moz-selection { background-color:transparent; }

However, that doesn't work in IE.


问:
Github file size limit changed 6/18/13. Can't push now
How does this change as of June 18, 2013 affect my existing repository with a file that exceeds that limit? I last pushed 2 months ago with a large file.

I have a large file that I have removed locally but I can not push anything now. I get a "remote error" ... remote: error: File cron_log.log is 126.91 MB; this exceeds GitHub's file size limit of 100 MB

I added the file to .gitignore after original push... But it still exists on remote (origin)

Removing it locally should get rid of it at origin(Github) right? ... but ... it is not letting me push because there is a file on Github that exceeds the limit...

https://github.com/blog/1533-new-file-size-limits

These are the commands I issued plus error messages..

```
git add .
git commit -m "delete cron_log.log"
git push origin master

remote: Error code: 40bef1f6653fd2410fb2ab40242bc879
remote: warning: Error GH413: Large files detected.
remote: warning: See http://git.io/iEPt8g for more information.
remote: error: File cron_log.log is 141.41 MB; this exceeds GitHub's file size limit of 100 MB
remote: error: File cron_log.log is 126.91 MB; this exceeds GitHub's file size limit of 100 MB

To https://github.com/slinds(omited_here)/linexxxx(omited_here).git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://github.com/slinds(omited_here)
```

I then tried things like

```<code>git rm cron_log.log
git rm --cached cron_log.log
</code>```

Same error.

答:
The actual limit for each file on GitHub is 100 MiB, not 100 MB.

Demo: https://github.com/Franck-Dernoncourt/github-max-file-size

https://help.github.com/articles/what-is-my-disk-quota/  (mirror) erroneously claims that they place a strict limit of files exceeding 100 MB in size

The confusion between MB and MiB can be seen when pushing: in the example below, the error message from GitHub server indicates the file is 101 MB whereas git correctly indicates it is 101 MiB:

```<code>~\Documents\GitHub\test123 [master ↑1 +3 ~0 -0 !]> git push
Counting objects: 3, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 101.03 MiB | 896.00 KiB/s, done.
Total 3 (delta 1), reused 0 (delta 0)
remote: Resolving deltas: 100% (1/1), completed with 1 local objects.
remote: error: GH001: Large files detected. You may want to try Git Large File S
torage - https://git-lfs.github.com.
remote: error: Trace: e9206a9cd05c4ff5de79bba9d4caf9df
remote: error: See http://git.io/iEPt8g for more information.
remote: error: File 101MB is 101.00 MB; this exceeds GitHub's file size limit of
 100.00 MB
To https://github.com/Franck-Dernoncourt/test123.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://github.com/Franck-Dernoncourt/test12
3.git'
~\Documents\GitHub\test123 [master ↑1 +3 ~0 -0 !]>
</code>```

Body:
How does this change as of June 18, 2013 affect my existing repository with a file that exceeds that limit? I last pushed 2 months ago with a large file.

I have a large file that I have removed locally but I can not push anything now. I get a "remote error" ... remote: error: File cron_log.log is 126.91 MB; this exceeds GitHub's file size limit of 100 MB

I added the file to .gitignore after original push... But it still exists on remote (origin)

Removing it locally should get rid of it at origin(Github) right? ... but ... it is not letting me push because there is a file on Github that exceeds the limit...

https://github.com/blog/1533-new-file-size-limits

These are the commands I issued plus error messages..

git add .
git commit -m "delete cron_log.log"
git push origin master

remote: Error code: 40bef1f6653fd2410fb2ab40242bc879
remote: warning: Error GH413: Large files detected.
remote: warning: See http://git.io/iEPt8g for more information.
remote: error: File cron_log.log is 141.41 MB; this exceeds GitHub's file size limit of 100 MB
remote: error: File cron_log.log is 126.91 MB; this exceeds GitHub's file size limit of 100 MB

To https://github.com/slinds(omited_here)/linexxxx(omited_here).git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://github.com/slinds(omited_here)

I then tried things like

git rm cron_log.log
git rm --cached cron_log.log

Same error.

Body:
The actual limit for each file on GitHub is 100 MiB, not 100 MB.

Demo: https://github.com/Franck-Dernoncourt/github-max-file-size

https://help.github.com/articles/what-is-my-disk-quota/  (mirror) erroneously claims that they place a strict limit of files exceeding 100 MB in size

The confusion between MB and MiB can be seen when pushing: in the example below, the error message from GitHub server indicates the file is 101 MB whereas git correctly indicates it is 101 MiB:

~\Documents\GitHub\test123 [master ↑1 +3 ~0 -0 !]> git push
Counting objects: 3, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 101.03 MiB | 896.00 KiB/s, done.
Total 3 (delta 1), reused 0 (delta 0)
remote: Resolving deltas: 100% (1/1), completed with 1 local objects.
remote: error: GH001: Large files detected. You may want to try Git Large File S
torage - https://git-lfs.github.com.
remote: error: Trace: e9206a9cd05c4ff5de79bba9d4caf9df
remote: error: See http://git.io/iEPt8g for more information.
remote: error: File 101MB is 101.00 MB; this exceeds GitHub's file size limit of
 100.00 MB
To https://github.com/Franck-Dernoncourt/test123.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://github.com/Franck-Dernoncourt/test12
3.git'
~\Documents\GitHub\test123 [master ↑1 +3 ~0 -0 !]>


问:
How to get a video to pause, play another video, and resume to the original video
I have two videos, I want the first video to play for 10 seconds, pause, play the second video, and when the second video has stopped, return to playing the first video from where it left off. Kind of like an advert/commercial.

Currently I have two videos, that play sequentially, after the first one has completely ended. I know the solution is in the JavaScript event handler but the I can't seem to get it right.

HTML:

```<code><div class="vidBox" id="contain">

  <video id="video1" class="vid" muted controls="true" height="300" width="500">
      <source src="http://jcath-drg.s3.amazonaws.com/BigBuck.m4v" type="video/mp4">
  </video>

  <video id="video2" class="vid2" autoplay muted controls="true" style="display:none;" height="300" width="500">
    <source src="http://jcath-drg.s3.amazonaws.com/BigBuck.m4v" type="video/mp4">
  </video>

</div>
</code>```

JavaScript:

```<code>var vid = document.getElementById('video1');
vid.addEventListener("ended", hideVideo, false);

function hideVideo() {
    var vid = document.getElementById('video1');
    var vid2 = document.getElementById('video2');
    vid.removeEventListener("ended", hideVideo, false);
    vid.style.display='none';
    vid2.style.display='block';
}
</code>```

答:
Here is one solution, tested on chrome, safari, firefox: (I changed the second video to be able to tell if it is working, but you can set the one you want of course):</p>

```<code><!DOCTYPE html>
<html>

<head>
</head>
<body>

<div class="vidBox" id="contain">

  <video id="video1" class="vid" muted controls="true" height="300" width="500" autoplay>
      <source src="http://jcath-drg.s3.amazonaws.com/BigBuck.m4v" type="video/mp4">
  </video>

  <video id="video2" class="vid2" autoplay muted controls="true" style="display:none;" height="300" width="500">
    <source src="myVideo3.mp4" type="video/mp4">
  </video>

</div>

<script type="text/javascript">
var vid = document.getElementById('video1');
vid.addEventListener("ended", hideVideo, false);

function hideVideo(event) {
    console.log("hideVideo");
    var vid = document.getElementById('video1');
    vid.pause();
    vid.style.display='none';
    vid.removeEventListener("ended", hideVideo, false);

    var vid2 = document.getElementById('video2');
    vid2.style.display='block';
    vid2.addEventListener("ended", hideVideo2, false);
    vid2.load();
}

function hideVideo2(event) {
    console.log("hideVideo2");
    var vid2 = document.getElementById('video2');
    vid2.style.display='none';

    var vid = document.getElementById('video1');
    vid.style.display='block';
    vid.play();
}

// start timer in milliseconds
setTimeout( hideVideo, 10000);

</script>

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

Body:
I have two videos, I want the first video to play for 10 seconds, pause, play the second video, and when the second video has stopped, return to playing the first video from where it left off. Kind of like an advert/commercial.

Currently I have two videos, that play sequentially, after the first one has completely ended. I know the solution is in the JavaScript event handler but the I can't seem to get it right.

HTML:

  <video id="video1" class="vid" muted controls="true" height="300" width="500">
      <source src="http://jcath-drg.s3.amazonaws.com/BigBuck.m4v" type="video/mp4">
  </video>

  <video id="video2" class="vid2" autoplay muted controls="true" style="display:none;" height="300" width="500">
    <source src="http://jcath-drg.s3.amazonaws.com/BigBuck.m4v" type="video/mp4">
  </video>

JavaScript:

var vid = document.getElementById('video1');
vid.addEventListener("ended", hideVideo, false);

function hideVideo() {
    var vid = document.getElementById('video1');
    var vid2 = document.getElementById('video2');
    vid.removeEventListener("ended", hideVideo, false);
    vid.style.display='none';
    vid2.style.display='block';
}

Body:
Here is one solution, tested on chrome, safari, firefox: (I changed the second video to be able to tell if it is working, but you can set the one you want of course):

<!DOCTYPE html>
<html>

<head>
</head>
<body>

<div class="vidBox" id="contain">

  <video id="video1" class="vid" muted controls="true" height="300" width="500" autoplay>
      <source src="http://jcath-drg.s3.amazonaws.com/BigBuck.m4v" type="video/mp4">
  </video>

  <video id="video2" class="vid2" autoplay muted controls="true" style="display:none;" height="300" width="500">
    <source src="myVideo3.mp4" type="video/mp4">
  </video>

</div>

<script type="text/javascript">
var vid = document.getElementById('video1');
vid.addEventListener("ended", hideVideo, false);

function hideVideo(event) {
    console.log("hideVideo");
    var vid = document.getElementById('video1');
    vid.pause();
    vid.style.display='none';
    vid.removeEventListener("ended", hideVideo, false);

    var vid2 = document.getElementById('video2');
    vid2.style.display='block';
    vid2.addEventListener("ended", hideVideo2, false);
    vid2.load();
}

function hideVideo2(event) {
    console.log("hideVideo2");
    var vid2 = document.getElementById('video2');
    vid2.style.display='none';

    var vid = document.getElementById('video1');
    vid.style.display='block';
    vid.play();
}

// start timer in milliseconds
setTimeout( hideVideo, 10000);

</script>

</body>
</html>


问:
Sending data from JavaScript to PHP via XMLHttpRequest
Good day.

I'm trying to send a simple piece of data from one php file (manage.php) to another (view.php).

I cannot send the data via a form, I want to send it via a JS script. Here's my attempt:

var read = function(id) {
  xmlhttp = new XMLHttpRequest();

  xmlhttp.open("POST", "view.php", true);
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlhttp.send("id=" + id);
}```

In view.php, using $_POST["id"] causes an error stating that the index "id" is undefined.

What's the correct way to send the data? Thank you.

答:
```<code>        <!DOCTYPE html>
    <html>
    <head>
      <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    </head>
    <body>
        <form id="formoid" title="" method="post">
            <div>
                <label class="title">First Name</label>
                <input type="text" id="name" name="name" >
            </div>
            <div>
                <label class="title">Name</label>
                <input type="text" id="name2" name="name2" >
            </div>
            <div>
                <input type="submit" id="submitButton"  name="submitButton" value="Submit">
            </div>
     </form>
    <script type='text/javascript'>
        /* attach a submit handler to the form */
        $("#formoid").submit(function(event) {

          /* stop form from submitting normally */
          event.preventDefault();

          $.ajax({
    type: 'POST',
    data: id,
    url: 'PATH_TO_VIEW.PHP',
    success: function(data) {
        //do something
    },
    error: function(data){
        console.log('Something went wrong.');
    }
});
        });
    </script>

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

<p>Now the data in ajax can be collected numerous e.g. serialized and new FormData(form) to quickly name two. </p>

Body:
Good day.

I'm trying to send a simple piece of data from one php file (manage.php) to another (view.php).

I cannot send the data via a form, I want to send it via a JS script. Here's my attempt:

var read = function(id) {
  xmlhttp = new XMLHttpRequest();

  xmlhttp.open("POST", "view.php", true);
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlhttp.send("id=" + id);
}

In view.php, using $_POST["id"] causes an error stating that the index "id" is undefined.

What's the correct way to send the data? Thank you.

Body:
        <!DOCTYPE html>
    <html>
    <head>
      <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    </head>
    <body>
        <form id="formoid" title="" method="post">
            <div>
                <label class="title">First Name</label>
                <input type="text" id="name" name="name" >
            </div>
            <div>
                <label class="title">Name</label>
                <input type="text" id="name2" name="name2" >
            </div>
            <div>
                <input type="submit" id="submitButton"  name="submitButton" value="Submit">
            </div>
     </form>
    <script type='text/javascript'>
        /* attach a submit handler to the form */
        $("#formoid").submit(function(event) {

          /* stop form from submitting normally */
          event.preventDefault();

          $.ajax({
    type: 'POST',
    data: id,
    url: 'PATH_TO_VIEW.PHP',
    success: function(data) {
        //do something
    },
    error: function(data){
        console.log('Something went wrong.');
    }
});
        });
    </script>

    </body>
    </html>

Now the data in ajax can be collected numerous e.g. serialized and new FormData(form) to quickly name two.